Magnetic door sensor

Hello. I’ve made a code to open/close the garage door that works great, but I’d also like to add a magnetic sensor. I’m currently trying to make the code work only for the magnetic sensor,but I can’t make it work. The code is supposed to show 1 or 0 in a value display widget inside Blynk, depending on the state. Here’s the code:

int door;
BlynkTimer timer;

void setup()
{
  // Debug console
  Serial.begin(9600);
  pinMode(D0,INPUT_PULLUP);
  Blynk.begin(auth, ssid, pass);
  timer.setInterval(1L,stagiu);
}

void stagiu(){
  if(digitalRead(D0)==HIGH){
    
      door=1;
      Blynk.virtualWrite(V0,door);
      Serial.print("CLOSED");
  }
  else if(digitalRead(D0)==LOW){
    
      door=0;
      Blynk.virtualWrite(V0,door);
      Serial.print("OPENED");
}
}
void loop()
{
  Blynk.run();
  stagiu();
}

It reads the value only once because of the “stagiu” function in the loop. The timer doesn’t do anything

For the BlynkTimer to run, you need timer.run(); in your void loop.

This:

will call your stagiu function one thousand timer per second. If you want to call it once per second then the interval needs to be 1000L (once every 1000 milliseconds).

This line should be deleted from your void loop:

Pin D0 (GPIO16) isn’t the best pin to use.
Read this:

Pete.

I’m using D0 as I have a LED feedback. I’ve made the changes, still the same result.

void setup()
{
  // Debug console
  Serial.begin(9600);
  pinMode(D0,INPUT_PULLUP);
  Blynk.begin(auth, ssid, pass);
  timer.setInterval(1000L,stagiu);
}


void stagiu(){
  if(digitalRead(D0)==HIGH){
    
      Blynk.virtualWrite(V0,door);
      door=1;
      Serial.print("CLOSED");
  }
  else if(digitalRead(D0)==LOW){
    
      Blynk.virtualWrite(V0,door);
    door=0;
      Serial.print("OPENED");
}
}
void loop()
{
  Blynk.run();
  timer.run();
}

It only works one time

//Seems like the pin was the problem, changed it to D1 and it works fine :slight_smile:

1 Like

image

Pete :grinning:

5 Likes