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

IOT Lab Experiments

The document contains descriptions of 7 experiments involving interfacing various sensors and devices with Arduino. Experiment 1 involves interfacing an LED and buzzer with Arduino. Experiment 2 involves interfacing a DHT11 temperature and humidity sensor and displaying the readings on an OLED screen. Experiment 3 involves using an IR sensor to control a relay. Experiment 4 involves sending sensor data to a smartphone over Bluetooth. Experiment 5 involves controlling an LED remotely over Bluetooth. Experiment 6 involves sending sensor data to ThingSpeak using WiFi. Experiment 7 involves reading data from a ThingSpeak channel over WiFi.

Uploaded by

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

IOT Lab Experiments

The document contains descriptions of 7 experiments involving interfacing various sensors and devices with Arduino. Experiment 1 involves interfacing an LED and buzzer with Arduino. Experiment 2 involves interfacing a DHT11 temperature and humidity sensor and displaying the readings on an OLED screen. Experiment 3 involves using an IR sensor to control a relay. Experiment 4 involves sending sensor data to a smartphone over Bluetooth. Experiment 5 involves controlling an LED remotely over Bluetooth. Experiment 6 involves sending sensor data to ThingSpeak using WiFi. Experiment 7 involves reading data from a ThingSpeak channel over WiFi.

Uploaded by

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

Experiment 1.

1
Aim:
To interface LED/Buzzer with Arduino and write a program to ‘turn ON’ LED for 1 sec after
every 2 seconds.
Program:

const int ledPin = 13;


void setup() {
pinMode(ledPin, OUTPUT);
}

void loop() {
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(2000);
}
Experiment 1.2
Aim:
To interface IR sensor with Arduino and write a program to ‘turn ON’ LED when sensor
detection.
Program:

void setup() {
Serial.begin(9600);
pinMode(2,INPUT); // IR sensor(out pin) input to arduino uno
pinMode(10,OUTPUT); // Arduino 10th pin connect to the LED positive
}

void loop() {
int sensor_state=digitalRead(2);
if(sensor_state==1){
Serial.println("Motion Detected");
digitalWrite(10,HIGH);

}else{
Serial.println("Motion Not Detected");
digitalWrite(10,LOW);

}
}

Circuit Diagram:
Experiment 2.1
Aim:
To interface DHT11 sensor with Arduino and write a program to print temperature and humidity
readings.
Program:

#include "DHT.h"

#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

void setup() {
Serial.begin(9600);
Serial.println(F("DHTxx test!"));

dht.begin();
}

void loop() {
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature();

if (isnan(h) || isnan(t) || isnan(f)) {


Serial.println(F("Failed to read from DHT sensor!"));
return;
}

Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(F("% Temperature: "));
Serial.print(t);
Serial.println(F(" degree C "));

Circuit Diagram:
Experiment 2.2
Aim:
To interface OLED with Arduino and write a program to print temperature and humidity
readings on it.
Program:

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "DHT.h"

#define dhtpin 2
#define dhttype DHT11

DHT dht(dhtpin, dhttype);

Adafruit_SSD1306 myDisplay(128, 64, &Wire);

void setup() {
myDisplay.begin(SSD1306_SWITCHCAPVCC, 0x3C);
dht.begin();
}

void loop() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
myDisplay.clearDisplay();

myDisplay.setTextSize(1);
myDisplay.setCursor(0,0);
myDisplay.setTextColor(WHITE);
myDisplay.print("Temperature: ");
myDisplay.print(temperature);
myDisplay.println(" °C");
myDisplay.print("Humidity: ");
myDisplay.print(humidity);
myDisplay.println(" %");

myDisplay.display();
delay(3000);
}

Circuit Diagram:
Experiment 3
Program:

void setup() {
pinMode(2,INPUT); //IR sensor input
pinMode(10,OUTPUT); // output of arduino uno to input of the relay
}

void loop() {
int sensor_state=digitalRead(2);
if(sensor_state==1){
digitalWrite(10,HIGH);
}else{
digitalWrite(10,LOW);
}
}

