iot pgms
iot pgms
OUTPUT:
Title: Program for Interfacing an External LED
void setup() {
pinMode(18,OUTPUT);
}
void loop() {
digitalWrite(18,HIGH); //on
delay(200);// 1000ms = 1sec
digitalWrite(18,LOW); //off
delay(200);// 1000ms = 1sec
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600); //UART---- BAUD RATE is 96000 (how many bits u can send)
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println(342);
Serial.println(34.432);
Serial.println('K');
Serial.println("bangalore");
delay(2000);
}
ii) To interface Push button/Digital sensor (IR/LDR) with Arduino/Raspberry Pi and
write a program to ‘turn ON’ LED when push button is pressed or at sensor detection.
Title: Program to Get Data from the Push Button and Display It in Serial Monitor.
void setup() {
Serial.begin(9600);
pinMode(35,INPUT); //GPIO-35(already designed)
}
void loop() {
// put your main code here, to run repeatedly:
int val;
val = digitalRead(35); // push button status pin=35
Serial.println(val);
}
Title: To interface Push button/Digital sensor (IR/LDR)
void setup() {
// put your setup code here, to run once:
pinMode(18,OUTPUT); // LED
pinMode(35,INPUT); //Push button
}
void loop() {
// put your main code here, to run repeatedly:
int val;
val= digitalRead(35);
if(val==1)
digitalWrite(18,HIGH); // LED on
else
digitalWrite(18,LOW);
}
OUTPUT:
SMART LED:
sensor----- LDR(light dependent register)
For analog read to get the status of light intensity value in serial monitor
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(36,INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int val;
val = analogRead(36);
Serial.println(val);
delay(500);
}
Output:
Title: Street light Monitoring
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(18,OUTPUT); // LED
pinMode(36,INPUT); //LDR pin 35
}
void loop() {
// put your main code here, to run repeatedly:
int val;
val= analogRead(36);
Serial.println(val);
if(val< 500) // less than 500 light is blocked
digitalWrite(18,HIGH); // LED on
else
digitalWrite(18,LOW); // LED off
}
output:
2 i) i) To interface DHT11 sensor with Arduino/Raspberry Pi and write a program to
print temperature and humidity readings
#include <Adafruit_Sensor.h> // include adafruit library
#include <DHT.h>
#include <DHT_U.h>
#define DHTPIN 32 // digital pin 32
#define DHTTYPE DHT11
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
// Bluetooth Serial object
BluetoothSerial SerialBT;
// GPIO where the LDR is connected to
const int ldr = 36;
String ldrString = "";
// Timer: auxiliar variables
unsigned long previousMillis = 0; // Stores last time temperature was published
const long interval = 1000; // interval at which to publish sensor readings
void setup() {
Serial.begin(115200);
// Bluetooth device name
SerialBT.begin("ESP32test");
Serial.println("The device started, now you can pair it with bluetooth!");
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval){
previousMillis = currentMillis;
ldrString = String(analogRead(36)) ;
SerialBT.println(ldrString);
}
}
While execution
replace SerialBT.begin("ESP32test"); with SerialBT.begin("any name");
to check output ---->
install serial bluetooth terminal in Mobile
OPEN APP:
CONNECT THE PAIRED DEVICE to Bluetooth
check the values
5. To interface Bluetooth with Arduino/Raspberry Pi and write a program to turn LED
ON/OFF when '1'/'0' is received from smartphone using Bluetooth.
#include "BluetoothSerial.h"
// Check if Bluetooth configs are enabled
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
// Bluetooth Serial object
BluetoothSerial SerialBT;
// GPIO where LED is connected to
const int ledPin = 18;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(115200);
// Bluetooth device name
SerialBT.begin("ESP32test");
Serial.println("The device started, now you can pair it with bluetooth!");
}
void loop() {
char val;
if (SerialBT.available()){
val = SerialBT.read();
if (val =='1')
digitalWrite(ledPin,HIGH);
if (val =='0')
digitalWrite(ledPin,LOW);
}
}
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#define DHTPIN 32
#define DHTTYPE DHT11
DHT_Unified dht(DHTPIN, DHTTYPE);
#include <WiFi.h>
#include "ThingSpeak.h"
const char* ssid = "Namratha";// your network SSID (name)
const char* password = "kruthika";// your network password
WiFiClient client;
unsigned long myChannelNumber = 2;
const char *myWriteAPIKey = "KM0DAH7DAEWSL9P8";
// Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 30000;
float temperatureC;
float humidityP;
void setup() {
Serial.begin(115200); //Initialize serial
dht.begin();
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void loop() {
if ((millis() - lastTime) > timerDelay) {
// Connect or reconnect to WiFi
if(WiFi.status() != WL_CONNECTED){
Serial.print("Attempting to connect");
while(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, password);
delay(5000);
}
Serial.println("\nConnected.");
}
sensors_event_t event;
dht.temperature().getEvent(&event);
temperatureC=event.temperature;
dht.humidity().getEvent(&event);
humidityP=event.relative_humidity;
Serial.print("Temperature: ");
Serial.print(temperatureC);
Serial.println("°C");
Serial.print("Relative Humidity: ");
Serial.print(humidityP);
Serial.println("%");
// set the fields with the values
ThingSpeak.setField(1,temperatureC);
ThingSpeak.setField(2,humidityP);
// Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8
different
// pieces of information in a channel. Here, we write to field 1.
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if(x == 200){
Serial.println("Channel update successful.");
}
else{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
lastTime = millis();
}
}
7. Write a program on Arduino/Raspberry Pi to retrieve temperature and humidity
data from thingspeak cloud.
// Write a program on Arduino/Raspberry Pi to
//retrieve temperature and humidity data from thingspeak
//cloud.
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#define DHTPIN 32
#define DHTTYPE DHT11
DHT_Unified dht(DHTPIN, DHTTYPE);
#include <WiFi.h>
#include "ThingSpeak.h"
const char* ssid = "Namratha";// your network SSID (name)
const char* password = "kruthika";// your network password
WiFiClient client;
unsigned long myChannelNumber = 3;
const char * myWriteAPIKey = "M62TBVDF7LA9F2O3";
const char* readAPIKey = "P261LAD39SDRKP2X";
const long channelID =2456613 ;
const unsigned int firstReadFieldNumber = 1;
const unsigned int secondReadFieldNumber = 2;
const unsigned int switchField = 3; // Field number (1-8) to use to change status of device.
Determines if data is read from ThingSpeak.
// Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 30000;
float temperatureC;
float humidityP;
float temperatureR;
float humidityR;
void setup() {
Serial.begin(115200); //Initialize serial
dht.begin();
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void loop() {
if ((millis() - lastTime) > timerDelay) {
// Connect or reconnect to WiFi
if(WiFi.status() != WL_CONNECTED){
Serial.print("Attempting to connect");
while(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, password);
delay(5000);
}
Serial.println("\nConnected.");
}
sensors_event_t event;
dht.temperature().getEvent(&event);
temperatureC=event.temperature;
dht.humidity().getEvent(&event);
humidityP=event.relative_humidity;
Serial.print("Temperature: ");
Serial.print(temperatureC);
Serial.println("°C");
Serial.print("Relative Humidity: ");
Serial.print(humidityP);
Serial.println("%");
// set the fields with the values
ThingSpeak.setField(1,temperatureC);
ThingSpeak.setField(2,humidityP);
if(x == 200){
Serial.println("Channel update successful.");
}
else{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
temperatureR= ThingSpeak.readFloatField(channelID,firstReadFieldNumber,readAPIKey);
Serial.println(" Temperature read from ThingSpeak "+String(temperatureR));
humidityR= ThingSpeak.readFloatField(channelID,secondReadFieldNumber,readAPIKey);
Serial.println(" Humidity read from ThingSpeak "+String(humidityR));
lastTime = millis();
}
}
9. Write a program on Arduino/Raspberry Pi to publish temperature data to MQTT
broker.
12. Write a program on Arduino/Raspberry Pi to subscribe to MQTT broker for
temperature data and print it.
#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
#define DHTPIN 32 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "abcd";
const char* password = "ZXCV@098";
char *mqttServer = "broker.hivemq.com";
//char *mqttServer = "test.mosquitto.org";
int mqttPort = 1883;
void setupMQTT() {
mqttClient.setServer(mqttServer, mqttPort);
mqttClient.setCallback(callback);
}
void reconnect() {
Serial.println("Connecting to MQTT Broker...");
while (!mqttClient.connected()) {
Serial.println("Reconnecting to MQTT Broker..");
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
if (mqttClient.connect(clientId.c_str())) {
Serial.println("Connected.");
// subscribe to topic
mqttClient.subscribe("esp32/message");
}
}
}
void setup() {
Serial.begin(9600);
Serial.println("DHT11 test!");
dht.begin();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected to Wi-Fi");
pinMode(2, OUTPUT);
setupMQTT();
}
void loop() {
if (!mqttClient.connected())
reconnect();
mqttClient.loop();
long now = millis();
long previous_time = 0;
if (now - previous_time > 4000) {
previous_time = now;
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
char tempString[8];
dtostrf(t, 1, 2, tempString);
Serial.print("Temperature: ");
Serial.println(tempString);
mqttClient.publish("esp32/temperature", tempString);
char humString[8];
dtostrf(h, 1, 2, humString);
Serial.print("Humidity: ");
Serial.println(humString);
mqttClient.publish("esp32/humidity", humString);
delay(4000);
}
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Callback - ");
Serial.print("Message:");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
if (String(topic) == "esp32/message") {
Serial.print("Changing output to ");
if(messageTemp == "on"){
Serial.println("on");
digitalWrite(2, HIGH);
}
else if(messageTemp == "off"){
Serial.println("off");
digitalWrite(2, LOW);
}
}
}
10. Write a program to create UDP server on Arduino/Raspberry Pi and respond with
humidity data to UDP client when requested.
#include <WiFi.h>
#include <WiFiUdp.h>
#include <DHT.h>
// Replace with your network credentials
const char* ssid = "abcd";
const char* password = "ZXCV@098";
// Replace with your DHT sensor type and pin
#define DHT_PIN 32
#define DHT_TYPE DHT11
// UDP server port
#define UDP_PORT 5000
// Create an instance of the DHT sensor
DHT dht(DHT_PIN, DHT_TYPE);
WiFiUDP udp;
float humidity = 0.0;
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Print the ESP32 IP address
Serial.print("ESP32 IP address: ");
Serial.println(WiFi.localIP());
// Start the UDP server
udp.begin(UDP_PORT);
while (client.connected()) {
if (client.available()) {
String request = client.readStringUntil('\r');
client.flush();
if (request.indexOf("/humidity") != -1) {
// Read humidity data from DHT sensor
float humidity = dht.readHumidity();
if (isnan(humidity)) {
Serial.println("Failed to read humidity from DHT sensor");
client.println("Failed to read humidity from DHT sensor");
} else {
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println("%");
client.print("Humidity: ");
client.print(humidity);
client.println("%");
}
}
// Close the connection
client.stop();
Serial.println("Client disconnected");
}
}
}
}