c++ - Arduino Uno 代码创建不正确的时间值

标签 c++ c arduino arduino-uno

你好,我有一 block Arduino Uno 开发板,我最近拿到了,我想在开发板上运行一个秒表功能。我有两个瞬时按钮。当按下第一个按钮时,它会将自程序开始使用 millis() 函数以来耗时量存储在 startTime 变量中。当稍后按下第二个按钮时,它还会使用相同的 millis() 函数在 endTime 变量中存储自程序开始运行以来耗时量。然后,它通过将 startTime 减去 endTime 来计算 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);
  }
}

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

最佳答案

变量的声明在loop()中执行.这意味着每次 loop()由 Arduino 库调用,这些变量可以包含任意值,这些值可能与它们在 loop() 时的值相同,也可能不同。最后被调用。将声明移至模块范围(在 loop() 之外和之前),以便它们只创建一次。

关于c++ - Arduino Uno 代码创建不正确的时间值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23050491/

相关文章:

python - 将JSON字符串从zmq(C)传输到Python问题

c++ - 用于与 arduino 进行串行通信的 struct termios 设置

c# - 非托管库中的堆栈溢出导致 .NET 应用程序崩溃

c++ - 类属性包括模板类的实例(错误 C3857)

c++ - AFX_MANAGE_STATE(AfxGetStaticModuleState()) 究竟做了什么

c++ - 程序集:C++ 堆栈变量地址不同/错误?

c - 如何用变量指定字段宽度?

c - 接受位域值的函数 arg 使用什么类型

c++ - Arduino - 蚕食整数函数不稳定的结果

class - 从 Arduino 中的库调用主程序中的函数