Circuit Diagram:
Experiment 4
Aim:
To interface Bluetooth with Arduino and write a program to send sensor data to smartphone
using Bluetooth.
Procedure:
Install Serial Bluetooth Terminal in smart phone

Configuring with AT Commands (HC-05)

*AT command Mode*

1. Disconnect the +5v line from the modules end as shown in the hook diagram above.

2. Press and hold the switch (DO NOT RELEASE IT!)

3. Reconnect the +5v connection

4. Now Release the switch. Observe that the led on the module starts blinking once every
two seconds, slower than normal disconnected mode.

5. Upload the code below to the Arduino.

Program:

#include <SoftwareSerial.h>
#include "DHT.h"

#define dhtpin 2
#define dhttype DHT11
SoftwareSerial EEBlue(11, 10); // RX | TX(10,11)

DHT dht(dhtpin, dhttype);


void setup()
{

Serial.begin(9600);
configure_HC05();
EEBlue.begin(9600); //Default Baud for comm, it may be different for your
Module.
Serial.println("The bluetooth gates are open.\n Connect to HC-05 from any
other bluetooth device with 0000 OR 1234 as pairing key!.");
dht.begin();

void loop()
{
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
Serial.print("Temperature: ");
delay(100);
Serial.print(temperature);
delay(500);
Serial.print(" °C, Humidity: ");
delay(100);
Serial.print(humidity);
delay(500);
Serial.println(" %");
delay(100);

EEBlue.print("Temperature: ");
delay(100);
EEBlue.print(temperature);
delay(500);
EEBlue.print(" degree C, Humidity: ");
delay(100);
EEBlue.print(humidity);
delay(500);
EEBlue.println(" %");
delay(2000);

}
void configure_HC05(){
EEBlue.begin(38400);
EEBlue.println("AT");
delay(500);
EEBlue.println("AT+NAME=USN046");
delay(1000);
EEBlue.println("AT+RESET");
delay(1000);
}

Circuit Diagram:
Experiment 5
Aim:
To interface Bluetooth with Arduino and write a program to turn LED ON/OFF when '1'/'0' is
received from smartphone using Bluetooth.
Procedure:
Install Serial Bluetooth Terminal in smart phone

Configuring with AT Commands (HC-05)

*AT command Mode*

1. Disconnect the +5v line from the modules end as shown in the hook diagram above.

2. Press and hold the switch (DO NOT RELEASE IT!)

3. Reconnect the +5v connection

4. Now Release the switch. Observe that the led on the module starts blinking once every
two seconds, slower than normal disconnected mode.

5. Upload the code below to the Arduino.

Program:

#include <SoftwareSerial.h>

const int LED= 13;


const char turnON ='1';
const char turnOFF ='0';
SoftwareSerial EEBlue(11, 10); // RX | TX

void setup()
{

Serial.begin(9600);
pinMode(LED, OUTPUT);
configure_HC05();
EEBlue.begin(9600); //Default Baud for comm, it may be different for your
Module.
Serial.println("The bluetooth gates are open.\n Connect to HC-05 from any
other bluetooth device with 1234 as pairing key!.");
Serial.print("Now You can TURN ON LED by sending '1' and TURN OFF by '0'");
EEBlue.println("Now You can TURN ON LED by sending '1' and TURN OFF by
'0'");
}

void loop()
{
char message;

if (EEBlue.available()) {
message=EEBlue.read();
Serial.write(message);

if(message==turnON){
digitalWrite(LED, HIGH); //Turn LED ON
Serial.println(" :LED Turned ON");
EEBlue.println(" :LED Turned ON");
delay(500);
}

else if(message==turnOFF){
digitalWrite(LED, LOW); //Turn LED Off
Serial.println(" :LED Turned OFF");
EEBlue.println(" :LED Turned OFF");
delay(500);
}
}

}
void configure_HC05(){
EEBlue.begin(38400);
EEBlue.println("AT");
delay(500);
EEBlue.println("AT+NAME=USN046");
delay(1000);
EEBlue.println("AT+RESET");
delay(1000);
}

Circuit Diagram:
Experiment 6
Program:

#include "WiFiEsp.h"
#include "ThingSpeak.h" // always include thingspeak header file after other
header files and custom macros
#include "DHT.h"

#define dhtpin 2
#define dhttype DHT11

DHT dht(dhtpin,dhttype);
char ssid[] = "SATHISH"; // change your wifi ssid
char pass[] = "123456789"; // change your wifi password
unsigned long myChannelNumber = 2296803; // change your thingspeak channel ID

const char * myWriteAPIKey = "IN3JETGQSH3DV2IX"; // change your thingspeak


write api key
WiFiEspClient client;

#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX

String myStatus = "";

void setup() {
Serial.begin(115200); // Initialize serial
dht.begin(); // Initialize serial for DHT sensor

Serial1.begin(19200); // initialize serial for ESP module


Serial.print("Searching for ESP8266...");
// initialize ESP module
WiFi.init(&Serial1);
// Connect or reconnect to WiFi
if(WiFi.status() != WL_CONNECTED){
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
while(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, pass); // Connect to WPA/WPA2 network. Change this
line if using open or WEP network
Serial.print(".");
delay(5000);
}
Serial.println("\nConnected.");
}

ThingSpeak.begin(client); // Initialize ThingSpeak


}
void loop() {
float t=dht.readTemperature();
float h=dht.readHumidity();
ThingSpeak.setField(1, t);
ThingSpeak.setField(2, h);
// set the status
ThingSpeak.setStatus(myStatus);
// write to the ThingSpeak channel
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));
}
delay(20000); // Wait 20 seconds to update the channel again
}

