ESP8266 D1 Mini upload and run code, create server bur won't turn relay on

Hello Community.

Yesterday my code worked perfectly, then made some changes on some conditions and now I still can upload both codes, and create a server in which I can interact but neither the new nor the old code turns the relay on and won't send info to the serial monitor. Here's my code:

#include <ESP8266WiFi.h>                   //Include the Wi-Fi library.
#include <ESP8266WiFiMulti.h>              //Include the Wi-Fi-Multi library.
#include <ESP8266mDNS.h>                   //Works great for normal sites on the Internet, but most local networks don't have their own DNS server. 
                                           //This means that you can't reach local devices using a domain name, and you're stuck using IP addresses mDNS uses domain names with the .local suffix.
#include <WiFiUdp.h>                       //Initializes the ethernet UDP library and network settings.
#include <time.h>                          //Include time library (Day and hours).
ESP8266WiFiMulti wifiMulti;                //Create an instance of the ESP8266WiFiMulti class, called 'wifiMulti'.
#define RELAY_PIN D1
WiFiServer server(80);
int i = 0;//Corrida del día
int j = 0;
int k = 0;
int l = 0;
int value = LOW;

void setup() {
  int timezone = -6 * 3600;                //Variable para asignar la zona horaria.
  int dst = 0;                             //Forma de compartir el horario UTC.
                                           //Start the Serial communication to send messages to the computer.
  Serial.begin(115200);
  delay(1000);
  pinMode(RELAY_PIN, OUTPUT);
                                           //Agrega las redes Wi-Fi a las que te quieres poder conectar.
  wifiMulti.addAP("ABC", "XYZ");   
  
  Serial.print("Conectando");
  while (wifiMulti.run() != WL_CONNECTED) {//Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above.
    delay(1000);
    Serial.print('.');
  }
  Serial.print("\nConectado a: ");
  Serial.println(WiFi.SSID());             //Muestra el nombre de la red a la que se conectó.
                                           //Inicia el Servidor ESP8266 en la red en la que está conectado.
  server.begin();
  Serial.println("Servidor iniciado");
                                           //Muestra el número de URL del Servidor ESP8266.
  Serial.print("Usa este URL: http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
                                           //De aqui consigue la hora UTC en formato DST.
  configTime(timezone, dst, "pool.ntp.org","time.nist.gov");
  Serial.println("\nObteniendo horario de zona");
  while(!time(nullptr)){
     Serial.print("*");
     delay(1000);
  }
  Serial.println("Horario obtenido!!!");
}
void loop() {
                                           //Revisa la conexión del cliente.
  WiFiClient client = server.available();
                                           //Lee la primera línea del requerimiento.
  String request = client.readStringUntil('\r');
  client.flush();
                                           //Gestiona la solicitud desde el servidor.
  if (request.indexOf("/LED=ON") != -1) {
    digitalWrite(RELAY_PIN, HIGH);
    value = HIGH;
  }
  if (request.indexOf("/LED=OFF") != -1){
    digitalWrite(RELAY_PIN, LOW);
    value = LOW;
  }
                                           // Avisa en el servidor el status de la luz.
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println("Connection: close");
  client.println();
  client.println("<!DOCTYPE html><html>");
  client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
  client.println("<link rel=\"icon\" href=\"data:,\">");
  client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
  client.println(".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;");
  client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
  client.println(".button2 {background-color: #77878A;}</style></head>");
                                           //Header del Servidor.
  if(value == HIGH) client.println("<body><h1>La luz esta actualmente: Prendida</h1>");
  if(value == LOW) client.println("<body><h1>La luz esta actualmente: Apagada</h1>");
                                           //Elige el boton con base en el valor "value".
  if (value==LOW) {
    client.println("<p><a href=\"/LED=ON\"><button class=\"button\">ON</button></a></p>");
  } else {
    client.println("<p><a href=\"/LED=OFF\"><button class=\"button button2\">OFF</button></a></p>");
  }
  client.println("
\n V.C.:");
  client.println(i);
  client.println(j);
  client.println(k);
  client.println(l);
  client.println("
");
  client.println("</body></html>");
                                           //La respuesta HTTP termina con una línea en blanco.
  client.println();
                                           //Asigna hora del PoolServidor.
  time_t now = time(nullptr);
  struct tm* p_tm = localtime(&now);
                                           //Código para mtto muestra día, horario y valores de variables.
  Serial.print("\n");
  Serial.print(p_tm->tm_mday);
  Serial.print("/");
  Serial.print(p_tm->tm_mon + 1);
  Serial.print("/");
  Serial.print(p_tm->tm_year + 1900);
  Serial.print(" - ");
  Serial.print(p_tm->tm_hour);
  Serial.print(":");
  Serial.print(p_tm->tm_min);
  Serial.print(":");
  Serial.print(p_tm->tm_sec);
  Serial.print(" ");
  if (p_tm->tm_wday == 0 ) Serial.print("Domingo");
  if (p_tm->tm_wday == 1 ) Serial.print("Lunes");
  if (p_tm->tm_wday == 2 ) Serial.print("Martes");
  if (p_tm->tm_wday == 3 ) Serial.print("Miércoles");
  if (p_tm->tm_wday == 4 ) Serial.print("Jueves");
  if (p_tm->tm_wday == 5 ) Serial.print("Viernes");
  if (p_tm->tm_wday == 6 ) Serial.print("Sábado");
  Serial.print(" ");
  Serial.print(" Luz:");
  Serial.print(value);
  Serial.print(" V.C.:");                  //Variables de Control.
  Serial.print(i);
  Serial.print(" ");
  Serial.print(j);
  Serial.print(k);
  Serial.print(l);
  }
}

Hi,

Please post the code using the code tags.

Would be easy if toy post the original code, your code, and tell us what you changed.

Of Course I will and thanks for your answer :slight_smile:

I've changed this lines:

  if ( (p_tm->tm_hour == 6) && (p_tm->tm_min == 0) && (p_tm->tm_wday > 0) && (p_tm->tm_wday < 6) ){
    digitalWrite(RELAY_PIN, HIGH);
    value = HIGH;
    delay(1800000);
    digitalWrite(RELAY_PIN, LOW);
    value = LOW;
  }
                                           //Después de las 18 horas de cada día hace un calculo aleatorio de tiempos para encender al menos 5 minutos la luz.
  if ( (p_tm->tm_hour >= 19) && (i == 0) ){
      j = random(20,24);                   //Hora de inicio.
      k = random(0,30);                    //Minuto de inicio.
      l = random(5,30);                    //Tiempo de duración.
      i = 1;                               //V.C. Una vez al día.
  }
  if ( (p_tm->tm_hour == j) && (p_tm->tm_min == k) ){
      digitalWrite(RELAY_PIN, HIGH);
      value = HIGH;
      delay(l*1000*60);
      digitalWrite(RELAY_PIN, LOW);
      value = LOW;
  }
}

For this lines:

  if ( (p_tm->tm_hour >= 19) && (i == 0) ){
      j = random(20,24);                   //Hora de inicio.
      k = random(0,31);                    //Minuto de inicio.
      l = random(5,30);                    //Tiempo de duración.
      i = 1;                               //V.C. Una vez al día.
  }
  if ( (p_tm->tm_hour <= 19)) n = 0;
                                           //Si son las 06:00 horas prende la luz 30 min solo de Lunes a Viernes.
  if ( (p_tm->tm_hour == 6) && (p_tm->tm_min <= 30) && (p_tm->tm_wday > 0) && (p_tm->tm_wday < 6) || (i == 1) && (n == 0) && (p_tm->tm_hour == j) && (p_tm->tm_min >= k) && (p_tm->tm_min <= k + l) || m == 1){
    digitalWrite(RELAY_PIN, HIGH);
    value = HIGH;
  }else{
    digitalWrite(RELAY_PIN, LOW);
    value = LOW;
  }
}

