#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "TMPL6vDSP5ViA"
#define BLYNK_TEMPLATE_NAME "LED"
#define BLYNK_AUTH_TOKEN "72_26W6voso5GjOGEhNwMudfq_k2BTBh"
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include <HTTPClient.h>
char auth[] = "72_26W6voso5GjOGEhNwMudfq_k2BTBh";
const char* ssid = "Wokwi-GUEST"; // Wifi name
const char* pass = ""; // Wifi pass
const char* webAppUrl = "https://script.google.com/macros/s/AKfycbwQw5u9PjJgs0RlAtSc80DuwFZQzdChCx_mllJthYGNrxVQcpxLpcnrhNe6vDk5gim5/exec";
BlynkTimer timer;
#define LED 13
#define LED2 12
int SW_State = 0;
BLYNK_WRITE(V0)
{
SW_State = param.asInt();
if (SW_State == 1)
{
digitalWrite(LED, HIGH);
String lampu = "LAMPU MERAH HIDUP";
Serial.println(lampu);
Blynk.virtualWrite(V0, HIGH);
sendDataToScript(lampu);
}
else
{
digitalWrite(LED, LOW);
String lampu = "LAMPU MERAH MATI";
Serial.println(lampu);
Blynk.virtualWrite(V0, LOW);
sendDataToScript(lampu);
}
}
BLYNK_WRITE(V1)
{
SW_State = param.asInt();
if (SW_State == 1)
{
digitalWrite(LED2, HIGH);
String lampu = "LAMPU HIJAU HIDUP";
Serial.println(lampu);
Blynk.virtualWrite(V1, HIGH);
sendDataToScript(lampu);
}
else
{
digitalWrite(LED2, LOW);
String lampu = "LAMPU HIJAU MATI";
Serial.println(lampu);
Blynk.virtualWrite(V1, LOW);
sendDataToScript(lampu);
}
}
void setup()
{
Serial.begin(115200);
pinMode(LED, OUTPUT);
pinMode(LED2, OUTPUT);
delay(100);
Blynk.begin(auth, ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop()
{
Blynk.run();
timer.run();
delay(2000);
}
void sendDataToScript(String lampu) {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi not connected, can't send data");
return;
}
HTTPClient http;
String serverPath = String(webAppUrl) + "?lampu=" + urlEncode(lampu);
Serial.print("Connecting to server: ");
Serial.println(serverPath);
// Send HTTP GET request
if (http.begin(serverPath.c_str())) {
int httpCode = http.GET();
if (httpCode > 0) {
Serial.print("Server response code: ");
Serial.println(httpCode);
// String payload = http.getString();
// Serial.println("Server response: " + payload);
} else {
Serial.print("HTTP GET request failed with error code: ");
Serial.println(httpCode);
Serial.println("Error message: " + http.errorToString(httpCode));
}
http.end();
} else {
Serial.println("Unable to connect to the server");
}
delay(2000);
}
String urlEncode(String str) {
String encodedString = "";
char c;
for (int i = 0; i < str.length(); i++) {
c = str.charAt(i);
if (isalnum(c)) {
encodedString += c;
} else {
encodedString += '%';
encodedString += charToHex(c >> 4);
encodedString += charToHex(c & 15);
}
}
return encodedString;
}
char charToHex(char c) {
if (c < 10) return '0' + c;
return 'A' + c - 10;
}