您好,我最近得到了一块 Arduino Uno 板,我正在尝试在板上运行秒表功能。我有两个瞬时按钮。当按下第一个按钮时,它会将自程序开始使用 millis() 函数以来经过的时间量存储在 startTime 变量中。当稍后按下第二个按钮时,它还会使用相同的 millis() 函数将自程序开始运行以来经过的时间量存储在 endTime 变量中。然后,它通过从结束时间中减去开始时间来计算已用时间。

我在中间使用了 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);
  }
}

如果有人能帮助我,我将非常感激,因为我多年来一直尝试解决这个问题并采取了许多不同的方法。

有帮助吗?

解决方案

变量的声明是在 loop(). 。这意味着每次 loop() 由 Arduino 库调用,这些变量可以包含任意值,这些值可能与它们在 loop() 最后被呼叫。将声明移至模块作用域(在其之外和之前) loop())以便它们只被创建一次。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top