0% found this document useful (0 votes)
6 views

iot pgms

iot

Uploaded by

gowdabhavya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

iot pgms

iot

Uploaded by

gowdabhavya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

IoT (Internet of Things) Lab- 21EC581

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.
Title: LED Blink Program (Utilizing Inbuilt LED Module)
void setup() {
pinMode(2,OUTPUT);
}
void loop() {
digitalWrite(2,HIGH); //on
delay(1000);// 1000ms = 1sec
digitalWrite(2,LOW); //off
delay(1000);// 1000ms = 1sec
}

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
}

Department of Electronics and Communication Engineering, B.I.T 1


IoT (Internet of Things) Lab- 21EC581

Title: Program to Display Output in Serial Monitor


Steps to open the Serial Monitor:
1. Go to the "Tools" menu.
2. Select "Serial Monitor".
3. If you encounter the comment "Board at COM7 is not available," it indicates that the
Serial Monitor has been added. Alternatively, it may be present at the top right corner
of the window.

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

Department of Electronics and Communication Engineering, B.I.T 2


IoT (Internet of Things) Lab- 21EC581

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;

Department of Electronics and Communication Engineering, B.I.T 3


IoT (Internet of Things) Lab- 21EC581

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

Department of Electronics and Communication Engineering, B.I.T 4


IoT (Internet of Things) Lab- 21EC581

DHT_Unified dht(DHTPIN, DHTTYPE);


void setup() {
Serial.begin(115200);
dht.begin();
}
void loop() {
sensors_event_t event; // It's a class underthat I'LL give name event
dht.temperature().getEvent(&event); // dht is object ,&-- address of object
Serial.print("Temperature: ");// print temp
Serial.print(event.temperature);// under event it displays temp
Serial.println("°C");
dht.humidity().getEvent(&event);
Serial.print("Relative Humidity: ");
Serial.print(event.relative_humidity);// serial is object
Serial.println("%");
delay(2000);
}

ii) To interface OLED with Arduino/Raspberry Pi and write a program to print


temperature and humidity readings on it.
#include <Arduino.h>
#include <U8x8lib.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
U8X8_SH1106_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#define DHTPIN 32
#define DHTTYPE DHT11

Department of Electronics and Communication Engineering, B.I.T 5


IoT (Internet of Things) Lab- 21EC581

DHT_Unified dht(DHTPIN, DHTTYPE);


void setup(void)
{
u8x8.begin();
u8x8.setPowerSave(0);
u8x8.setFont(u8x8_font_chroma48medium8_r);
dht.begin();
}
void loop(void)
{
u8x8.setCursor (0,1);
sensors_event_t event;
// get temperature and print as float
dht.temperature().getEvent(&event);
u8x8.print("Temp:");
u8x8.print(event.temperature);
u8x8.print(" Cels");
// get humidity and print as integer
u8x8.setCursor(0,3);
dht.humidity().getEvent(&event);
u8x8.print("Hum:");
u8x8.print(event.relative_humidity);
u8x8.print("%");
delay(2000);
}

Department of Electronics and Communication Engineering, B.I.T 6


IoT (Internet of Things) Lab- 21EC581

3. To interface motor using relay with Arduino/Raspberry Pi and write a program to


‘turn ON’ motor when push button is pressed.
// To interface motor using relay with Arduino/Raspberry
// Pi and write a program to ‘turn ON’ motor when
// push button is pressed.
void setup() {
// put your setup code here, to run once:
pinMode(13,OUTPUT);
pinMode(35,INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
if(digitalRead(35))
{
digitalWrite(13,HIGH);
}
else
{
digitalWrite(13,LOW);
}
}
output -
4. To interface Bluetooth with Arduino/Raspberry Pi and write a program to send
sensor data to smartphone using Bluetooth.
// To interface Bluetooth with Arduino/Raspberry Pi and
// write a program to send sensor data to smartphone
// using Bluetooth.
// Load libraries
#include "BluetoothSerial.h"
// Check if Bluetooth configs are enabled
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)

Department of Electronics and Communication Engineering, B.I.T 7


IoT (Internet of Things) Lab- 21EC581

#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

Department of Electronics and Communication Engineering, B.I.T 8


IoT (Internet of Things) Lab- 21EC581

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);
}
}

Department of Electronics and Communication Engineering, B.I.T 9


IoT (Internet of Things) Lab- 21EC581

program to connect hotspot and wifi(example program)


