Chat freely about anything...

User avatar
By naim
#78435 hello. i'm doing a project using nodemcu and magnetic door sensor. i got one problem.

#define sensor D0
int state = 0;
void setup()
{
Serial.begin(9600);
pinMode(sensor, INPUT_PULLUP);
}
void loop()
{
state=digitalRead(sensor);
if(state==LOW)
{
Serial.println("open");
}
else if(state==HIGH)
{
Serial.println("close");
}
}

when i run it, the serial print show "close". when i put the magnet close to the reed, the serial print"open".but when i put out the magnet from the reed, the serial print still show "open". then i modify the code to this:

#define sensor D0
int state = 0;
void setup()
{
Serial.begin(9600);
pinMode(sensor, INPUT_PULLUP);
}
void loop()
{
state=digitalRead(sensor);
if(state==HIGH)
{
Serial.println("open");
}
else if(state==LOW)
{
Serial.println("close");
}
}

when i run it, the serial print show "open" then i put the magnet close to the reed and the serial print show "close". but when i put out the magnet from the reed, the serial print still show "close".

i found that my code is stuck at (state==LOW)
anyone know how to fix it?