1(i).
To interface LED/Buzzer with Arduino /Raspberry Pi and write a program to ‘turn ON’ LED
for 1 sec after every 2 seconds.
1(ii). To interface the Push button/Digital sensor (IR/LDR) with Arduino /Raspberry Pi and write
a program to ‘turn ON’ LED when a push button is pressed or at sensor detection.
2 (i). To interface the DHT11 sensor with Arduino /Raspberry Pi and write a program to print
temperature and humidity readings.
2(ii). To interface OLED with Arduino /Raspberry Pi and write a program to print its temperature
and humidity readings.
3. To interface the motor using a relay with Arduino /Raspberry Pi and write a program to ‘turn
ON’ the motor when a push button is pressed.
4(i). Write an Arduino/Raspberry Pi program to interface the Soil Moisture Sensor.
4(ii). Write an Arduino/Raspberry Pi program to interface the LDR/Photo Sensor.
5. Write a program to interface an Ultrasonic Sensor with Arduino /Raspberry Pi.
6. Write a program on Arduino/Raspberry Pi to upload temperature and humidity data
to thingspeak cloud.
7. Write a program on Arduino/Raspberry Pi to retrieve temperature and humidity data
from thingspeak cloud.
8. Write a program to interface LED using Telegram App.
9. Write a program on Arduino/Raspberry Pi to publish temperature data to the MQTT broker.
10. Write a program to create a UDP server on Arduino/Raspberry Pi and respond with humidity
data to the UDP client when requested.
11. Write a program to create a TCP server on Arduino /Raspberry Pi and respond with humidity
data to the TCP client when requested.
12. Write a program on Arduino / Raspberry Pi to subscribe to the MQTT broker for temperature
data and print it.
1(i). To interface LED/Buzzer with Arduino /Raspberry Pi and write a program to ‘turn ON’ LED
for 1 sec after every 2 seconds.
void setup() {
 // initialize digital pin LED_BUILTIN as an output. Which acts as Active low. (means Not operation)
 pinMode(LED_BUILTIN, OUTPUT); //NodeMCU uses GPIO02 or D4 as built in LED.
}
// the loop function runs over and over again forever
void loop() {
 digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
 delay(1000); // wait for a second
 digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
 delay(2000); // wait for a second
}
1(ii). To interface the Push button/Digital sensor (IR/LDR) with Arduino /Raspberry Pi and write
a program to ‘turn ON’ LED when a push button is pressed or at sensor detection.
#define LED_PIN 14 // D5 (GPIO14) - LED
#define SENSOR_PIN 12 // D6 (GPIO12) - Push Button / Digital Sensor
void setup() {
 pinMode(LED_PIN, OUTPUT);
 pinMode(SENSOR_PIN, INPUT); // Internal pull-up for button/sensor
 Serial.begin(115200);
}
void loop() {
 int sensorState = digitalRead(SENSOR_PIN); // Read sensor/button state
 if (sensorState == HIGH) { // Button Pressed / Sensor Triggered
 digitalWrite(LED_PIN, HIGH); // Turn ON LED
 Serial.println("LED ON");
 } else {
 digitalWrite(LED_PIN, LOW); // Turn OFF LED
 Serial.println("LED OFF");
 }
 delay(100); // Small delay for stability
}
2 (i). To interface the DHT11 sensor with Arduino /Raspberry Pi and write a program to print
temperature and humidity readings.
#include <DHT.h>
#define DHTPIN 2 // D4 (GPIO2) connected to DHT11 Data pin
#define DHTTYPE DHT11 // Define sensor type
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor
void setup() {
 Serial.begin(115200);
 dht.begin();
}
void loop() {
 float temperature = dht.readTemperature(); // Read temperature (Celsius)
 float humidity = dht.readHumidity(); // Read humidity
 if (isnan(temperature) || isnan(humidity)) {
 Serial.println("Failed to read from DHT11 sensor!");
 return;
 }
 Serial.print("Temperature: ");
 Serial.print(temperature);
 Serial.print(" degree C | Humidity: ");
 Serial.print(humidity);
 Serial.println(" %");
 delay(2000); // Wait for 2 seconds before next reading
}
2(ii). To interface OLED with Arduino /Raspberry Pi and write a program to print its temperature
and humidity readings.
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>
#define SCREEN_WIDTH 128 // OLED display width
#define SCREEN_HEIGHT 64 // OLED display height
#define OLED_RESET -1 // Reset pin (not used)
#define SCREEN_ADDRESS 0x3C // I2C address for OLED
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define DHTPIN 2 // D4 (GPIO2) connected to DHT11 Data pin
#define DHTTYPE DHT11 // Define sensor type
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor
void setup() {
 Serial.begin(115200);
 dht.begin();
 // Initialize OLED display
 if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
 Serial.println(F("SSD1306 allocation failed"));
 while (1);
 }
 display.clearDisplay();
 display.setTextSize(1);
 display.setTextColor(WHITE);
}
void loop() {
 float temperature = dht.readTemperature();
 float humidity = dht.readHumidity();
 if (isnan(temperature) || isnan(humidity)) {
 Serial.println("Failed to read from DHT sensor!");
 return;
 }
 // Print to Serial Monitor
 Serial.print("Temperature: ");
 Serial.print(temperature);
 Serial.print(" degree C | Humidity: ");
 Serial.print(humidity);
 Serial.println(" %");
 // Display on OLED
 display.clearDisplay();
 display.setCursor(0, 10);
 display.println("Temperature: " + String(temperature) + " degree C");
 display.setCursor(0, 30);
 display.println("Humidity: " + String(humidity) + " %");
 display.display();
 delay(2000); // Update every 2 seconds
}
Circuit:
OLED Pin NodeMCU Pin
VCC 3.3V
GND GND
SDA D2 (GPIO4)
SCL D1 (GPIO5)
3. To interface the motor using a relay with Arduino /Raspberry Pi and write a program to ‘turn ON’
the motor when a push button is pressed.
#define LED_PIN 14 // D5 (GPIO14) - LED
#define SENSOR_PIN 12 // D6 (GPIO12) - Push Button / Digital Sensor
void setup() {
 pinMode(LED_PIN, OUTPUT);
 pinMode(SENSOR_PIN, INPUT); // Internal pull-up for button/sensor
 Serial.begin(115200);
}
void loop() {
 int sensorState = digitalRead(SENSOR_PIN); // Read sensor/button state
 if (sensorState == HIGH) { // Button Pressed / Sensor Triggered
 digitalWrite(LED_PIN, HIGH); // Turn ON LED
 Serial.println("LED ON");
 } else {
 digitalWrite(LED_PIN, LOW); // Turn OFF LED
 Serial.println("LED OFF");
 }
 delay(100); // Small delay for stability
}
4(i). Write an Arduino/Raspberry Pi program to interface the Soil Moisture Sensor.
#define SOIL_SENSOR A0 // Analog pin for Soil Moisture Sensor
void setup() {
 Serial.begin(115200);
 pinMode(SOIL_SENSOR, INPUT);
}
void loop() {
 int moistureValue = analogRead(SOIL_SENSOR);
 Serial.print("Soil Moisture Level: ");
 Serial.println(moistureValue);
 if (moistureValue > 700) { //
 Serial.println("Status: Dry Soil! Water Needed.");
 } else if (moistureValue > 300 && moistureValue <= 700) {
 Serial.println("Status: Moist Soil.");
 } else {
 Serial.println("Status: Wet Soil!");
 }
 delay(2000);
}
4(ii). Write an Arduino/Raspberry Pi program to interface the LDR/Photo Sensor.
#define LDR_PIN D2 // Digital Output from LDR module
void setup() {
 Serial.begin(115200);
 pinMode(LDR_PIN, INPUT);
}
void loop() {
 int lightState = digitalRead(LDR_PIN);
 if (lightState == LOW) { // Adjust sensitivity using the onboard potentiometer
 Serial.println("Status: Bright Light Detected.");
 } else {
 Serial.println("Status: Dark Environment!");
 }
 delay(1000);
}
5. Write a program to interface an Ultrasonic Sensor with Arduino /Raspberry Pi.
#define TRIG_PIN D5 // GPIO14
#define ECHO_PIN D6 // GPIO12
void setup() {
 Serial.begin(115200);
 pinMode(TRIG_PIN, OUTPUT);
 pinMode(ECHO_PIN, INPUT);
}
void loop() {
 long duration;
 float distance;
 // Send a 10µs HIGH pulse to trigger the sensor
 digitalWrite(TRIG_PIN, LOW);
 delayMicroseconds(2);
 digitalWrite(TRIG_PIN, HIGH);
 delayMicroseconds(10);
 digitalWrite(TRIG_PIN, LOW);
 // Read the echo pulse duration
 duration = pulseIn(ECHO_PIN, HIGH);
 // Convert time to distance (in cm)
 distance = (duration * 0.0343) / 2; //speed of sound in air is 343 m/s. 0.0343 cm/micro s
 Serial.print("Distance: ");
 Serial.print(distance);
 Serial.println(" cm");
 delay(1000);
}
6. Write a program on Arduino/Raspberry Pi to upload temperature and humidity data to thingspeak
cloud.
#include <ESP8266WiFi.h>
#include <DHT.h>
#define DHTPIN D4 // GPIO2 where DHT11 is connected
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "Sathish"; // Enter your WiFi Name
const char* password = "123456789"; // Enter your WiFi Password
const char* server = "api.thingspeak.com";
String apiKey = "KVJLSA08F5KUHUHS"; // Replace with your ThingSpeak Write API Key
WiFiClient client;
void setup() {
 Serial.begin(115200);
 WiFi.begin(ssid, password);
 Serial.print("Connecting to WiFi");
 while (WiFi.status() != WL_CONNECTED) {
 delay(1000);
 Serial.print(".");
 }
 Serial.println("\nWiFi Connected!");
 dht.begin();
}
void loop() {
 float temperature = dht.readTemperature(); // Read Temperature
 float humidity = dht.readHumidity(); // Read Humidity
 if (isnan(temperature) || isnan(humidity)) {
 Serial.println("Failed to read from DHT sensor!");
 return;
 }
 Serial.print("Temperature: ");
 Serial.print(temperature);
 Serial.print(" degree C, Humidity: ");
 Serial.print(humidity);
 Serial.println("%");
 // Send data to ThingSpeak
 if (client.connect(server, 80)) {
 String url = "/update?api_key=" + apiKey + "&field1=" + String(temperature) + "&field2=" +
String(humidity);
 client.print(String("GET ") + url + " HTTP/1.1\r\n" +
 "Host: " + server + "\r\n" +
 "Connection: close\r\n\r\n");
 Serial.println("Data sent to ThingSpeak");
 } else {
 Serial.println("Failed to connect to ThingSpeak");
 }
 client.stop();
 delay(15000); // Wait 15 seconds before sending new data
}
7. Write a program on Arduino/Raspberry Pi to retrieve temperature and humidity data from
thingspeak cloud.
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h> // Include ArduinoJson library for parsing JSON
const char* ssid = "OnePlus Nord CE 2 Lite 5G"; // Enter your WiFi Name
const char* password = "Sathish@123"; // Enter your WiFi Password
String channelID = "2861168"; // Replace with your ThingSpeak Channel ID
String readAPIKey = "FG2VQLEPL9JEG9EM"; // Optional: Replace with Read API Key if private
WiFiClient client; // Create WiFiClient object
void setup() {
 Serial.begin(115200);
 WiFi.begin(ssid, password);
 Serial.print("Connecting to WiFi");
 while (WiFi.status() != WL_CONNECTED) {
 delay(1000);
 Serial.print(".");
 }
 Serial.println("\nWiFi Connected!");
}
void loop() {
 if (WiFi.status() == WL_CONNECTED) {
 HTTPClient http;
 String url = "http://api.thingspeak.com/channels/" + channelID + "/feeds/last.json?api_key=" +
readAPIKey;
 http.begin(client, url); // Use WiFiClient with the URL
 int httpCode = http.GET();
 if (httpCode > 0) {
 String payload = http.getString();
 Serial.println("Received Data: " + payload);
 // Parse JSON
 DynamicJsonDocument doc(512);
 DeserializationError error = deserializeJson(doc, payload);
 if (!error) {
 float temperature = doc["field1"].as<float>();
 float humidity = doc["field2"].as<float>();
 Serial.print("Temperature: ");
 Serial.print(temperature);
 Serial.println(" degree C");
 Serial.print("Humidity: ");
 Serial.print(humidity);
 Serial.println(" %");
 } else {
 Serial.println("JSON Parsing Failed!");
 }//
 } else {
 Serial.println("Error retrieving data from ThingSpeak");
 }
 http.end();
} else {
 Serial.println("WiFi Disconnected!");
}
delay(15000); // Wait 15 seconds before retrieving again
}
9. Write a program on Arduino/Raspberry Pi to publish temperature data to the MQTT broker.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
// WiFi Credentials
const char* ssid = "OnePlus Nord CE 2 Lite 5G";
const char* password = "Sathish@123";
// ThingSpeak MQTT Credentials
const char* mqtt_server = "mqtt3.thingspeak.com";
const int mqtt_port = 1883;
const char* mqtt_client_id = "PCw7OzIOKwo4Lg80JRsBFgU"; // Use your MQTT API Key as
client ID
const char* mqtt_username = "PCw7OzIOKwo4Lg80JRsBFgU"; // Your ThingSpeak username
const char* mqtt_password = "5NtCrE/dtrOkp71Tv5gDkRm4"; // Your MQTT API Key
const char* mqtt_topic = "channels/2861168/publish/fields/field1"; // Replace with your ThingSpeak
Channel ID
// DHT11 Sensor
#define DHTPIN D4 // GPIO2 (D4 on NodeMCU)
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
// MQTT Client
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
 Serial.begin(115200);
 // Connect to WiFi
 WiFi.begin(ssid, password);
 Serial.print("Connecting to WiFi");
 while (WiFi.status() != WL_CONNECTED) {
 delay(1000);
 Serial.print(".");
 }
 Serial.println("\nWiFi Connected!");
 dht.begin();
 // Set up MQTT Server
 client.setServer(mqtt_server, mqtt_port);
}
void reconnect() {
 while (!client.connected()) {
 Serial.print("Connecting to MQTT...");
 if (client.connect(mqtt_client_id, mqtt_username, mqtt_password)) {
 Serial.println("Connected to ThingSpeak MQTT broker");
 } else {
 Serial.print("Failed. Error Code: ");
 Serial.println(client.state());
 delay(5000);
 }
 }
}
void loop() {
 if (!client.connected()) {
 reconnect();
 }
 client.loop(); // Keep the connection alive
 // Read temperature
 float temperature = dht.readTemperature();
 if (!isnan(temperature)) {
 Serial.print("Temperature: ");
 Serial.print(temperature);
 Serial.println(" degree C");
 // Convert float to string
 char tempStr[8];
 dtostrf(temperature, 6, 2, tempStr);
 // Publish to ThingSpeak MQTT
 if (client.publish(mqtt_topic, tempStr)) {
 Serial.println("Temperature data published to ThingSpeak MQTT!");
 } else {
 Serial.println("Failed to publish data.");
 }
 } else {
 Serial.println("Failed to read from DHT sensor!");
 }
 delay(20000); // ThingSpeak allows data every 15 seconds (set to 20s for stability)
}
12. Write a program on Arduino / Raspberry Pi to subscribe to the MQTT broker for temperature
data and print it.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// WiFi Credentials
const char* ssid = "OnePlus Nord CE 2 Lite 5G";
const char* password = "Sathish@123";
// ThingSpeak MQTT Credentials
const char* mqtt_server = "mqtt3.thingspeak.com";
const int mqtt_port = 1883;
const char* mqtt_client_id = "PCw7OzIOKwo4Lg80JRsBFgU"; // Use your MQTT API Key as
client ID
const char* mqtt_username = "PCw7OzIOKwo4Lg80JRsBFgU"; // Your ThingSpeak username
const char* mqtt_password = "5NtCrE/dtrOkp71Tv5gDkRm4"; // Your MQTT API Key
const char* mqtt_topic = "channels/2861168/subscribe/fields/field1"; // Replace with your
ThingSpeak Channel ID
// MQTT Client
WiFiClient espClient;
PubSubClient client(espClient);
// Function to connect to WiFi
void connectWiFi() {
 WiFi.mode(WIFI_STA);
 WiFi.begin(ssid, password);
 Serial.print("Connecting to WiFi: ");
 Serial.println(ssid);
 int attempts = 0;
 while (WiFi.status() != WL_CONNECTED) {
 delay(1000);
 Serial.print(".");
 attempts++;
 // Try reconnecting every 10 seconds
 if (attempts > 10) {
 Serial.println("\nRestarting WiFi Connection...");
 WiFi.disconnect();
 WiFi.begin(ssid, password);
 attempts = 0;
 }
 }
 Serial.println("\nWiFi Connected!");
 Serial.print("IP Address: ");
 Serial.println(WiFi.localIP());
}
// Callback function for receiving MQTT messages
void callback(char* topic, byte* payload, unsigned int length) {
 Serial.print("\nMessage received from topic: ");
 Serial.println(topic);
 Serial.print("Payload received: ");
 String receivedData = "";
 for (unsigned int i = 0; i < length; i++) {
 receivedData += (char)payload[i];
 }
 Serial.println("Temperature Data: " + receivedData + " degree C");
}
void setup() {
 Serial.begin(115200);
 delay(10);
 connectWiFi(); // Call the WiFi connection function
 // Set up MQTT Server
 client.setServer(mqtt_server, mqtt_port);
 client.setCallback(callback);
}
void reconnect() {
 while (!client.connected()) {
 Serial.print("Connecting to MQTT...");
 if (client.connect(mqtt_client_id, mqtt_username, mqtt_password)) {
 Serial.println("Connected to ThingSpeak MQTT broker");
 // Subscribe to the temperature topic
 Serial.print("Subscribing to topic: ");
 Serial.println(mqtt_topic);
 client.subscribe(mqtt_topic);
 } else {
 Serial.print("Failed. Error Code: ");
 Serial.println(client.state());
 delay(5000);
 }
 }
}
void loop() {
 if (!client.connected()) {
 reconnect();
 }
 client.loop(); // Keep the connection alive
 delay(1000);
}
10. Write a program to create a UDP server on Arduino/Raspberry Pi and respond with humidity
data to the UDP client when requested.
Server Program
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <DHT.h>
// WiFi Credentials
const char* ssid = "OnePlus Nord CE 2 Lite 5G";
const char* password = "Sathish@123";
// UDP Settings
WiFiUDP udp;
const unsigned int udpPort = 1234; // Listening port
char packetBuffer[255]; // Buffer for incoming data
// DHT11 Sensor Configuration
#define DHTPIN D4 // GPIO2 (D4) on NodeMCU
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
 Serial.begin(115200);
 delay(10);
 // Connect to WiFi
 WiFi.begin(ssid, password);
 Serial.print("Connecting to WiFi");
 while (WiFi.status() != WL_CONNECTED) {
 delay(1000);
 Serial.print(".");
 }
 Serial.println("\nWiFi Connected!");
 Serial.print("ESP8266 IP Address: ");
 Serial.println(WiFi.localIP());
 // Start UDP Server
 udp.begin(udpPort);
 Serial.print("UDP Server started on port ");
 Serial.println(udpPort);
 // Initialize DHT Sensor
 dht.begin();
}
void loop() {
 int packetSize = udp.parsePacket(); // Check if data is received
 if (packetSize) {
 Serial.println("UDP Request Received!");
 // Read the request packet
 udp.read(packetBuffer, packetSize);
 packetBuffer[packetSize] = '\0'; // Null terminate string
 Serial.print("Received Packet: ");
 Serial.println(packetBuffer);
 // Check if client requests humidity data
 if (strcmp(packetBuffer, "GET_HUMIDITY") == 0) {
 float humidity = dht.readHumidity();
 // Check if the reading is valid
 if (isnan(humidity)) {
 Serial.println("Failed to read from DHT sensor!");
 udp.beginPacket(udp.remoteIP(), udp.remotePort());
 udp.print("Error: Failed to read humidity");
 udp.endPacket();
 } else {
 Serial.print("Sending Humidity Data: ");
 Serial.println(humidity);
 // Send the humidity data as a response
 udp.beginPacket(udp.remoteIP(), udp.remotePort());
 udp.print(humidity);
 udp.endPacket();
 }
 }
 }
}
Client Program (Python)
import socket
UDP_IP = "192.168.35.219"
UDP_PORT = 1234
MESSAGE = "GET_HUMIDITY"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(bytes(MESSAGE, "utf-8"), (UDP_IP, UDP_PORT))
data, addr = sock.recvfrom(1024)
print(f"Received humidity: {data.decode('utf-8')}")
sock.close()
11. Write a program to create a TCP server on Arduino /Raspberry Pi and respond with humidity
data to the TCP client when requested.
Server Program
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <DHT.h>
// WiFi Credentials
const char* ssid = "OnePlus Nord CE 2 Lite 5G";
const char* password = "Sathish@123";
// TCP Server Settings
WiFiServer server(1234); // TCP server on port 1234
// DHT11 Sensor Configuration
#define DHTPIN D4 // GPIO2 (D4) on NodeMCU
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
 Serial.begin(115200);
 delay(10);
 // Connect to WiFi
 WiFi.begin(ssid, password);
 Serial.print("Connecting to WiFi");
 while (WiFi.status() != WL_CONNECTED) {
 delay(1000);
 Serial.print(".");
 }
 Serial.println("\nWiFi Connected!");
 Serial.print("ESP8266 IP Address: ");
 Serial.println(WiFi.localIP());
 // Start TCP Server
 server.begin();
 Serial.println("TCP Server Started. Waiting for client...");
 // Initialize DHT Sensor
 dht.begin();
}
void loop() {
 WiFiClient client = server.available(); // Check for client connection
 if (client) {
 Serial.println("Client Connected!");
 while (client.connected()) {
 if (client.available()) {
 String request = client.readStringUntil('\n'); // Read request
 Serial.print("Received Request: ");
 Serial.println(request);
 // Check if client requests humidity data
 if (request.indexOf("GET_HUMIDITY") >= 0) {
 float humidity = dht.readHumidity();
 // Check if reading is valid
 if (isnan(humidity)) {
 Serial.println("Failed to read from DHT sensor!");
 client.println("Error: Failed to read humidity");
 } else {
 Serial.print("Sending Humidity Data: ");
 Serial.println(humidity);
 client.println(humidity);
 }
 }
 break; // Exit loop after processing request
 }
 }
 client.stop(); // Close connection
 Serial.println("Client Disconnected.");
 }
}
Client Program (Python)
import socket
ESP8266_IP = "192.168.35.219" # Replace with the actual IP address of your ESP8266
ESP8266_PORT = 1234
def send_tcp_request(request):
 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
 s.connect((ESP8266_IP, ESP8266_PORT))
 s.sendall(request.encode())
 response = s.recv(1024).decode()
 print("Received response:", response)