#include<WiFi.h>//to access wi fi
//enter SSID and password of your wi fi router
char ssid[]="Namratha";//
char pass[]="kruthika";
void setup()
{
Serial.begin(115200);
pinMode(2,OUTPUT);
WiFi.mode(WIFI_STA);//set wifi mode as station
WiFi.begin(ssid,pass);//begin connection
Serial.println();
Serial.println("Connecting to");
Serial.print(ssid);
}
void loop(){
while(WiFi.status()!=WL_CONNECTED)//macro named wireless connected
{
delay(500);
Serial.print(".");
digitalWrite(2,LOW);
}
Serial.print("connected ,IP address:");
Serial.println(WiFi.localIP());//display IP assigned by wifi router
digitalWrite(2,HIGH);
delay(2000);
}
6. Write a program on Arduino/Raspberry Pi to upload temperature and humidity data
to thingspeak cloud.

#include <Adafruit_Sensor.h>

Department of Electronics and Communication Engineering, B.I.T 10


IoT (Internet of Things) Lab- 21EC581

#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);

Department of Electronics and Communication Engineering, B.I.T 11


IoT (Internet of Things) Lab- 21EC581

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();
}

Department of Electronics and Communication Engineering, B.I.T 12


IoT (Internet of Things) Lab- 21EC581

}
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;

Department of Electronics and Communication Engineering, B.I.T 13


IoT (Internet of Things) Lab- 21EC581

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

Department of Electronics and Communication Engineering, B.I.T 14


IoT (Internet of Things) Lab- 21EC581

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));
}

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;

Department of Electronics and Communication Engineering, B.I.T 15


IoT (Internet of Things) Lab- 21EC581

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();

Department of Electronics and Communication Engineering, B.I.T 16


IoT (Internet of Things) Lab- 21EC581

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];

Department of Electronics and Communication Engineering, B.I.T 17


IoT (Internet of Things) Lab- 21EC581

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);
}
}
}

Department of Electronics and Communication Engineering, B.I.T 18


IoT (Internet of Things) Lab- 21EC581

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);

Department of Electronics and Communication Engineering, B.I.T 19


IoT (Internet of Things) Lab- 21EC581

Serial.println("UDP server started");

// Initialize DHT sensor


dht.begin();
}
void loop() {
// Wait for incoming UDP packets
int packetSize = udp.parsePacket();
if (packetSize) {
// Read the incoming packet
char packetData[packetSize];
udp.read(packetData, packetSize);
String request = String(packetData);
if (request == "get_humidity") {
// Read humidity from the DHT sensor
humidity = dht.readHumidity();
// Send humidity data to the UDP client
udp.beginPacket(udp.remoteIP(), udp.remotePort());
udp.printf("Humidity: %.2f%%", humidity);
udp.endPacket();
Serial.printf("Sent humidity data: %.2f%%\n", humidity);
}
}
}
11. Write a program to create TCP server on Arduino/Raspberry Pi and respond with
humidity data to TCP client when requested.
#include <WiFi.h>
#include <WiFiClient.h>
#include <DHT.h>
// Replace with your network credentials
const char* ssid = "abcd";

Department of Electronics and Communication Engineering, B.I.T 20


IoT (Internet of Things) Lab- 21EC581

const char* password = "ZXCV@098";


// Replace with your DHT sensor type and pin number
#define DHT_PIN 32
#define DHT_TYPE DHT11
DHT dht(DHT_PIN, DHT_TYPE);
WiFiServer server(8888); // TCP server port
void setup() {
Serial.begin(115200);
delay(10);
// Connect to Wi-Fi
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
dht.begin();
server.begin();
}
void loop() {
WiFiClient client = server.available();
if (client) {
Serial.println("New client connected");
// Wait for data from client

Department of Electronics and Communication Engineering, B.I.T 21


IoT (Internet of Things) Lab- 21EC581

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");
}
}
}
}

Department of Electronics and Communication Engineering, B.I.T 22


IoT (Internet of Things) Lab- 21EC581

12.Displaying "Hello World" on an LCD Connected to Arduino


//Compatible with the Arduino IDE 1.0
//Library version:1.1
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line
display
void setup()
{
// initialize LCD
lcd.init();
// turn on LCD backlight
lcd.backlight();
lcd.setCursor(0,1);
lcd.print("HELLO WORLD ");
}
void loop()
{
}
OUTPUT:

Department of Electronics and Communication Engineering, B.I.T 23

You might also like