ESP8266环路错误

2022-06-22 00:00:00 arduino c++ arduino-esp8266

我是NodeMCU ESP8266板的新手,并且一直在使用它,我对此代码中的问题感到有点困惑。代码在Arduino上运行,最初是为Arduino Uno编写的,但当我在ESP8266板上尝试它时,我得到了一个串行监视器错误?我认为这与我在底部循环的方式有关,但我不确定是否谢谢你的帮助。

const int MotionSense = D2;
const int MotionLed = D3;
const int NoMotionLed = D7;
int MotionState = 0;
int MotionCheck = 0;
int onTime = 0;
const unsigned long timerCounter = 100;
const unsigned long timer = 1000;
unsigned long prevTime = 0;

void setup() {
  pinMode(MotionLed, OUTPUT);
  pinMode(NoMotionLed, OUTPUT);
  pinMode(MotionSense, INPUT);
  Serial.begin(19200);
}

void loop() {
  //while no motion stay off
  MotionState = digitalRead(MotionSense);
  while (MotionState == LOW) {
    digitalWrite(MotionLed, LOW);
    digitalWrite(NoMotionLed, HIGH);
    MotionState = digitalRead(MotionSense);
  }
  //turn back on
  digitalWrite(MotionLed, HIGH);
  digitalWrite(NoMotionLed, LOW);


  onTime = 0;
  while (onTime < timer) {
    unsigned long currentTime = millis();
    if ((currentTime - prevTime) >= (timerCounter)) {
    MotionState = digitalRead(MotionSense);
   
    if (MotionState == HIGH){
       onTime = 0;
    } else {
       onTime +=1;
    }
    Serial.println(onTime);
    prevTime = millis();
  }
}

解决方案

您在loop内的while循环会使基本的后台函数匮乏。在该循环内添加yield(),将控制权暂时交回基础框架。

while (onTime < timer) {
  yield(); // Do (almost) nothing -- yield to allow ESP8266 background functions
  ...
}

https://stackoverflow.com/a/34498165/131929

有一些很好的解释

ESP8266在后台运行许多实用程序功能--保持WiFi连接、管理TCP/IP堆栈以及执行其他任务。阻止这些功能运行可能会导致ESP8266崩溃并重置自身。为了避免这些神秘的重置,请避免在你的草图中出现长而阻塞的循环。

来源:https://learn.sparkfun.com/tutorials/esp8266-thing-hookup-guide/using-the-arduino-addon

相关文章