# Test the "GET_HUMIDITY" request
send_tcp_request("GET_HUMIDITY")
8. Write a program to interface LED using Telegram App.
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
// WiFi Credentials
const char* ssid = "OnePlus Nord CE 2 Lite 5G";
const char* password = "Sathish@123";
// Telegram Bot Credentials
const char* botToken = "7674131182:AAGnyKPJ7HRYC70vWCqmAVR3vCF071Lwrmo"; //
Replace with your bot token
const String chatID = "1109218144"; // Replace with your Chat ID
// LED Configuration
#define LED_PIN D4 // GPIO2 (D4) on NodeMCU
// WiFi and Telegram Client
WiFiClientSecure client;
UniversalTelegramBot bot(botToken, client);
void setup() {
 Serial.begin(115200);
 pinMode(LED_PIN, OUTPUT);
 digitalWrite(LED_PIN, LOW);
 // Connect to WiFi
 WiFi.begin(ssid, password);
 Serial.print("Connecting to WiFi");
 while (WiFi.status() != WL_CONNECTED) {
 delay(1000);
 Serial.print(".");
 }
 Serial.println("\nWiFi Connected!");
 // Fix SSL Connection for Telegram (Required for ESP8266)
 client.setInsecure();
 Serial.println("Telegram Bot Ready.");
}
void loop() {
 int newMessages = bot.getUpdates(bot.last_message_received + 1);
 while (newMessages) {
 for (int i = 0; i < newMessages; i++) {
 String text = bot.messages[i].text;
 String senderID = String(bot.messages[i].chat_id);
 Serial.println("Received Message: " + text);
 if (String(senderID) == chatID) {
 if (text == "/on") {
 digitalWrite(LED_PIN, HIGH);
 bot.sendMessage(chatID, "LED is ON", "");
 Serial.println("LED Turned ON");
 } else if (text == "/off") {
 digitalWrite(LED_PIN, LOW);
 bot.sendMessage(chatID, "LED is OFF", "");
 Serial.println("LED Turned OFF");
 } else {
 bot.sendMessage(chatID, "Invalid Command! Use /on or /off", "");
 }
 } else {
 bot.sendMessage(senderID, "Unauthorized User! Access Denied", "");
 }
 }
 newMessages = bot.getUpdates(bot.last_message_received + 1);
 }
 delay(1000); // Check for new messages every second
}