#include <WiFi.h>
#include <HTTPClient.h>
#include "base64.h" // Include base64 library
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Twilio credentials
const String account_sid = "ACc5fe505851407b66a3e952ab1859dbbb";
const String auth_token = "25498cba6a2075bf2dc21ef4d7d36e60";
const String twilio_phone_number = "whatsapp:+14155238886"; // Twilio WhatsApp Sandbox number
// Destination WhatsApp number
const String destination_number = "whatsapp:+6285298601434"; // WhatsApp number to send notifications
// Define the GPIO pin for push button and buzzer
const int buttonPin = 12; // GPIO2 (D4) for push button
const int buzzerPin = 4; // GPIO5 (D5) for buzzer
void setup() {
Serial.begin(115200);
// Initialize push button and buzzer pins
pinMode(buttonPin, INPUT_PULLUP);
pinMode(buzzerPin, OUTPUT);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting...");
}
Serial.println("Connected to WiFi");
// Print ESP32 Local IP Address
Serial.println(WiFi.localIP());
}
void loop() {
// Check if push button is pressed
if (digitalRead(buttonPin) == LOW) {
// Button pressed, send WhatsApp notification and activate buzzer
sendWhatsAppNotification("Pintu Panel Terbuka");
Serial.println("send WA");
activateBuzzer();
// Wait for button release
while (digitalRead(buttonPin) == LOW) {
delay(100); // Wait for button release
}
// Send standby notification when button is released
sendWhatsAppNotification("Panel Standby");
}
}
// Function to send WhatsApp notification via Twilio
void sendWhatsAppNotification(String message) {
HTTPClient http;
// Construct the URL for Twilio API
String url = "https://api.twilio.com/2010-04-01/Accounts/";
url += account_sid;
url += "/Messages.json";
// HTTP Basic Authentication
String auth = account_sid + ":" + auth_token;
String base64_auth = base64::encode((const unsigned char*)auth.c_str(), auth.length()); // Encode auth credentials to Base64
// Construct the message body
String body = "To=" + destination_number;
body += "&From=" + twilio_phone_number;
body += "&Body=" + message;
// Send the HTTP POST request
http.begin(url.c_str());
http.addHeader("Authorization", "Basic " + base64_auth);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpResponseCode = http.POST(body);
// Check for successful HTTP request
if (httpResponseCode > 0) {
Serial.print("Twilio API success, HTTP Response code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Twilio API request failed, HTTP Response code: ");
Serial.println(httpResponseCode);
}
http.end();
}
// Function to activate the buzzer
void activateBuzzer() {
digitalWrite(buzzerPin, HIGH); // Turn buzzer ON
delay(1000); // Buzzer active for 1 second
digitalWrite(buzzerPin, LOW); // Turn buzzer OFF
}