Circuit Diagram:
Experiment 7
Program:

#include "WiFiEsp.h"
#include "ThingSpeak.h" // always include thingspeak header file after other
header files and custom macros
char ssid[] = "SATHISH"; // change your wifi ssid
char pass[] = "123456789"; // change your wifi password
unsigned long counterChannelNumber = 2296803; // change your thingspeak
channel ID
const char * myCounterReadAPIKey = "ZJN3QM0H28MHAVF5";// change your
thingspeak read api key

WiFiEspClient client;

#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX

void setup() {
Serial.begin(115200); //Initialize serial and wait for port to open
Serial1.begin(19200); // initialize serial for ESP module
Serial.print("Searching for ESP8266...");
// initialize ESP module
WiFi.init(&Serial1);
delay(5000);
if(WiFi.status() != WL_CONNECTED){
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
while(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, pass); // Connect to WPA/WPA2 network. Change this line
if using open or WEP network
Serial.print(".");
delay(5000);
}
Serial.println("\nConnected");
}
ThingSpeak.begin(client); // Initialize ThingSpeak
}

void loop() {
int statusCode = 0;
float temperature = ThingSpeak.readFloatField(counterChannelNumber, 1,
myCounterReadAPIKey); //1 indicates temperature field in thingspeak.com(my
channel)
delay(1000);
float humidity=ThingSpeak.readFloatField(counterChannelNumber, 2,
myCounterReadAPIKey); //2 indicates humidity field in thingspeak.com(my
channel)
// Check the status of the read operation to see if it was successful
statusCode = ThingSpeak.getLastReadStatus();
delay(2000);
if(statusCode == 200){
Serial.println("Temperature: " + String(temperature)+" deg C");
Serial.println("Humidity: "+String(humidity)+" %");
}
else{
Serial.println("Problem reading channel. HTTP error code " +
String(statusCode));
}
delay(15000); // No need to read the counter too often.
}

Circuit Diagram:
Experiment 9
Program:

#include <DHT.h>
#include <WiFiEsp.h>
#include <SoftwareSerial.h>
#include <PubSubClient.h>

#define DHTPIN 2 // connect to D4 on ESP-01


#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

SoftwareSerial Serial1(6, 7); // RX, TX for ESP-01

char ssid[] = "SATHISH"; // change your wifi ssid


char pass[] = "123456789"; // change your wifi password

WiFiEspClient espClient;
PubSubClient client(espClient);

