Open and Close a door or gate with a SONOFF BASIC R2 (new version)


Surely it is not a perfectly written code, but it is the result of copy&paste and help from other users of this community. However, the initial idea was to use a Sonoff Basic (R2 version) to open and close the door of my house.

On the new version of the Sonoff Basic (R2), they removed the GPIO14 but there is a pitch with the GPIO2. The GPIO1 and GPIO3 remain (RX and TX). By doing a lot of tests, I discovered that by connecting the magnetic switch (normally closed to GND) on the GPIO1 or GPIO2, to a possible reset of the device (or in the absence of current and restarting of it), the Sonoff went into flash mode (I think), however it did not restart. The only method from newbie (by doing some tests) was to use the GPIO3 as a magnetic contact, and insert the DHT probe on the GPIO2.

In the project (as a beginner) I noticed that the tripWire turns off the led widget a few seconds before, but not always (I still haven’t understood the operation of the various tripWire very well, maybe you can fix it by adding a delete/reset of the timer or other, but for now I like it so good).

So obviously mine is just an idea to be able to use a SONOFF BASIC R2 to open a gate or a door that are already controlled by wall buttons.

I also did a more complex program to open a gate and even stop it with a second relay, but I don’t put it because I’m ashamed of the code even more than this :smile:

Tips are obviously welcome!

#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <DHT.h>
#include <DHT_U.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>

#define DHTPIN2 2
#define DHTTYPE DHT11

char auth[] = "xxx";
char ssid[] = "xxx";
char pass[] = "xxx";

int runDays; //only for widget counting UP TIME
int runHours;
int secsRemaining;
int runMinutes;
int runSeconds;
char buf[21];
unsigned long allSeconds;

int relay1 = 12;   //relay sonoff basic active HIGH
int ledboard = 13; //led sonoff basic active LOW
int pulsante = 0;  //on board switch
int switch1 = 3;   //GPIO3 for an external magnetic switch

int relayState = HIGH;
int inMovimento = LOW;
boolean ledState = LOW;
int fast_timer_id;
int slow_timer_id;

BlynkTimer timer;
BlynkTimer tripWire;

WidgetLED led1(V2); //widget led IN MOVIMENTO
WidgetLED led3(V3); //widget led APERTO (OPEN DOOR with external magnetic contact on GPIO3)
WidgetLED ledb(V4); //widget led ONLINE DEVICE BLINKING

