Controla una luz con TalkBack en Arduino
Este ejemplo muestra cómo obtener comandos de una cola de ThingSpeak™ TalkBack y usarlos para cambiar el estado del LED integrado.
Use TalkBack cuando su aplicación involucre una máquina que desee ejecutar solo cuando haya un comando en la cola.
En este ejemplo, escribes TURN_ON
o TURN_OFF
a una cola de TalkBack y el dispositivo cambia el estado del LED integrado para que coincida con el comando. Usar ThingSpeak Aplicación TalkBack para almacenar comandos para su dispositivo. Puedes usar el interfaz web o comandos HTTP para escribir comandos de dispositivos en una lista. Puede almacenar hasta 8000 comandos en la lista. Cada vez que el dispositivo lee la lista de comandos, lee un solo comando y elimina el último comando de la lista.
Hardware compatible
Arduino UNO o similar con módulo Wi-Fi o conectividad Wi-Fi
MKR1000
requisitos previos
Configure un TalkBack para ejecutar este ejemplo. Ir aplicaciones > TalkBack y elige Nuevo TalkBack. Luego, agregue comandos a la cola.
Agregar comandos a la cola de TalkBack
Puede agregar comandos a una cola de TalkBack de dos maneras.
Usar ThingSpeak Replicar interfaz web para agregar comandos a la cola de TalkBack. Puede configurar TalkBack para tener hasta 8000 comandos.
Utilice la API de ThingSpeak. Puede usar una solicitud HTTP POST para agregar un comando a la cola. En el siguiente POST, reemplace
TALKBACK_ID
,YOUR_TALKBACK_API_KEY
,TALKBACK_COMMAND
, yPOSITION_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
Programa tu Arduino
1) Descargue el último IDE de Arduino®.
2) Agregar WiFi101
hacia Gerente de biblioteca , si no está ya allí.
a) Seleccione Bosquejo > Incluir biblioteca > Administrar bibliotecas. Buscar WiFi101
.
b) Seleccione el Wi-Fi101 biblioteca y haga clic Instalar.
3) Añadir el WiFi101
biblioteca al croquis.
a) Seleccione Bosquejo > Incluir biblioteca > Administrar bibliotecas.
b) Seleccionar WiFi101
para agregarlo a su boceto.
4) Añadir el SPI
biblioteca al croquis.
a) Seleccione Bosquejo > Incluir biblioteca > Administrar bibliotecas.
b) Seleccionar SPI
para agregarlo a su boceto.
5) En el Instrumentos seleccione el puerto y la placa adecuados en el IDE de Arduino.
6) Pegue el código en el IDE de Arduino. Agregue la información de su red WiFi, su clave API de TalkBack y su número de TalkBack.
7) Programe el dispositivo y luego mire el monitor serial y el LED para observar los cambios cuando se consumen los comandos. Cada vez que se ejecuta un comando, se elimina de la lista. Debe agregar más comandos a la lista después de que se consuman.
Código
1) Comience por incluir las bibliotecas apropiadas y definir variables.
/* FetchCommandFromTalkBack Description: Checks a TalkBack queue every 60 seconds and set 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: Arduino WiFi Shield 101 or MKR Notes: - Requires WiFi101 library. Use the WiFi101 library version 0.13.0 or older. WiFi101 library versions 0.14.0 and newer have a bug that prevents the ThingSpeak library from working properly. - Make sure the WiFi Shield 101 has updated firmware. Find instructions at https://www.arduino.cc/en/Tutorial/FirmwareUpdater. Copyright 2018, The MathWorks, Inc. */ #include <SPI.h> // Required for shield communication #include <WiFi.h> char ssid[] = <enter your SSID>; // your network SSID (name) char pass[] = <enter your password>; // your network password WiFiClient client; unsigned long myTalkBackID = <enter your TalkBack ID; const char * myTalkBackKey = <enter your TalkBack API key>;
2)
En el setup
función, inicialice el LED e inicie el monitor serie.
void setup() { pinMode(LED_BUILTIN, OUTPUT); // Set up LED Serial.begin(115200); // Initialize serial }
3) En el bucle principal, comience por establecer una conexión a la red WiFi local. Cree el mensaje POST con los parámetros correctos. Envíe la solicitud POST, verifique el resultado y busque un comando TalkBack. Espere 60 segundos y verifique la cola nuevamente.
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 TalkBack URI String tbURI = String("/talkbacks/") + String(myTalkBackID) + String("/commands/execute"); // Create the message body for the POST out of the values String postMessage = String("api_key=") + String(myTalkBackKey); // Make a string for any commands in the queue String newCommand = String(); // Make the POST to ThingSpeak int x = httpPOST(tbURI, 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)); } delay(60000); // Wait 60 seconds to check queue again }
4) Usa el httpPOST
función para leer el siguiente comando de TalkBack.
// General function to POST to ThingSpeak int httpPOST(String uri, 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 ") + uri + String(" 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; }