Porting from Nano to ESP8266

I have just completed my first project which monitors 2 PIRs and a Reed switch and outputs to a linear actuator via double relay.

Is it possible to use the same code on ESP8266, so that I can add some remote WiFi control, using the Blynk app? I'd like to be able to manually override the relay using Blynk and also use the time from the router to make the system dormant at night.

This is the code I have used on the Nano, will this run on ESP8266? I understand that I will need to add more code to deploy the Wifi Blynk, but was hoping I could get some general guidance here.

[code]
const int relay1 = 2; //drives linear actuator to open flap
const int relay2 = 3; //drives linear actuator to close flap
const int pIR1 = 5; //outputs HIGH signal when motion detected
const int pIR2 = 6;  //outputs HIGH signal when motion detected
const int doorSensor = 4; //outputs HIGH is closed - reed switch
const unsigned long flapOpenTime = 30000; //in addition to timing of piR pot
unsigned long previousTime = 0;
void openFlap();
void closeFlap();
enum _state_enum
{
  IDLE,
  MONITOR_DOOR_CLOSED,
  CMD_OPEN_FLAP,
  MONITOR_OPEN_FLAP,
  CMD_CLOSE_FLAP,
};
_state_enum systemState = IDLE;
int lastPIR1Status;
int lastPIR2Status;
byte doorSensorStatus;
void turnOFF();


void setup() {
  delay (30000); // wait for PIR modules to stabalize
  pinMode(relay1, OUTPUT);// set pin as output for relay 1
  pinMode(relay2, OUTPUT);// set pin as output for relay 2
  pinMode(pIR1, INPUT);
  pinMode(pIR2, INPUT);
  pinMode(doorSensor, INPUT_PULLUP);
  //turnOFF();
  lastPIR1Status = digitalRead(pIR1);
  lastPIR2Status = digitalRead(pIR2);
  doorSensorStatus = digitalRead(doorSensor);
  closeFlap();
  Serial.begin(9600);// initialize serial monitor with 115200 baud
}


void loop() {

  byte pIR1Status = digitalRead(pIR1);
  byte pIR2Status = digitalRead(pIR2);
  int doorSensorStatus = digitalRead(doorSensor);
  unsigned long currentTime = millis();


  switch (systemState)
  {
    // Wait for motion
    case IDLE:
      Serial.println ("IDLE");
      Serial.print ("pIR1Status (last/Current)= ");
      Serial.print (lastPIR1Status);
      Serial.print ("/");
      Serial.println(pIR1Status);
      Serial.print ("pIR2Status (last/Current)= ");
      Serial.print (lastPIR2Status);
      Serial.print ("/");
      Serial.println(pIR2Status);
      Serial.print ("doorSensorStatus = ");
      Serial.println(doorSensorStatus);
      Serial.println ("***********************");

      // If either PIR sensor went from LOW to HIGH then open the flap
      if ((((pIR1Status != lastPIR1Status) && pIR1Status == 1 && (doorSensorStatus) != 1)
           ||  ((pIR2Status != lastPIR2Status) && pIR2Status == 1 && (doorSensorStatus) != 1)))

      {
        systemState = CMD_OPEN_FLAP;
        previousTime = currentTime;
      }

      break;

    case MONITOR_DOOR_CLOSED:
      Serial.println ("MONITOR_DOOR_CLOSED");
      if (doorSensorStatus == 0)
      {
        systemState = CMD_CLOSE_FLAP;
      }
      break;

    case CMD_OPEN_FLAP:
      Serial.println ("CMD_OPEN_FLAP");
      openFlap();
      systemState = MONITOR_OPEN_FLAP;
      break;

    case MONITOR_OPEN_FLAP:
      Serial.println ("MONITOR_OPEN_FLAP");
      Serial.print ("elapsed time = ");
      Serial.println (currentTime - previousTime);
      Serial.print (lastPIR1Status);
      Serial.println(pIR1Status);
      Serial.print (lastPIR2Status);
      Serial.println(pIR2Status);
      Serial.print ("doorSensorStatus = ");
      Serial.println(doorSensorStatus);
      Serial.println ("***********************");
      if ((pIR1Status == 0 && pIR2Status == 0) && (currentTime - previousTime >= flapOpenTime))
      {
        systemState = CMD_CLOSE_FLAP;
      }
      break;

    case CMD_CLOSE_FLAP:
      Serial.println ("CMD_CLOSE_FLAP");
      closeFlap();
      systemState = IDLE;

      break;

  }
  lastPIR1Status = pIR1Status;
  lastPIR2Status = pIR2Status;

}
//
//   when the actuator is pushed, it closes the flap
//
void openFlap()
{
  digitalWrite(relay1, LOW);// turn relay 1 ON
  digitalWrite(relay2, HIGH);// turn relay 2 OFF
}//openFlap()
void closeFlap()
{
  digitalWrite(relay1, HIGH);// turn relay 1 OFF
  digitalWrite(relay2, LOW);// turn relay 2 ON
}//closeFlap()

