Advertisement
mudhita_triari

ESP32 menggunakan talkback in thinkspeak iot platform V.1.2

Apr 2nd, 2024
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | Source Code | 0 0
  1. #include <WiFi.h>
  2. #include <ThingSpeak.h>
  3.  
  4. const char *ssid = "";
  5. const char *password = "";
  6. const char *talkbackAPIKey = "";
  7.  
  8. enum DevicePin {
  9.   LED1 = 2,
  10.   LED2 = 4,
  11.   BUZZER = 5
  12. };
  13.  
  14. WiFiClient client;
  15.  
  16. void setupDevice(DevicePin pin) {
  17.   pinMode(pin, OUTPUT);
  18. }
  19.  
  20. void connectToWiFi() {
  21.   WiFi.begin(ssid, password);
  22.   Serial.print("Connecting to WiFi");
  23.   while (WiFi.status() != WL_CONNECTED) {
  24.     delay(500);
  25.     Serial.print(".");
  26.   }
  27.   Serial.println("\nConnected to WiFi");
  28. }
  29.  
  30. void Setup_ThingSpeak() {
  31.   ThingSpeak.begin(client);
  32. }
  33.  
  34. void Logika_LED_dan_Buzzer(String command, DevicePin pin, const char* deviceName) {
  35.   if (command == (String(deviceName) + "_on")) {
  36.     digitalWrite(pin, HIGH);
  37.     Serial.println("Response: 200, " + String(deviceName) + " ON");
  38.   } else if (command == (String(deviceName) + "_off")) {
  39.     digitalWrite(pin, LOW);
  40.     Serial.println("Response: 200, " + String(deviceName) + " OFF");
  41.   }
  42. }
  43.  
  44. void setup() {
  45.   Serial.begin(115200);
  46.   setupDevice(LED1);
  47.   setupDevice(LED2);
  48.   setupDevice(BUZZER);
  49.   connectToWiFi();
  50.   Setup_ThingSpeak();
  51. }
  52.  
  53. void loop() {
  54.   ThingSpeak.writeField(talkbackAPIKey, 1, 0, "command", "check", "txt");
  55.   delay(5000);
  56.   String response = ThingSpeak.readStringField(talkbackAPIKey, 2, "string");
  57.  
  58.   if (response.length() > 0) {
  59.     Logika_LED_dan_Buzzer(response, LED1, "LED1");
  60.     Logika_LED_dan_Buzzer(response, LED2, "LED2");
  61.     Logika_LED_dan_Buzzer(response, BUZZER, "BUZZER");
  62.   } else {
  63.     Serial.println("No response from TalkBack");
  64.   }
  65.  
  66.   delay(10000);
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement