您好,我有一个最近得到的 Arduino Uno 板,我正在尝试在板上运行秒表功能。我有两个瞬时按钮。当第一个按钮被按下时,它会在 startTime 变量中存储自程序开始使用 millis() 函数以来经过的时间量。当稍后按下第二个按钮时,它还会使用相同的 millis() 函数将自程序开始运行以来经过的时间量存储在 endTime 变量中。然后它通过从 endTime 中取出 startTime 来计算 timeElapsed。
我在两者之间使用了 Serial.print 以进行调试。我得到了我期望的 startTime 和 endTime 值,它们是正确的,但是我的 elapsedTime 值似乎无法正常工作。
关于这个问题有一个线索。经过的时间旨在返回 endTime-startTime 的值。然而,它总是返回的是 endTime-773 的值。我不确定这究竟意味着什么,但我相信它可能是有用的信息,可以帮助解决我的问题。
void setup(){
Serial.begin(9600); //start the Serial.moniter on the computer
pinMode(2, INPUT); //Set the button attached to pin 2 as an input
pinMode(3, INPUT); //Set the button attached to pin 3 as an input
}
void loop(){
int buttonStateTwo = digitalRead(2); //stores either a HIGH(button pressed) or LOW(button not being pressed) value
int buttonStateThree = digitalRead(3);
unsigned int startTime;
unsigned int endTime;
unsigned int elapsedTime;
if(buttonStateTwo == HIGH){ //if the button is pressed
startTime = millis();
Serial.print(" The start time is: ");
Serial.print(startTime);
delay(1000); //pause the program for a second
}
if(buttonStateThree == HIGH){
endTime = millis();
Serial.print(" The end time is: ");
Serial.print(endTime);
elapsedTime = endTime-startTime; //this returns an incorrect value
Serial.print(" The time elapsed is: ");
Serial.println(elapsedTime); //incorrect value
delay(1000);
}
}
如果有人可以帮助我,我将非常感激,因为我已经尝试了很长时间来解决这个问题并采取了许多不同的方法。