ESP-01, builtin led and Alexa

Hello team, I am trying to make my first project with Alexa and my ESP-01. Alexa is able to see the device, is able to turn on or off (I can see it in the serial monitor) but the builtin led doesn't turn on or off. What am I doing wrong?

#include <Arduino.h>
#if defined(ESP8266)
    #include <ESP8266WiFi.h>
#elif defined(ESP32)
    #include <WiFi.h>
#endif
#include <ESPAsyncWebServer.h>
#include "fauxmoESP.h"

// Rename the credentials.sample.h file to credentials.h and 
// edit it according to your router configuration
#define WIFI_SSID "mywifinetwork"
#define WIFI_PASS "password"
fauxmoESP fauxmo;
AsyncWebServer server(80);

// -----------------------------------------------------------------------------

#define SERIAL_BAUDRATE                 115200
#define LED_BUILTIN                             2

// -----------------------------------------------------------------------------
// Wifi
// -----------------------------------------------------------------------------

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 serverSetup() {

    // Custom entry point (not required by the library, here just as an example)
    server.on("/index.html", HTTP_GET, [](AsyncWebServerRequest *request){
        request->send(200, "text/plain", "Hello, world");
    });

    // These two callbacks are required for gen1 and gen3 compatibility
    server.onRequestBody([](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) {
        if (fauxmo.process(request->client(), request->method() == HTTP_GET, request->url(), String((char *)data))) return;
        // Handle any other body request here...
    });
    server.onNotFound([](AsyncWebServerRequest *request) {
        String body = (request->hasParam("body", true)) ? request->getParam("body", true)->value() : String();
        if (fauxmo.process(request->client(), request->method() == HTTP_GET, request->url(), body)) return;
        // Handle not found request here...
    });

    // Start the server
    server.begin();

}

void setup() {

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

    // LED_BUILTIN
    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, HIGH); // Our LED_BUILTIN has inverse logic (high for OFF, low for ON)

    // Wifi
    wifiSetup();

    // Web server
    serverSetup();

    // Set fauxmoESP to not create an internal TCP server and redirect requests to the server 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(false);
    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 kitchen on" ("kitchen" is the name of the first device below)
    // "Alexa, turn on kitchen"
    // "Alexa, set kitchen to fifty" (50 means 50% of brightness)

    // Add virtual devices
   // fauxmo.addDevice("kitchen");
  fauxmo.addDevice("luce");

    // You can add more devices
  //fauxmo.addDevice("light 3");
    //fauxmo.addDevice("light 4");
    //fauxmo.addDevice("light 5");
    //fauxmo.addDevice("light 6");
    //fauxmo.addDevice("light 7");
    //fauxmo.addDevice("light 8");

    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_BUILTIN,...)
        // 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.
        
        // if (0 == device_id) digitalWrite(RELAY1_PIN, state);
        // if (1 == device_id) digitalWrite(RELAY2_PIN, state);
        // if (2 == device_id) analogWrite(LED_BUILTIN1_PIN, value);
        
        Serial.printf("[MAIN] Device #%d (%s) state: %s value: %d\n", device_id, device_name, state ? "ON" : "OFF", value);

        // For the example we are turning the same LED_BUILTIN on and off regardless fo the device triggered or the value
      //  digitalWrite(LED_BUILTIN, !state); // we are nor-ing the state because our LED_BUILTIN has inverse logic.
      
       if (state==1) {
          
            Serial.printf("accendo\n");
            digitalWrite(LED_BUILTIN, LOW);
                   delay(4000);

  }
   else if (state==0) {
    Serial.printf("spengo");
            digitalWrite(LED_BUILTIN, HIGH);
            delay(2000);
        } 

    });

}

void loop() {

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

    // This is a sample code to output free heap every 5 seconds
    // This is a cheap way to detect memory leaks
    static unsigned long last = millis();
    if (millis() - last > 5000) {
        last = millis();
        //Serial.printf("[MAIN] Free heap: %d bytes\n", ESP.getFreeHeap());
    }

}

I seem to remember that not all esp-01 are the same. Some have the blue LED connected to GPIO2 and some have it connected to GPIO1 which is also TX. Maybe your esp-01 has the led on GPIO1. But if so, you can't turn the led on/off and print messages to the serial monitor in the same sketch. Do you see any brief, faint flashing as messages are being sent to serial monitor? That might be easier to see if you use a very slow baud rate.

IIRC the early ESP01 modules had LED on pin 1 and later they switched to using pin 2.

The ESP8266 generic board setting has a menu entry to select the built-in led pin.

As the LED is on the same pins used by Serial I'm not sure you can use both together easily.

Try loading the blink sketch and determine that LED is on GPIO2.

First of all, thank you very much for your replies!

When using my code yes, there's a tiny blue led that flashes for a micro second. The following blink code works fine:

void setup() {
 pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
 digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
 // but actually the LED is on; this is because
 // it is active low on the ESP-01)
 delay(1000);                      // Wait for a second
 digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
 delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

UPDATE:

The following code works fine:

#include <Arduino.h>
#if defined(ESP8266)
    #include <ESP8266WiFi.h>
#elif defined(ESP32)
    #include <WiFi.h>
#endif
#include <ESPAsyncWebServer.h>
#include "fauxmoESP.h"

// Rename the credentials.sample.h file to credentials.h and 
// edit it according to your router configuration
#define WIFI_SSID "mywifinetwork"
#define WIFI_PASS "password"
fauxmoESP fauxmo;
AsyncWebServer server(80);

// -----------------------------------------------------------------------------

#define SERIAL_BAUDRATE                 115200
//#define LED_BUILTIN                             2

// -----------------------------------------------------------------------------
// Wifi
// -----------------------------------------------------------------------------

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 serverSetup() {

    // Custom entry point (not required by the library, here just as an example)
    server.on("/index.html", HTTP_GET, [](AsyncWebServerRequest *request){
        request->send(200, "text/plain", "Hello, world");
    });

    // These two callbacks are required for gen1 and gen3 compatibility
    server.onRequestBody([](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) {
        if (fauxmo.process(request->client(), request->method() == HTTP_GET, request->url(), String((char *)data))) return;
        // Handle any other body request here...
    });
    server.onNotFound([](AsyncWebServerRequest *request) {
        String body = (request->hasParam("body", true)) ? request->getParam("body", true)->value() : String();
        if (fauxmo.process(request->client(), request->method() == HTTP_GET, request->url(), body)) return;
        // Handle not found request here...
    });

    // Start the server
    server.begin();

}

void setup() {

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

    // LED_BUILTIN
    pinMode(1, OUTPUT);
    digitalWrite(1, HIGH); // Our LED_BUILTIN has inverse logic (high for OFF, low for ON)

    // Wifi
    wifiSetup();

    // Web server
    serverSetup();

    // Set fauxmoESP to not create an internal TCP server and redirect requests to the server 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(false);
    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 kitchen on" ("kitchen" is the name of the first device below)
    // "Alexa, turn on kitchen"
    // "Alexa, set kitchen to fifty" (50 means 50% of brightness)

    // Add virtual devices
   // fauxmo.addDevice("kitchen");
  fauxmo.addDevice("luce");

    // You can add more devices
  //fauxmo.addDevice("light 3");
    //fauxmo.addDevice("light 4");
    //fauxmo.addDevice("light 5");
    //fauxmo.addDevice("light 6");
    //fauxmo.addDevice("light 7");
    //fauxmo.addDevice("light 8");

    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_BUILTIN,...)
        // 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.
        
        // if (0 == device_id) digitalWrite(RELAY1_PIN, state);
        // if (1 == device_id) digitalWrite(RELAY2_PIN, state);
        // if (2 == device_id) analogWrite(LED_BUILTIN1_PIN, value);
        
        Serial.printf("[MAIN] Device #%d (%s) state: %s value: %d\n", device_id, device_name, state ? "ON" : "OFF", value);

        // For the example we are turning the same LED_BUILTIN on and off regardless fo the device triggered or the value
      //  digitalWrite(LED_BUILTIN, !state); // we are nor-ing the state because our LED_BUILTIN has inverse logic.
      
       if (state==1) {
          
           // Serial.printf("accendo\n");
            digitalWrite(1, LOW);
                   delay(4000);

  }
   else if (state==0) {
 //   Serial.printf("spengo");
            digitalWrite(1, HIGH);
            delay(2000);
        } 

    });

}

void loop() {

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

    // This is a sample code to output free heap every 5 seconds
    // This is a cheap way to detect memory leaks
    static unsigned long last = millis();
    if (millis() - last > 5000) {
        last = millis();
        //Serial.printf("[MAIN] Free heap: %d bytes\n", ESP.getFreeHeap());
    }

}

Now that the Alexa integration is ready I'd like to use it to turn on an external led. Where can I find the pinout to understand which pin to use?

Thanks in advance

adelast:
Now that the Alexa integration is ready I'd like to use it to turn on an external led. Where can I find the pinout to understand which pin to use?

Here

Thank you! Everything works fine, I am finding some difficulties with the delay function here:

    if (state==1) {
          
           // Serial.printf("accendo\n");
            digitalWrite(1, LOW);
                   delay(4000);
 digitalWrite(1, HIGH);

  }

It looks like the delay 4000 is ignored, what am I doing wrong? :confused:

After a research it seems that I have to use millis but the results don't change

   if (state==1) {
          
            Serial.printf("accendo\n");
            digitalWrite(LED_BUILTIN, HIGH);
      a1Flag = true;  //allow timing
        a1Millis = millis(); //set to the time right now

  }
   else if (state==0) {
    Serial.printf("spengo");
            digitalWrite(LED_BUILTIN, LOW);
            delay(2000);
        } 
    
    if(a1Flag == true && millis() - a1Millis >= 2000)
    {
      digitalWrite(LED_BUILTIN, LOW); //led off
  
      a1Flag = false; //get ready for the next HIGH on a1
    }

Please perform Tools->Auto format before you post any more code, the indentation is a mess. Indentation does not change the meaning of code in any way, but it can make spotting errors much easier.

Can't see what's wrong with your code, looks like it should work, so the problem may be elsewhere in the sketch, please post it completely.

PS. You don't need to write "a1Flag == true", you can just write "a1Flag", because it's already a boolean. It's better to give boolean variables names that indicate what true means in the real world, for example "ledIsOn" rather than "a1Flag" (which doesn't give a human reader a clue as to what true means or what false means).

PaulRB:
Please perform Tools->Auto format before you post any more code, the indentation is a mess. Indentation does not change the meaning of code in any way, but it can make spotting errors much easier.

Can't see what's wrong with your code, looks like it should work, so the problem may be elsewhere in the sketch, please post it completely.

PS. You don't need to write "a1Flag == true", you can just write "a1Flag", because it's already a boolean. It's better to give boolean variables names that indicate what true means in the real world, for example "ledIsOn" rather than "a1Flag" (which doesn't give a human reader a clue as to what true means or what false means).

Thanks for your suggestions Paul, I have solved the issue by moving the

 if(a1Flag == true && millis() - a1Millis >= 2000)
    {
      digitalWrite(LED_BUILTIN, LOW); //led off
  
      a1Flag = false; //get ready for the next HIGH on a1
    }

portion inside the void loop