// void turnOFF()
//  {
//  digitalWrite(relay1, HIGH);// turn relay 1 OFF
//  digitalWrite(relay2, HIGH);// turn relay 2 OFF
//  }//turnOFF()

[/code]

Yep, that should all run fine on esp8266. There’s nothing there that’s specific to Nano or any particular chip. Obviously you will need to change the pin numbers listed at the top of the sketch to match the connections in your new circuit. Hint: if you connect a relay to the pin marked “D6”, put “D6” in the sketch too, for example:

const int relay1 = D6; //drives linear actuator to open flap

Do you already have an esp8266 of some kind? If not, I would recommend a wemos d1 mini. The "lite" version also fine. But if you have very weak wifi signal in the place the esp will be, maybe get the "pro" version. With that version, and a rather tricky bit of fine soldering, you can configure it to use an external wifi antenna with a higher gain.

Please post a schematic for your Nano circuit and links to the components like the relay modules and pir sensors, so we can advise any problems with updating it for esp. For example, esp is a 3.3V device and could be damaged by 5V signals.

Which ESP8266? There must be dozens of variants.

You can't use the same pins. On the ESP pin 3 is Serial RX (pin 1 is TX). ESP Pin 2 needs to be HIGH during reset (see Beginner's guide to ESP8266).

The ESP outputs are 3.3V with 10mA recommended max current. Can that output drive control the relays?

With any esp8266, you do have to be a little careful about which pins you attach sensors to. Certain pins control whether the esp boots into "normal", "sketch upload" and other modes, for example, which can catch beginners out. Also pin D0 is a little odd and has some special functions relating to battery-saving "deep sleep" mode, so don't use that if you can avoid it.

I would recommend a wemos d1 mini.

Agreed.

Thank you for your replies. I have already bought 3 units of AZ Delivery
NodeMCU V2 WiFi Lua Amica ESP8266 ESP-12F I2C Development Board CP2102 3.3V

I am working on preparing a schematic on Fritz (first attempt!) so I will upload as soon as I have this completed.

UPDATE **** here it is- not pretty, but tbh I find fritzing a painful experience!
link to Fritzing Breadboard image

OK, but the NodeMCU is just a somewhat more expensive version of the D1 Mini. Little difference in practice apart from being larger.

joatmon13:
I am working on preparing a schematic on Fritz (first attempt!) so I will upload as soon as I have this completed.

PLEASE NOOOO!

Pretty Fritzing pictures are NOT schematics.

There is little similarity between a circuit diagram and Fritzing. The use of the latter is just trying to dumb it down to “Lego” building blocks and the user learns nothing useful. Then when they are looking for help and support, those pictures are presented which we have to try to follow.

Some of us won’t even look at Fritzing pictures as it’s an effort to mentally construct a schematic, which is why we prefer a schematic. No matter how crude.

SteveMann:
PLEASE NOOOO!

Wish I had seen this earlier - just spent 2 frustrating hours trying to create in Fritzing!!
What other simple tool do you recommend for schematic

What other simple tool do you recommend for schematic

Paper and pencil/pen.

After your draw it out, take a photo of the schematic with your phone and attach it to your post.

Does not Fricktzing have a facility for a schematic? :astonished:

Paul__B:
Does not Fricktzing have a facility for a schematic? :astonished:

It's pretty pathetic. I prefer a pencil schematic on the back of an envelope. The Fritzing schematic often doesn't follow most customary schematic practices. You will find grounds on top, Vcc on the bottom and no effort to not cross lines.

SteveMann:
The Fritzing schematic often doesn't follow most customary schematic practices. You will find grounds on top, Vcc on the bottom and no effort to not cross lines.

That's entirely due to poor drawing skills on the part of the user, nothing to do with Fritzing's schematic editor. The same users would make the same mistakes with any schematic drawing app.

joatmon13:
Wish I had seen this earlier - just spent 2 frustrating hours trying to create in Fritzing!!

