Not having fun/luck with ESP-8266 12E

Hi,

I am trying to configure an ESP-8366 12E to trigger a relay. I have no clue what I am doing wrong but I simply cannot make it fire one of the pins as intended.

Here is my simple code:

const int relay1Pin = 3; 
const int relay2Pin = 4; 
const int ledPin = 2; 


void setup() {
  // initialize digital pin ledPin as an output.
  pinMode(ledPin, OUTPUT);
  pinMode(relay1Pin, OUTPUT);
  pinMode(relay2Pin, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(ledPin, HIGH);   
  delay(100);                       
  digitalWrite(ledPin, LOW);   
  delay(100);                       
  digitalWrite(ledPin, HIGH);  
  delay(100);                       
  digitalWrite(ledPin, LOW);   
  delay(100);                       
  digitalWrite(ledPin, HIGH);  
  delay(100);                       
  digitalWrite(ledPin, LOW);   
  delay(100);                       
  digitalWrite(ledPin, HIGH);  
  delay(100);                       

  digitalWrite(relay1Pin, HIGH);   
  delay(500);                       
  digitalWrite(relay2Pin, HIGH);   
  delay(1000);                       

  digitalWrite(ledPin, LOW);   
  delay(500);                       
  digitalWrite(relay1Pin, LOW);  
  delay(500);                       
  digitalWrite(relay2Pin, LOW);  
  delay(1000);                       
  
}

It is a very simple code to make the LED blink a few times and then trigger relays. I am using 2-relay module for this setup.

When I run this same code on Arduino Nano (changed led pin to 13), it works fine. LED flashed a few times and then both relays are triggered.

When I load it onto ESP, LED and Relay one trigger at the same time (same frequency). Relay 1 is not triggered at its intended frequency and Relay 2 does not trigger at all.

My hardware setup is pretty simple as well. It is simply to trigger the relays with nothing attached. I have attached images.

ESP unit itself seems to be working fine because if I load a wifi sketch, it will connect and acquire IP address. Just won't fire pins. I have been at this for a couple of weeks now. :frowning:

Thank you.

Here is the hardware setup

What type of relays are you using? Arduino uses 5V logic and the ESP uses 3.3V - if the relays need 5V to activate that may be your problem.

I've inlined your images here:

On an ESP (nodeMCU as you have) the GPIO pin nrs are there ones declared in the sketch, but they are not the same as the numbers printed on the board. Check the pinout

You have connected the Relay to pins D3 & D4 those are GPIO0 & GPIO2 so either change that in you sketch or change the way you connect the relay (a bit of both would actually be best, i would not want to use GPIO3 because it is the RX pin and GPIO0 is a pin that can not be pulled low during startup or the unit will go into FlashMode

Deva_Rishi:
On an ESP (nodeMCU as you have) the GPIO pin nrs are there ones declared in the sketch, but they are not the same as the numbers printed on the board. Check the pinout

Yes, using the constants D2, D3 and D4 would eliminate this "issue".

I'm finding it hard to follow all of your wires.

It seems like you need the following:

Breadboard power adapter 5V -> VIN/VCC on relay and to VIN/VCC on esp (assuming your esp module has a built in 3v reg !important).

Breadboard negative -> GND on esp and relay.

Now your relay is probably 5v, so you can't just connect it to a digital pin on your esp as those are all rated at 3.3v. This means, you'll probably have to trigger it via a transistor.

Something like:

If you don't have a npn transistor you can also use a mosfet.

Whether or not you've hurt your pins by feeding it too high of a voltage is another thing.

Please take what I've said with a grain of salt. I might not be entirely correct. If I am wrong, anyone can feel free to correct me.

Have you tried a multimeter on pin 4 to confirm it changes from 0 to 1 (0V to 3V3)? Better still an oscilloscope. A resistor in series with an LED to ground would be good too.

I found the pin out of the ESP8266s I have (different to yours) confusing. Maybe the outputs are not on the pins you think they are.

PerryBebbington:
I found the pin out of the ESP8266s I have (different to yours) confusing.

My nodeMCU is one of those early ones that's exactly the same width as a breadboard (is that v0.9 maybe,not sure), that is to say 2 pins too wide to be able to use it. So seeing as I had to mount it on 2x mini breadboards, I then stuck those on a bit of hardboard and glued the pin diagram to the back of that: it's the only way I can ever fathom out how to connect the bloody thing.

Hi all,

Thank you for your replies and suggestions. Here are a few of the answers to the questions raised.

My MCU and Relays are 5v. I was not aware that MCU gives out 3.3v on the pins. This could be one of my issues for sure. I have never worked with mofset or npn resisters so need to look these up and figure out which one I need ad ebay shows a boat load of different ones.

Another issue I see if probably the pin numbers as suggested above. Since I have worked with arduinos only and pin numbering on the board has not been an issue, I thought this would be same for MCU as well. I will check the image mentioned above and also see if I can check it with multi-meter. I, unfortunately, do not have an oscilloscope. Yes, I have LEDs and resisters that I could use to test this as well. Thanks for the suggestion.

Hardware-setup wise it is pretty simple. Since MSU to as wide as the middle pins of the breadboard, I am using two breadboards. This fits perfectly and leaves me with enough room to attach wires. Breadboard rails are fed through power supply set to 5v.

I will come back with my findings.

In order to fix the pin numbering issues, try this:

const int relay1Pin = D3;
const int relay2Pin = D4;
const int ledPin = D2;

A nice, cheap allround NPN transistor could be a BC337. The transistor needs to be in a "common emitter" (+5V switch) setup and not the "common collector" (GND switch) as the diagram in #5 shows. Alternatively you could look for a "logic level shifter" which will convert 3.3V logic to 5V and vice versa.

Unfortunately, do not have an oscilloscope

If you are serious about electronics as a hobby buy an oscilloscope. If you don't have a clue what to buy then either search these forums for advice (the subject has been discussed) or buy a cheap one. A cheap one will teach you 2 things: It will teach you how useful they are and it will teach you what features you need on a decent on. Then buy a more expensive one. Mine cost me about £250 for a duel input. 4 input would have been worth the extra cost however.

Danois90:
In order to fix the pin numbering issues, try this:

const int relay1Pin = D3;

const int relay2Pin = D4;
const int ledPin = D2;




A nice, cheap allround NPN transistor could be a BC337. The transistor needs to be in a "common emitter" (+5V switch) setup and not the "common collector" (GND switch) as the diagram in #5 shows. Alternatively you could look for a "logic level shifter" which will convert 3.3V logic to 5V and vice versa.

Thank you for the quick fix. I shall try it. I saw it in a couple of place but thought it was in error as we are defining the const as an int but assigning a string value. I am extremely new to electronics so don't even know what logic level shifter is. I will, however, check it out and order some BC337s as well. Thanks.

PerryBebbington:
If you are serious about electronics as a hobby buy an oscilloscope. If you don't have a clue what to buy then either search these forums for advice (the subject has been discussed) or buy a cheap one. A cheap one will teach you 2 things: It will teach you how useful they are and it will teach you what features you need on a decent on. Then buy a more expensive one. Mine cost me about £250 for a duel input. 4 input would have been worth the extra cost however.

Thank you Perry. I will check it out. Since I am very new to this hobby, I am still collecting tools and equipment. I will look into getting one of these as well. Thank you.

If your Relay board is of the type that i suspect it is (the type that includes an optocoupler) you can also modify it to take a 3.3v logic level by bypassing 1 of the 2 resistors (per channel) but to guide you with this you'll need a multimeter and we need a good close-up picture of the relay board (without the wires connected, they're obstructing the view) Either way GPIO 0 is only usable as an output if the output is active-high which this relay board probably isn't.

OP's project worked for me first time at bat. The builtin led blinks, and both relays switch. (I have a LoLin nodeMCU and the exact same relay module.)

I used this code (OP's, but note pin definitions):

// https://forum.arduino.cc/index.php?topic=636314

const int relay1Pin = D5; //aka 14
const int relay2Pin = D6; //aka 12
const int ledPin = D4; //aka 2, built in on nodemcu


void setup() {
  // initialize digital pin ledPin as an output.
  pinMode(ledPin, OUTPUT);
  pinMode(relay1Pin, OUTPUT);
  pinMode(relay2Pin, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(ledPin, HIGH);   
  delay(100);                       
  digitalWrite(ledPin, LOW);   
  delay(100);                       
  digitalWrite(ledPin, HIGH); 
  delay(100);                       
  digitalWrite(ledPin, LOW);   
  delay(100);                       
  digitalWrite(ledPin, HIGH); 
  delay(100);                       
  digitalWrite(ledPin, LOW);   
  delay(100);                       
  digitalWrite(ledPin, HIGH); 
  delay(100);                       

  digitalWrite(relay1Pin, HIGH);   
  delay(500);                       
  digitalWrite(relay2Pin, HIGH);   
  delay(1000);                       

  digitalWrite(ledPin, LOW);   
  delay(500);                       
  digitalWrite(relay1Pin, LOW); 
  delay(500);                       
  digitalWrite(relay2Pin, LOW); 
  delay(1000);                       
 
}

I took 5V from the nodeMCU's "VV" pin to the relay module's Vcc, with the Jdd-Vcc jumper in place. (edit: nodeMCU powered from laptop USB.)

3V3 on the digital output to the opto's led cathode (relay module INx) is evidently high enough to turn the opto-led off (it has 5V on its anode, from the relay module Vcc (originally from nodeMCU VV).

When I get a gap I'll test it again with the jumper off and an external 5V supply, with no ground between the nodeMCU and the relay module.

UPDATE to previous:

First I ran exactly as above but with nodeMCU powered off a cell phone battery pack; all good.

Then I took the Jdd-Vcc jumper off, and removed the ground between the nodeMCU and the relay module. With no external power connected to the relay module, the relay module leds indicated correctly but of course the relays didn't activate. That's as one would expect: the relay indicator leds are across Vcc (nodeMCU VV) and a low INx (on) or a high (3V3) INx (off).

Then I supplied an external 5V to the relay module Jdd, and all worked perfectly.

THEN I had an idea: using the nodeMCU simply as a handy 3V3 power supply (no code doing anything), and with the jumper back on, I tried to activate the relays manually with 3V3 to the relay module Vcc, nodeMCU gnd to relay gnd, and nodeMCU gnd to relay INx as a low signal to activate.

Although I only tried to activate one of the relays at a time, only one of them ever worked! One seemed happy to activate with 3V3 on the coil and 0V signal, the other wouldn't. (Both relay indicator leds were working correctly.)

Anyway I think the upshot of the matter is that if (and it's not really clear from the photos) the OP is powering the relay coils from 3V3 that may be the problem. (Funny that OP seemed to get only one relay working at 3V3, same as I did....) That the nodeMCU signal is 3V3 is not an issue as far as I can tell: with 5V on the coils, nodeMCU digital low turns the relay on and nodeMCU digital high (3V3) turns it off.

Solution? OP should try powering the coils from the nodeMCU VV pin (which is 5V on mine) or better yet, take advantage of the opto isolation and use an external 5V.)

BTW, one thing I don't think the OP mentioned (I may have missed it though) is to say if the relay indicator leds are behaving correctly, although the relays (or one of them) are / is not switching.

Solution?OP should try powering the coils from the nodeMCU VV pin (which is 5V on mine) or etter yet, take advantage of the opto isolation and use an external 5V.)

BTW, one thing I don't think the OP mentioned (I may have missed it though) is to say if the relay indicator leds are behaving correctly, although the relays (or one of them) are / is not switching.

Bad plan !! powering the relays from the nodeMCU is a bad plan all together, Why do you think that the relayboard is activated via opto-couplers ? The idea is that the relays can be powered from a separate power source on a completely independent system from the control unit. Although there are fly-back diodes on the relay-board to prevent induction from damaging the control unit, the power requirements usually exceed what can be delivered from the regulators on the control unit, so Power the Relays via 5v and power the board with 5v on the Vin is always better, and the best is 2 separate power sources.

Hi guys,

I finally got it working. All I did was changed to Pin 6,7 and in the code changed it to D6, D7. Code seems to be working now. I did not have to use any transistors. I load the code via USB and then unplug and power everything using external power supply. My power supply is set to 5v and feeds relays and the ESP board.

I can trigger relays with voice commands using Alexa. The only item remaining is to add a momentary button to manually trigger relay in case Alexa is on holidays. I have added a momentary button to pin D5 and attached the other side of the button to the ground rail. However, it does not seem to be triggering the relay.

Unfortunately, I have gone over code multiple times without much success. Could someone please give me some pointers?

Thank you for all your help.

// Project for: Alexa Control mains light; + Button 
#include <ESP8266WiFi.h>

#define button1_Pin D5

// variables for push button control
byte button1; 
byte oldButton1 = 0;
byte button1_state = 0;

#define RELAY_PIN_1 D6
#define RELAY_PIN_2 D7

#include "fauxmoESP.h"

#define SERIAL_BAUDRATE 115200

#define WIFI_SSID "ssid"
#define WIFI_PASS "password"

#define LAMP_1 "Kitchen Light"
#define LAMP_2 "lamp two"

fauxmoESP fauxmo;

// Wi-Fi Connection
void wifiSetup() {
  // Set WIFI module to STA mode
  WiFi.mode(WIFI_STA);

  // Connect
  Serial.printf("[WIFI] Connecting to %s ", WIFI_SSID);
  WiFi.begin(WIFI_SSID, WIFI_PASS);

  // Wait
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(100);
  }
  Serial.println();

  // Connected!
  Serial.printf("[WIFI] STATION Mode, SSID: %s, IP address: %s\n", WiFi.SSID().c_str(), WiFi.localIP().toString().c_str());
}

void setup() {

  
  // Init serial port and clean garbage
  Serial.begin(SERIAL_BAUDRATE);
  Serial.println();

  // Wi-Fi connection
  wifiSetup();

  // LED
  pinMode(RELAY_PIN_1, OUTPUT);
  digitalWrite(RELAY_PIN_1, HIGH);

  pinMode(RELAY_PIN_2, OUTPUT);
  digitalWrite(RELAY_PIN_2, HIGH);

// Manual button
  pinMode (button1_Pin, INPUT);

//***  mySwitch.enableReceive(RF_RECEIVER);  // Receiver on interrupt 0 => that is pin #2

  // By default, fauxmoESP creates it's own webserver on the defined port
  // The TCP port must be 80 for gen3 devices (default is 1901)
  // This has to be done before the call to enable()
  fauxmo.createServer(true); // not needed, this is the default value
  fauxmo.setPort(80); // This is required for gen3 devices

  // You have to call enable(true) once you have a WiFi connection
  // You can enable or disable the library at any moment
  // Disabling it will prevent the devices from being discovered and switched
  fauxmo.enable(true);
  // You can use different ways to invoke alexa to modify the devices state:
  // "Alexa, turn lamp two on"

  // Add virtual devices
  fauxmo.addDevice(LAMP_1);
  fauxmo.addDevice(LAMP_2);

  fauxmo.onSetState([](unsigned char device_id, const char * device_name, bool state, unsigned char value) {
    // Callback when a command from Alexa is received. 
    // You can use device_id or device_name to choose the element to perform an action onto (relay, LED,...)
    // State is a boolean (ON/OFF) and value a number from 0 to 255 (if you say "set kitchen light to 50%" you will receive a 128 here).
    // Just remember not to delay too much here, this is a callback, exit as soon as possible.
    // If you have to do something more involved here set a flag and process it in your main loop.
        
    Serial.printf("[MAIN] Device #%d (%s) state: %s value: %d\n", device_id, device_name, state ? "ON" : "OFF", value);
    if ( (strcmp(device_name, LAMP_1) == 0) ) {
      // this just sets a variable that the main loop() does something about
      Serial.println("RELAY 1 switched by Alexa");
      //digitalWrite(RELAY_PIN_1, !digitalRead(RELAY_PIN_1));
      if (state) {
        digitalWrite(RELAY_PIN_1, LOW);
        Serial.print("LED should be off");
      } else {
        digitalWrite(RELAY_PIN_1, HIGH);
        Serial.print("LED should be on");
      }
    }
    if ( (strcmp(device_name, LAMP_2) == 0) ) {
      // this just sets a variable that the main loop() does something about
      Serial.println("RELAY 2 switched by Alexa");
      if (state) {
        digitalWrite(RELAY_PIN_2, LOW);
      } else {
        digitalWrite(RELAY_PIN_2, HIGH);
      }
    }
  });

}

void loop() {
  // fauxmoESP uses an async TCP server but a sync UDP server
  // Therefore, we have to manually poll for UDP packets
  fauxmo.handle();

  static unsigned long last = millis();
  if (millis() - last > 5000) {
    last = millis();
    Serial.printf("[MAIN] Free heap: %d bytes\n", ESP.getFreeHeap());
  }


// Manually trigger Relay using momentary push button

// Read Button
button1 = digitalRead(button1_Pin);

// Following code is used to switch button state. Input is received from a momentary push button. 
if(button1 && !oldButton1) // same as if(button1 == high && oldButton1 == low)
 {
   //we have a new button press
   if(button1_state == 0) // if the state is off, turn it on
   {
     //do stuff
     button1_state = 1;
     digitalWrite(RELAY_PIN_1, LOW);
     Serial.print("LED should be on from Switch");
     
   }
   else // if the state is on, turn it off
   {
     //do stuff
     button1_state = 0;
        digitalWrite(RELAY_PIN_1, HIGH);
        Serial.print("LED should be off from switch");
   }
   oldButton1 = 1;
 }
 else if(!button1 && oldButton1) // same as if(button == low && oldButton == high)
 {
   // the button was released
   oldButton1 = 0;
 }  
}

start with changing this pinMode (button1_Pin, INPUT);INPUT to INPUT_PULLUP or add a pull up resistor to the switch