const char* mqtt_server = "mqtt3.thingspeak.com"; // change your mqtt server

const char* publishTopic = "channels/2296803/publish"; // REPLACE WITH YOUR


CHANNEL ID
const char* subscribeTopicFor_Command_1 =
"channels/2296803/subscribe/fields/field1"; // REPLACE WITH YOUR CHANNEL ID

const unsigned long postingInterval = 20L * 1000L; // Post data every 20


seconds.

unsigned long lastUploadedTime = 0;

void setup_wifi() {
delay(10);
Serial.print("\nConnecting to ");
Serial.println(ssid);

WiFi.init(&Serial1);
int status = WiFi.begin(ssid, pass);

while (status != WL_CONNECTED) {


delay(500);
Serial.print(".");
status = WiFi.begin(ssid, pass);
}

randomSeed(micros());
Serial.println("\nWiFi connected\nIP address: ");
Serial.println(WiFi.localIP());
}

void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("JwgTGQc1HikbMBwpNC4RISs", "JwgTGQc1HikbMBwpNC4RISs",
"w25Z2L14X8OkDNwIgttnlk8k")) { // REPLACE WITH YOUR MQTT USERNAME AND
PASSWORD
Serial.println("connected");
client.subscribe(subscribeTopicFor_Command_1);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}

void callback(char* topic, byte* payload, unsigned int length) {


String incomingMessage = "";
for (int i = 0; i < length; i++) incomingMessage += (char)payload[i];

Serial.println("Message arrived [" + String(topic) + "] " +


incomingMessage);
}

void publishMessage(const char* topic, String payload, boolean retained) {


if (client.publish(topic, payload.c_str(), retained)) {
Serial.println("Message published [" + String(topic) + "]: " + payload);
}
}

void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(115200);
Serial1.begin(19200);
dht.begin();

setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}

void loop() {
float temperature = dht.readTemperature();
if (!client.connected()) {
reconnect();
}
client.loop();

if (millis() - lastUploadedTime > postingInterval) {


String dataText = String("field1=" +
String(temperature)+"&status=MQTTPUBLISH");
publishMessage(publishTopic, dataText, true);
lastUploadedTime = millis();
}
}

Circuit Diagram:
Experiment 10
Program 1 in Arduino IDE – UDP Server:

#include <DHT.h>
#include <WiFiEsp.h>
#include <WiFiEspUdp.h>
#include "SoftwareSerial.h"
// Replace pin and type with your sensor details
#define DHTPIN 2 // connect to D4 on ESP-01
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
// SoftwareSerial pins for communication with ESP-01
SoftwareSerial Serial1(6, 7); // RX, TX
// WiFi settings
char ssid[] = "SATHISH"; // change your wifi ssid
char pass[] = "123456789"; // change your wifi password
WiFiEspUDP udp;
void setup() {
Serial.begin(115200);
Serial1.begin(19200);
WiFi.init(&Serial1);

connectToWiFi();
// Print the local IP address
Serial.print("Arduino IP Address: ");
Serial.println(WiFi.localIP());
// Initialize the DHT sensor
dht.begin();
// Start UDP
udp.begin(8888);
}

void loop() {
// Check if data is available to read
int packetSize = udp.parsePacket();
if (packetSize) {
// Read the request
char request[packetSize];
udp.read(request, packetSize);
request[packetSize] = '\0'; // Null-terminate the string
// Check the request content
if (strcmp(request, "GET_HUMIDITY") == 0) {
float humidity = dht.readHumidity();
char response[10];
//snprintf(response, sizeof(response), "%.2f", humidity); don't use this
line creating error
dtostrf(humidity, 4, 2, response);
// Send the response to the UDP client
udp.beginPacket(udp.remoteIP(), udp.remotePort());
udp.write(response, strlen(response));
udp.endPacket();
}
}
}
void connectToWiFi() {
Serial.println("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
if (WiFi.begin(ssid, pass) != WL_CONNECTED) {
Serial.println("Failed to connect to WiFi. Retrying...");
delay(5000);
}
}
Serial.println("Connected to WiFi");
}