Do not despair! Simply switch from breadboard view to schematic view within Fritzing. All your components will be there, and a rat's nest of wires showing what you connected on the breadboard view. Now you can arrange your components and re-draw the connections neatly.

In a schematic drawing, you don't need to arrange your components in a way that reflects the physical layout of the circuit, you can arrange them any way you like to make the connections clear and easy to follow, avoiding crossing connections as much as you can, for example.

A really good tip for drawing a clear schematic is to use the "power" symbols such as "5V", "3V3" and "GND". Use these as many times as you like, anywhere on the diagram, near any components that need them. That means you dont need to draw in the power and ground lines between components, just connect each component directly to nearby power connectors.

OK - I have taken another try at Fritzing using the Schematic mode. I have attached the schematic as I can't seem to be able to embed it here in the post.

I couldn't find a regular 3 pin PIR part, so had to make do with a version someone created which looks ok in BB view but is incorrect on Schematic view. I'm sure there are other rooky mistakes in my diagram, but I hope it shows what I have done and backs up the code. Similarly couldn't find 2 circuit relay. Either I am going blind, or Fritzing seems to have a deficit of common parts in its library.

So to get back on point, I want to swap the Nano for a ESP8266 so that I can
a) track time of day and elect to have the system dormant at night and
b) make it WiFi accessible so we can override the automation to open the flap
c) remotely observe the status of the flap, is it open or closed.

I was planning on using Blynk, but happy to take recommendations.

Specifically, I have some questions:-

  1. I'm using digital Pins 2,3,4,5,6 in the Nano - can I just swap those to the same numbers in ESP8266?

  2. The relays require 5v as do the PIR's. This is supplied from the buck converter, which is powered from a 30amH battery, which also supplies the linear actuator. Could I use resistors to reduce voltage for the ESP8266, that will provide sufficient current? What value resisters?

Thank you for your assistance.

One step at a time...
So the PIR you're using is rated at 5v. You can bypass the onboard regulator to use it at 3v3 with a ESP8266. Some of them even have jumpers to do this

myiot23:
One step at a time...
So the PIR you're using is rated at 5v. You can bypass the onboard regulator to use it at 3v3 with a ESP8266. Some of them even have jumpers to do this

thank you, myiot23. If I understand you correctly, you can modify the wiring on the PIRs own onboard regulator to bypass it so that it will run at 3.3v . Can you point to any tutorial which clearly sets out how this can be done. (I found this example but it's more confusing than helpful Convert a 5v PIR Motion Sensor to 3.3v for ESP8266 - Instructables)

Secondly, any suggestions about the relays? They need 5v. Is there such a thing as a dual voltage buck converter?

The 5V relays were/would be a mistake, whether using Nano or ESP. To switch 12V DC, always use 12V relay modules. Then you don't need to supply 5V, they can run directly from the 12V supply.

If you must use the 5V relays, use the buck converter to output 5V. Then you have 5V to power the sensors, relays and the NODEMCU. The NODEMCU has an on board 3.3V regulator.

Fritzing seems to have a deficit of common parts in its library.

Maybe that is still a valid criticism of Fritzing. It was the reason I stopped using it, some 5 years ago. I had hoped the parts library had grown a little since then...

couldn't find 2 circuit relay.

If by that you mean a dual relay module, could you not simply use 2 single relay modules? Surely Fritzing has that.

I'm using digital Pins 2,3,4,5,6 in the Nano - can I just swap those to the same numbers in ESP8266?

Yes, but be sure to call them "D2" to "D6", not simply 2 to 6, in your sketch.

Could I use resistors to reduce voltage for the ESP8266,

No, resistors won't do that. Fortunately, you are not using an ESP8266, you are using a board which contains an ESP8266, and also contains a voltage regulator which can make 3.3V from a 5V input.

PaulRB:
The 5V relays were/would be a mistake. To switch 12V DC, use 12V relay modules. Then you don't need to supply 5V, they can run directly from the 12V supply.

I guess I don't understand how you can hook up a 12v/12v relay to a board which only accepts 3v. These are the relays I bought on Amazon https://www.amazon.co.uk/kwmobile-Channel-Relay-Module-Optocoupler/dp/B01H2D2RI0. They need to be switched with 5volts. I have seen a hack using a trimmer to to replace a resister on the 5v relay to allow them operate with 3v. But as a novice, it seems strange that there are not 3v dual channel relays readily available. Alternatively, I'm think of using an old PC PSU which will deliver 12, 3.3 and 5volts. That should do away with my 12v battery and buck converter.