I am new to the NodeMCU ESP8266 board and and been playing around with it am a little stumped as to what my issue within this code is. The code works on Arduino and was originally written for an Arduino Uno, but when I tried it on a ESP8266 board I get a serial monitor error? I think it has something to do with how I am looping at the bottom, but not sure thanks for any help.
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();
}
}
Your while
loop inside the loop
starves the essential background functions. Add yield()
inside that loop to give control temporarily back to the underlying framework.
while (onTime < timer) {
yield(); // Do (almost) nothing -- yield to allow ESP8266 background functions
...
}
There are some great explanations at https://stackoverflow.com/a/34498165/131929
The ESP8266 runs a lot of utility functions in the background -- keeping WiFi connected, managing the TCP/IP stack, and performing other duties. Blocking these functions from running can cause the ESP8266 to crash and reset itself. To avoid these mysterious resets, avoid long, blocking loops in your sketch.
Source: https://learn.sparkfun.com/tutorials/esp8266-thing-hookup-guide/using-the-arduino-addon
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.