But both sketches upload without errors and run cause the ESP8266 initiates the server and via WiFi if you press the button it works and change the "value" to High or Low. The problem is that there is no serial communication with the IDE Serial Monitor and the relay won't turn on or off.

So you say if you upload the old code again, it doesn't behave the same way as it did before? That would imply that something other than the code has changed (presumably hardware).

Check for bad connections, loose wires, things being shorted by a nearby conductive object - that kind of thing.

If you have a second D1 mini, you might also try swapping them and seeing if you see the same issue (if that one works, but you can switch back to the other one and it doesn't work again, your D1 mini is damaged). Is that relay a module with a transistor to switch the coil and a freewheel diode, or a bare relay you wired up? In the latter case, do you have the transistor and freewheel diode?

The fact that you're not getting serial output, but you can upload code is weird - because if you can upload code, the serial port is clearly functioning. That's very strange.

Thanks for your answer...

The code works perfectly on both sketches (Just the uploading, processing, server creation and interaction) but won't give any voltage to D1 my relay module.

I've figured it out... It was somehow the board type.

I was trying with WeMos D1 R1 and got those malfunction now switch to LOLIN(WEMOS) D1 R2 & mini and it works just fine.

For your question "Is that relay a module with a transistor to switch the coil and a freewheel diode" how can I know (just bought a Relay module at Banggood same as the WeMos)?

Probably different pin number mapping between the two board definitions. There are several pin number mapping schemes used - NodeMCU, (which combined impressive levels of competence - an interpreter for the ESP8266, released very quickly after the ESP8266 came out - with utterly stupid design decisions - using LUA as the language and renumbering the pins) has it's own pin mapping, different from the GPIO numbers that the ESP8266 uses internally. Since then, some people used the NodeMCU pin mapping, and others used the GPIO numbers.

On second question - almost all relay modules do have those components (certainly the ones that are shaped to stack with the D1 mini's do), but occasionally you see a cheap chinese module that doesn't have that, or does something else stupid. To tell if your module has them, you look at it - diodes and transistors are not invisible.

Got it thanks for the info...

And yes I have both the Diode and the transistor...