Main Content

Esta página se ha traducido mediante traducción automática. Haga clic aquí para ver la última versión en inglés.

Actualización de canales y control de luces con ESP32

Este ejemplo muestra cómo actualizar su canal y recuperar comandos de una cola ThingSpeak™ TalkBack. Utilice los comandos para cambiar el estado del LED integrado.

Utilice TalkBack cuando su aplicación involucre una máquina que desee ejecutar solo cuando haya un comando en la cola.

Puede actualizar su canal simultáneamente y recuperar el último comando guardado en una cola de TalkBack. Agregue el parámetro talkback_key a su solicitud POST y ThingSpeak devuelve el último comando TalkBack en la respuesta.

Hardware compatible

  • ESP32

Requisitos previos

Debe tener al menos un canal configurado para completar este ejemplo. Create a Channel, como se muestra en Recopilar datos en un nuevo canal y registrar la clave API de escritura. También necesitas configurar un TalkBack. Ve a Aplicaciones > TalkBacks y elige Nuevo TalkBack.

Agregar comandos a la cola de TalkBack

Puede agregar comandos a una cola de TalkBack de dos maneras.

  • Utilice la interfaz web de ThingSpeak TalkBack para agregar comandos a la cola de TalkBack. Puede configurar TalkBack para tener hasta 8000 comandos.

  • Utilice la API de ThingSpeak. Puede utilizar una solicitud HTTP POST para agregar un comando a la cola. En la siguiente POST, reemplace TALKBACK_ID, YOUR_TALKBACK_API_KEY, TALKBACK_COMMAND y POSITION_NUMBER con los valores apropiados. De tu canal.

POST https://api.thingspeak.com/talkbacks/TALKBACK_ID/commands
 api_key=YOUR_TALKBACK_API_KEY
     command_string=TALKBACK_COMMAND
     position=POSITION_NUMBER

Programe su ESP32

1) Descargue el último IDE de Arduino®.

2) Instale el núcleo ESP32. Para obtener más información, consulte Install Arduino ESP32 Support.

3) En el menú Herramientas, seleccione el puerto y la placa apropiados en el IDE de Arduino. Este ejemplo se prueba utilizando la opción Sparkfun ESP32 Thing .

4) Pegue el código en el IDE de Arduino. Agregue la información de su red inalámbrica, su clave API de TalkBack y su número de TalkBack.

5) Programe el dispositivo y luego observe el monitor serie y el LED para observar los cambios cuando se consumen los comandos. Cada comando que se ejecuta se elimina de la lista. Debe agregar más comandos a la lista una vez que se consuman.

Código

1) Comience incluyendo las bibliotecas apropiadas y definiendo variables. Ingrese el SSID y la contraseña de su red. Ingrese su número de canal y los parámetros de TalkBack: myTalkBackID y myTalkBackKey.

WriteMultipleFieldsAndFetchCommandFromTalkBack

Description: Checks a TalkBack queue every 60 seconds and sets the state of the built in LED according
             to the latest command fetched. Turn the LED on and off by using the commands TURN_ON and TURN_OFF.
             The TalkBack documentation can be found at https://www.mathworks.com/help/thingspeak/talkback-app.html            

Hardware: ESP32-based boards

Notes:
- Requires installation of EPS32 core. 
- Select the target hardware from the Tools -> Board menu

Copyright 2018, The MathWorks, Inc.
*/

#include <WiFi.h>

char ssid[] = <enter your SSID>;   // your network SSID (name) 
char pass[] = <enter your password>;   // your network password

WiFiClient  client;

unsigned long myChannelNumber = <enter your channel ID>;
unsigned long myTalkBackID = <enter your talkback ID>;
const char * myTalkBackKey = <enter your TalkBack API Key>;

// Initialize values for ThingSpeak updates
int number1 = 0;
int number2 = random(0,100);
int number3 = random(0,100);
int number4 = random(0,100);

2) En la función setup , inicialice el LED e inicie el monitor serie.

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);  // Set up LED
  Serial.begin(115200);  // Initialize serial
  WiFi.mode(WIFI_STA);
}

3) En el bucle principal, comience estableciendo una conexión a la red Wi-Fi local. Cree el mensaje POST a partir de los números generados aleatoriamente. Realice la POST, verifique el resultado y busque un comando TalkBack. Luego genera nuevos números aleatorios para publicar nuevamente en 20 segundos.

void loop() {

  // Connect or reconnect to Wi-Fi
  if(WiFi.status() != WL_CONNECTED){
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(String(ssid));
    while(WiFi.status() != WL_CONNECTED){
      WiFi.begin(ssid, pass);  
      Serial.print(".");
      delay(5000);     
    } 
    Serial.println("\nConnected.");
  }

  // Create the message body for the POST out of the values
  String postMessage =  String("field1=") + String(number1) +
                        String("&field2=") + String(number2) +
                        String("&field3=") + String(number3) +
                        String("&field4=") + String(number4) +
                        String("&api_key=") + String(myWriteAPIKey) +
                        String("&talkback_key=") + String(myTalkBackKey);                      
                       

   // Make a String for any commands that might be in the queue
  String newCommand = String();

  // Make the POST to ThingSpeak
  int x = httpPOST(postMessage, newCommand);
  client.stop();
  
  // Check the result
  if(x == 200){
    Serial.println("checking queue..."); 
    // Check for a command returned from TalkBack
    if(newCommand.length() != 0){

      Serial.print("  Latest command from queue: ");
      Serial.println(newCommand);
      
      if(newCommand == "TURN_ON"){
        digitalWrite(LED_BUILTIN, HIGH);  
      }

      if(newCommand == "TURN_OFF"){
        digitalWrite(LED_BUILTIN, LOW);
      }
    }
    else{
      Serial.println("  Nothing new.");  
    }
    
  }
  else{
    Serial.println("Problem checking queue. HTTP error code " + String(x));
  }

  // Confirm code works by changing values
  number1++;
  if(number1 > 99){
    number1 = 0;
  }
  number2 = random(0,100);
  number3 = random(0,100);
  number4 = random(0,100);
  
  delay(20000); // Wait 20 seconds to update the channel again
}

4) Utilice la función httpPOST para publicar datos en ThingSpeak y leer el siguiente comando de TalkBack.

int httpPOST(String postMessage, String &response){

  bool connectSuccess = false;
  connectSuccess = client.connect("api.thingspeak.com",80);

  if(!connectSuccess){
      return -301;   
  }
  
  postMessage += "&headers=false";
  
  String Headers =  String("POST /update HTTP/1.1\r\n") +
                    String("Host: api.thingspeak.com\r\n") +
                    String("Content-Type: application/x-www-form-urlencoded\r\n") +
                    String("Connection: close\r\n") +
                    String("Content-Length: ") + String(postMessage.length()) +
                    String("\r\n\r\n");

  client.print(Headers);
  client.print(postMessage);

  long startWaitForResponseAt = millis();
  while(client.available() == 0 && millis() - startWaitForResponseAt < 5000){
      delay(100);
  }

  if(client.available() == 0){       
    return -304; // Didn't get server response in time
  }

  if(!client.find(const_cast<char *>("HTTP/1.1"))){
      return -303; // Couldn't parse response (didn't find HTTP/1.1)
  }
  
  int status = client.parseInt();
  if(status != 200){
    return status;
  }

  if(!client.find(const_cast<char *>("\n\r\n"))){
    return -303;
  }

  String tempString = String(client.readString());
  response = tempString;
  
  return status;
}