void setup() {
  Blynk.begin(auth, ssid, pass);
  while (Blynk.connect() == false) {
    // Wait until connected
  ArduinoOTA.onError([](ota_error_t error) { ESP.restart(); });
  timer.setInterval(30000L, sendDHT);    // Temperature sensor DHT "polling" interval.
  timer.setInterval(1005L, blinkLedB);   // Blinking led widget
  timer.setInterval(100L, pulsanteread); // Read the state of internal switch of sonoff
  timer.setInterval(201L, switchread);   // Read the state of external magnetic switch
  timer.setInterval(1000L, UpTime);      // Write on widget the UP TIME
  pinMode(relay1, OUTPUT);
  pinMode(ledboard, OUTPUT);
  pinMode(pulsante, INPUT_PULLUP);
  pinMode(switch1, INPUT_PULLUP);

  inMovimento = LOW; 
  ledStop = LOW;;;
  digitalWrite(relay1, LOW);
  digitalWrite(ledboard, ledState);
  Blynk.setProperty(V1, "color", "#FFFFFF"); //change color and label of app BOTTON for open and close door
  Blynk.setProperty(V1, "onLabel", "APRI/CHIUDI");
  Blynk.setProperty(V1, "offLabel", "APRI/CHIUDI");
  fast_timer_id = timer.setInterval(100L, fInMovimento); //timer for blink the internal led differently, fast if the door is opening or closing, slowly when waiting for a command
  slow_timer_id = timer.setInterval(1000L, fInMovimento); 

void UpTime() { 
  allSeconds = millis() / 1000;
  runDays = allSeconds / 86400;
  secsRemaining = allSeconds % 86400;
  runHours = secsRemaining / 3600;
  secsRemaining = allSeconds % 3600;
  runMinutes = secsRemaining / 60;
  runSeconds = secsRemaining % 60;
  sprintf(buf, "%02dday %02d:%02d:%02d", runDays, runHours, runMinutes, runSeconds);
  Blynk.virtualWrite(V14, buf);  // Send UpTime seconds to App

BLYNK_CONNECTED() { // For write in widget the version of blynk/core, mac address, IP of device
  Blynk.virtualWrite(V10, BLYNK_VERSION);
  Blynk.virtualWrite(V11, ESP.getCoreVersion());
  Blynk.virtualWrite(V12, WiFi.macAddress());
  Blynk.virtualWrite(V13, WiFi.localIP().toString());

BLYNK_WRITE(V1) { //switch widget for open/close door
  int read1 = param.asInt();
    if (read1 == HIGH && inMovimento == LOW) {
        digitalWrite(relay1, HIGH);
        inMovimento = HIGH;
        Blynk.setProperty(V1, "color", "#D3435C");
        Blynk.setProperty(V1, "onLabel", "IN MOVIM");
        Blynk.setProperty(V1, "offLabel", "IN MOVIM");
        tripWire.setTimeout(700L, tripDeactivateOPEN);
        tripWire.setTimeout(19000L, tripnonmovimento); // The time in ms of opening/closing the door completely

void tripDeactivateOPEN() {    
       digitalWrite(relay1, LOW);
void tripnonmovimento() {;
  inMovimento = LOW;
  Blynk.setProperty(V1, "color", "#FFFFFF");
  Blynk.setProperty(V1, "onLabel", "APRI/CHIUDI");
  Blynk.setProperty(V1, "offLabel", "APRI/CHIUDI");
void sendDHT(){ //DHT reading  
  float h2 = dht2.readHumidity();
  float t2 = dht2.readTemperature();
  if (isnan(h2) || isnan(t2)) { 
  Blynk.virtualWrite(V21, h2);
  Blynk.virtualWrite(V20, t2); 

void pulsanteread() { // Internal switch reading
    if (digitalRead(pulsante) == LOW) {
    digitalWrite(relay1, HIGH);
    inMovimento = HIGH;
    Blynk.setProperty(V1, "color", "#D3435C");
    Blynk.setProperty(V1, "onLabel", "IN MOVIM");
    Blynk.setProperty(V1, "offLabel", "IN MOVIM");
    tripWire.setTimeout(700L, tripDeactivateOPEN);
    tripWire.setTimeout(19000L, tripnonmovimento);

void switchread() { // Read magnetic switch for display on widget app the state of the door
    if (digitalRead(switch1) == LOW) {;
    } else {

void fInMovimento(void) { // Blinking of internal led out of loop()
   if ((inMovimento && timer.isEnabled(slow_timer_id)) || 
      (!inMovimento && timer.isEnabled(fast_timer_id))) {
   ledState = !ledState;
   digitalWrite(ledboard, ledState);

void blinkLedB() // Blinking of a widget led on app for online status
  if (ledb.getValue()) {;
    } else {

void loop() 


The unnecessary widget for UPTIME and IP

The modified Sonoff with the added DHT probe and the wires for external magnetic contact

The sonoff in position (I’m waiting for magnetic contact) :smile:

I received many suggestions in this community, thanks to everyone!!

1 Like


As far as the physical installation is concerned, it looks like there could be some moisture in the area, because of the switch housings, and if any moisture were to run down the wire into the wire into the Sonoff there would obviously be quite a big bang. As the Sonoff has no earth connection then moisture wouldn’t immediately cause an earth leakage situation, which could be dangerous.
I’d be tempted to put the Sonoff in a waterproof box, althoughthe DHT sensors would obviously need to be mounted externally.

Actually, I’d probably not use a Sonoff because of the limited number of pins available and the difficulty in accessing the pins easily.
I did something similar where I put an RFID reader on the outside and added the ability to release the gate using Blynk (or other methods such as a 433MHz button). I had 12v available as part of the existing gate release system, so I didn’t need a mains adapter, I just needed to step the 12v down to 5v.
More about that project here:

I’ve been thinking of adding a sensor to my system to detect when the gate isn’t properly closed, and I’d had it in my mind that this would be a microswitch, but a magnetically operated reed switch is a much neater idea.


1 Like


The switch is all inside the garage, under a roof, water cannot enter by chance. The stains you see are not humidity, but mortar to fix a old work. Before sonoff, I had a usRiot used for 5 years, but with a very ugly app. In the description I forgot to mention that obviously the output of the sonoff was modified in clean contact. For the watertight box, however, it is a good idea. Thanks

1 Like


I chose a sonoff basic because it is an All in one, with power supply and box. Then it’s true, less gpio and more uncomfortable to use, but once done, it’s pretty simple