#include <SPI.h>
#include <WiFi.h>
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
int LED_PIN_r = 13;
int LED_PIN_y = 14;
int LED_PIN_g = 26;
WiFiClient client;
unsigned long myTalkBackID = 51295;
const char* myTalkBackKey = "UIRMDB4ZYBP3Q3HM";
void setup() {
Serial.begin(115200);
pinMode(LED_PIN_r, OUTPUT);
pinMode(LED_PIN_y, OUTPUT);
pinMode(LED_PIN_g, OUTPUT);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
while (WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid, pass);
delay(2000);
}
}
String tbURI = "/talkbacks/" + String(myTalkBackID) + "/commands/execute";
String postMessage = "api_key=" + String(myTalkBackKey);
String newCommand = String();
int x = httpPOST(tbURI, postMessage, newCommand);
client.stop();
if (x == 200) {
if (newCommand.length() > 0) {
if (newCommand.indexOf("red led on") != -1) {
digitalWrite(LED_PIN_r, HIGH);
}
else if (newCommand.indexOf("red led off") != -1) {
digitalWrite(LED_PIN_r, LOW);
}
else if (newCommand.indexOf("yellow led on") != -1) {
digitalWrite(LED_PIN_y, HIGH);
}
else if (newCommand.indexOf("yellow led off") != -1) {
digitalWrite(LED_PIN_y, LOW);
}
else if (newCommand.indexOf("green led on") != -1) {
digitalWrite(LED_PIN_g, HIGH);
}
else if (newCommand.indexOf("green led off") != -1) {
digitalWrite(LED_PIN_g, LOW);
}
}
}
delay(5000);
}
int httpPOST(String uri, String postMessage, String &response) {
bool connectSuccess = client.connect("api.thingspeak.com", 80);
if (!connectSuccess) {
return -301;
}
postMessage += "&headers=false";
String Headers = "POST " + uri + " HTTP/1.1\r\n" +
"Host: api.thingspeak.com\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Connection: close\r\n" +
"Content-Length: " + String(postMessage.length()) +
"\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;
}
if (!client.find("HTTP/1.1")) {
return -303;
}
int status = client.parseInt();
if (status != 200) {
return status;
}
if (!client.find("\n\r\n")) {
return -303;
}
response = client.readString();
return status;
}