Program 2 in Python(Idle) – UDP Client for data request to verify:


import socket

UDP_IP = "192.168.43.37" # change your board IP address


UDP_PORT = 8888
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()
Circuit Diagram:
Experiment 11
Program 1 in Arduino IDE – TCP Server:

#include <DHT.h>
#include <WiFiEsp.h>
#include "SoftwareSerial.h"

// Replace pin and type with your sensor details


#define DHTPIN 2 // connect to D4 on ESP-01
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

// SoftwareSerial pins for communication with ESP-01


SoftwareSerial Serial1(6, 7); // RX, TX

// WiFi settings
char ssid[] = "SATHISH"; // change your wifi ssid
char pass[] = "123456789"; // change your wifi password

WiFiEspServer server(80); // Port 80 for HTTP

void setup() {
Serial.begin(115200);
Serial1.begin(19200);

WiFi.init(&Serial1);

// Connect to WiFi
connectToWiFi();

// Print the local IP address


Serial.print("Arduino IP Address: ");
Serial.println(WiFi.localIP());

// Initialize the DHT sensor


dht.begin();

// Start the server


server.begin();
}

void loop() {
// Check for a client request
WiFiEspClient client = server.available();

if (client) {
Serial.println("New client connected");
// Read the request
String request = client.readStringUntil('\r');
Serial.println(request);

// Check the request content


if (request.indexOf("GET_HUMIDITY") != -1) {
// Respond with humidity data
float humidity = dht.readHumidity();
char response[10];
dtostrf(humidity, 4, 2, response);
//sending response
client.println(response);

// Close the connection


client.stop();
Serial.println("Client disconnected");
}

// Other tasks in your loop can go here


}

void connectToWiFi() {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Connecting to WiFi");
while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
Serial.println("Failed to connect to WiFi. Retrying...");
delay(5000);
}
Serial.println("Connected to WiFi");
}
}

Program 2 in Python(Idle) – TCP Client for data request to verify:


import socket

TCP_IP = "192.168.43.37" # Replace with the actual IP address of your ESP8266


TCP_PORT = 80

def send_tcp_request(request):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((TCP_IP, TCP_PORT))
s.sendall(request.encode())
response = s.recv(1024).decode()
print("Received response:", response)

# Test the "GET_HUMIDITY" request


send_tcp_request("GET_HUMIDITY")

Circuit Diagram:
Experiment 12
Program:

#include <WiFiEsp.h>
#include <SoftwareSerial.h>
#include <PubSubClient.h>

SoftwareSerial Serial1(6, 7); // RX, TX for ESP-01

char ssid[] = "SATHISH"; // change your wifi ssid


char pass[] = "123456789"; // change your wifi password

WiFiEspClient espClient;
PubSubClient client(espClient);

const char* mqtt_server = "mqtt3.thingspeak.com";

const char* subscribeTopicFor_Field1 =


"channels/2296803/subscribe/fields/field1"; // REPLACE WITH YOUR CHANNEL ID

void setup_wifi() {
delay(10);
Serial.print("\nConnecting to ");
Serial.println(ssid);

WiFi.init(&Serial1);
int status = WiFi.begin(ssid, pass);

while (status != WL_CONNECTED) {


delay(500);
Serial.print(".");
status = WiFi.begin(ssid, pass);
}

randomSeed(micros());
Serial.println("\nWiFi connected\nIP address: ");
Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {


String incomingMessage = "";
for (int i = 0; i < length; i++) incomingMessage += (char)payload[i];

Serial.println("Message arrived [" + String(topic) + "] " +


incomingMessage);
}

void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("JwgTGQc1HikbMBwpNC4RISs", "JwgTGQc1HikbMBwpNC4RISs",
"w25Z2L14X8OkDNwIgttnlk8k")) {
Serial.println("connected");
// Subscribe to the desired topics here
client.subscribe(subscribeTopicFor_Field1);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}

void setup() {
Serial.begin(115200);
Serial1.begin(19200);

setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}

void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}

Circuit Diagram:

You might also like