簡體   English   中英

ESP8266 循環錯誤

[英]ESP8266 looping errror

我是 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();
  }
}

循環內的while loop使基本的后台功能餓死。 在該循環中添加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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM