秒表无法重置

时间:2018-01-22 18:03:31

标签: arduino-uno

我正在研制一款Arduino秒表,它需要一个启动,停止和重置按钮。要重置它,我使用一个名为starttime的变量,它被更新为等于millis(),然后取差值来显示时间。但是,过去30秒,starttime无法正确更新,starttimemillis()之间产生的差异相当于65秒。有人可以解释为什么会这样吗?

#include <LiquidCrystal.h>



LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const int start = 8;
const int stp = 9;
const int reset = 10;

int seconds;
int minutes;
int timedif;
int starttime = -1;
int timestall = 0;

bool onoff = true;

void setup()
{
  pinMode(start, INPUT);
  pinMode(stp, INPUT);
  pinMode(reset, INPUT);

    lcd.begin(16, 2); //Initialize the 16x2 LCD

    lcd.clear();    //Clear any old data displayed on the LCD

  Serial.begin(9600);
}

void loop()
{
  int bsta = digitalRead(start);//sees if start switch is pressed
  int bstp = digitalRead(stp);//records if stop switch is pressed
  int bres = digitalRead(reset);//records if reset switch is pressed
  lcd.setCursor(0,0);
  lcd.print("Stopwatch");//prints stopwatch top row
  lcd.setCursor(0,1);
  if (starttime == -1) { //if running first time, time dif is initiated
    starttime = millis();
  }

  timedif = (millis() - starttime )/1000 + timestall; //will get difference in terms of seconds

  minutes = floor(timedif/60); // divides by sixty, drops decimal
  seconds = timedif%60; //gets remainder of divided by 60
  lcd.print(minutes);
  lcd.print(":");
  lcd.print(seconds);
  if (seconds < 10) {
    lcd.setCursor(3,1);
    lcd.print(' ');
  }
  if (bstp == HIGH) {
    onoff = false;
    while(onoff == false) {
      if (digitalRead(start) == HIGH) {
        onoff = true;
      }
    }
    timestall = timedif;
    starttime = millis();
  }
  if (bres == HIGH) {
    delay(100);
    timestall = 0;
    starttime = millis();
    timedif = 0;
    lcd.clear();
    Serial.println("stall:");
    Serial.println(timestall);
    Serial.println("dif");
    Serial.println(timedif);
    Serial.println("start");
    Serial.println(millis() - starttime);


  }

}

1 个答案:

答案 0 :(得分:0)

如果long声明包含时间值的变量,则应使用unsigned longint

int变量只能保持32,767毫秒,因此32秒。其中long变量可以容纳2,147,483,647毫秒,这可能是48天。 unsigned long可以保持两倍,但不能保持负值。