IOT Lab - PDF Final

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

Name – Kaushalendra Singh EC2 19EEAEC037

EXPERIMENT-01
Objective - Study the fundamental of IOT software’s and components.

Experimental requirement-
1. IoT software’s
2. IoT components

Theory-
IoT Software’s: -
The software and the programming languages on which IoT works uses very common
programming languages that programmers use.
Firstly, because embedded systems have less storage and processing power, their language
needs are different. The most used operating systems for such embedded systems are Linux or
UNIX-like OSs like Ubuntu Core or Android.
IoT software encompasses a wide range of software and programming languages from general-
purpose languages like C++ and Java to embedded-specific choices like Google’s Go language
or Parasail.
• C & C++: The C programming language has its roots in embedded systems—it even
got its start for programming telephone switches. C++ is the object-oriented version of
C, which is a language popular for both the Linux OS and Arduino embedded IoT
software systems. These languages were basically written for the hardware systems
which makes them so easy to use.
• Java: While C and C++ are hardware specific, the code in JAVA is more portable. It is
more like a write once and read anywhere language, where you install libraries, invests
time in writing codes once and you are good to go.
• Python: Its use is slowly spreading to the embedded control and IoT world—specially
the Raspberry Pi processor. Python is an interpreted language, which is, easy to read,
quick to learn and quick to write. Also, it’s a powerhouse for serving data-heavy
applications.
• B#: Unlike most of the languages mentioned so far, B# was specifically designed for
embedded systems, it’s small and compact and has less memory size.
• Data Collection: It is used for data filtering, data security, sensing, and measurement.
The protocols aid in decision making by sensing form real-time objects. It can work
both ways by collecting data from devices or distributing data to devices. All the data
transmits to a central server.
• Device Integration: This software ensures that devices bind and connect to networks
facilitating information sharing. A stable cooperation and communication ensure
between multiple devices.
• Real-Time Analytics: In this, the input from users serves as potential data for carrying
out real-time analysis, making insights, suggesting recommendations to solve an
organizations problem and improve its approach. This, as a result, allows automation
and increased productivity.
Name – Kaushalendra Singh EC2 19EEAEC037

• Application and Process Extension: These applications extend the reach of existing
systems and software to allow a wider, more effective system. They integrate predefined
devices for specific purposes such as allowing certain mobile devices or

engineering instruments access. It supports improved productivity and more accurate


data collection.

IoT Components: -
Here, 4 fundamental components of IoT system, which tells us how IoT works.

Sensors/Devices
First, sensors or devices help in collecting very minute data from the surrounding environment.
All of this collected data can have various degrees of complexities ranging from a simple
temperature monitoring sensor or a complex full video feed.
A device can have multiple sensors that can bundle together to do more than just sense things.
For example, our phone is a device that has multiple sensors such as GPS, accelerometer,
camera but our phone does not simply sense things.

Connectivity
Next, that collected data is sent to a cloud infrastructure but it needs a medium for transport.
The sensors can be connected to the cloud through various mediums of communication and
transports such as cellular networks, satellite networks, Wi-Fi, Bluetooth, wide-area networks
(WAN), low power wide area network and many more.
Every option we choose has some specifications and trade-offs between power consumption,
range, and bandwidth. So, choosing the best connectivity option in the IOT system is important.

Data Processing
Once the data is collected and it gets to the cloud, the software performs processing on the
acquired data.
This can range from something very simple, such as checking that the temperature reading on
devices such as AC or heaters is within an acceptable range. It can sometimes also be very
complex, such as identifying objects (such as intruders in your house) using computer vision
on video.

User Interface
Next, the information made available to the end-user in some way. This can achieve by
triggering alarms on their phones or notifying through texts or emails.
The user interface is the visible component that is easily accessible and in control of the IoT
user. This is where a user can control the system and set their preferences.

Result- Hence, we have learnt the fundamentals of IoT softwares and IoT components.
Name – Kaushalendra Singh EC2 19EEAEC037

EXPERIMENT-02

Objective -: - Familiarization with Arduino/Raspberry Pi and perform necessary software


installation.

Experimental requirement- Arduino IDE

Theory-
Arduino is a prototype platform (open-source) based on an easy-to-use hardware and software.
It consists of a circuit board, which can be programmed (referred to as a microcontroller) and a
ready-made software called Arduino IDE (Integrated Development Environment), which is
used to write and upload the computer code to the physical board. Arduino provides a standard
form factor that breaks the functions of the microcontroller into a more accessible package.
Arduino is a prototype platform (open-source) based on an easy-to-use hardware and software.
It consists of a circuit board, which can be programmed (referred to as a microcontroller) and
ready-made software called Arduino IDE (Integrated Development Environment), which is
used to write and upload the computer code to the physical board.

The key features are −


● Arduino boards are able to read analog or digital input signal from different sensors and
turn it into an output such as activating a motor, turning LED on/off, connect to the
cloud and many other actions.
● You can control your board functions by sending a set of instruction to the
microcontroller on the board via Arduino IDE (referred to as uploading software).
● Unlike most previous programmable circuit boards, Arduino does not need an extra
piece of hardware (called a programmer) in order to load a new code on the board. You
can simply use a USB cable.
● Additionally, the Arduino IDE uses a simplified version of C++, making it easier to
learn to program.
● Finally, Arduino provides a standard form factor that breaks the functions of the
microcontroller into a more accessible package.

Download the Arduino Software (IDE)


o Get the latest version from the arduino.cc web site. You can choose between the
Installer (.exe) and the Zip packages. We suggest you use the first one that installs
directly everything you need to use the Arduino Software (IDE), including the
drivers. With the Zip package you need to install the drivers manually. The Zip file
is also useful if you want to create a portable installation.
o When the download finishes, proceed with the installation and please allow the
driver installation process when you get a warning from the operating system.

Choose the components to install


Name – Kaushalendra Singh EC2 19EEAEC037

Choose the installation directory (we suggest to keep the default one)

The process will extract and install all the required files to execute properly the Arduino
Software (IDE)
● Proceed with board specific instructions
● When the Arduino Software (IDE) is properly installed you can go back to the Different
Arduino Boards:
1. Arduino Uno: This is the latest revision of the basic Arduino USB board. It connects
to the computer with a standard USB cable and contains everything else you need to
program and use the board.
2. Arduino NG: REV-C Revision C of the Arduino NG does not have a built-in LED on
pin 13 - instead you'll see two small unused solder pads near the labels "GND" and
"13".
3. Arduino Bluetooth: The Arduino BT is a microcontroller board originally was based
on the ATmega168, but now is supplied with the 328, and the Bluegiga WT11
bluetooth module. It supports wireless serial communication over bluetooth.
4. Arduino Mega: The original Arduino Mega has an ATmega1280 and an FTDI USB-
to serial chip.
5. Arduino NANO: The Arduino Nano 3.0 has an ATmega328 and a two-layer PCB.
The power LED moved to the top of the board.

Advantages of using Arduino:


It offers some advantage for teachers, students, and interested amateurs over other
systems:
Name – Kaushalendra Singh EC2 19EEAEC037

● Inexpensive - Arduino boards are relatively inexpensive compared to other


● microcontroller platforms. The least expensive version of the Arduino module can be
assembled by hand, and even the pre-assembled Arduino modules cost less than $50
● Cross-platform - The Arduino Software (IDE) runs on Windows, Macintosh OSX, and
Linux operating systems. Most microcontroller systems are limited to Windows.
● Simple, clear programming environment - The Arduino Software (IDE) is easy-to-use
for beginners, yet flexible enough for advanced users to take advantage of as well. For
teachers, it's conveniently based on the Processing programming environment, so
students learning to program in that environment will be familiar with how the Arduino
IDE works.
● Open source and extensible software - The Arduino software is published as open source
tools, available for extension by experienced programmers. The language can be
expanded through C++ libraries, and people wanting to understand the technical details
can make the leap from Arduino to the AVR C programming language on which it's
based. Similarly, you can add AVR-C code directly into your Arduino programs if you
want to.
Open source and extensible hardware - The plans of the Arduino boards are published under a
Creative Commons license, so experienced circuit designers can make their own version of the
module, extending it and improving it. Even relatively inexperienced users can build the
breadboard version of the module in order to understand how it works and save money.

Result- Hence, we have discussed about the Arduino fundamentals and its necessary
software installation.
Name – Kaushalendra Singh EC2 19EEAEC037

EXPERIMENT-03

Objective- To interface LED/Buzzer with Arduino and write a program to turn ON LED
for 1 sec after every 2 seconds.

Experimental requirement-
1. NodeMCU-12E
2. Bread board
3. LED
4. Resistor
5. Micro USB cable
6. Arduino IDE

Circuit diagram-

Program code-
#define LED 13 void setup() {
pinMode(LED, OUTPUT); // LED pin as output.
}
void loop() {
digitalWrite(LED, HIGH);// turn the LED off
delay(1000);// wait for 1 second.
Name – Kaushalendra Singh EC2 19EEAEC037

digitalWrite(LED, LOW); // turn the LED on.


delay(2000); // wait for 2 second.
}

Output-

Result- In output section Fig.1 states HIGH state of LED after 1sec LED is at LOW state
(Fig. 2). So, we observe LED is ON for 1 sec after every 2 seconds.
Name – Kaushalendra Singh EC2 19EEAEC037

EXPERIMENT- 04

Objective- 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.

Experimental requirement-
1. NodeMCU-12E
2. Bread board
3. LED
4. Resistors
5. Push button
6. Micro USB cable
7. Connecting wires
8. Arduino IDE

Circuit diagram-

Program code-
int led = 5; // LED pin
int button = 16 ; // push button is connected
int temp = 0; // temporary variable for reading the button pin status

void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT); // declare LED as output
pinMode(button, INPUT); // declare push button as input
Name – Kaushalendra Singh EC2 19EEAEC037

void loop() {
temp = digitalRead(button);

if (temp == HIGH) {
digitalWrite(led, HIGH);
Serial.println("LED Turned ON");
}
else {
digitalWrite(led, LOW);
Serial.println("LED Turned OFF");
}
temp = 0 ;
}

Result- We have observed that LED is on when push button is pressed and LED is off when
push button is not pressed.
Name – Kaushalendra Singh EC2 19EEAEC037

EXPERIMENT- 05

Objective - To interface DHT11 sensor with Arduino/Raspberry Pi and write a program to


print temperature and humidity readings.

Experimental requirement-
1. NodeMCU-12E
2. Bread board
3. DHT sensor
4. Micro USB cable
5. Connecting wires
6. Arduino IDE

Circuit diagram-

Program code-
#include <dht.h>
#include <Adafruit_Sensor.h>

dht DHT;
#define DHT11_PIN 16

void setup() {
Serial.begin(9600);
}
Name – Kaushalendra Singh EC2 19EEAEC037

void loop() {
int chk = DHT.read11(DHT11_PIN);
Serial.print("Temperature = ");
Serial.println(DHT.temperature);
delay(1000);
Serial.print("Humidity = ");
Serial.println(DHT.humidity);
delay(1000);
}

Output-
We can check temperature and humidity readings on tools > Serial monitor.

Result-
By using DHT11 sensor we have obtained temperature and humidity readings.
Name – Kaushalendra Singh EC2 19EEAEC037

EXPERIMENT-06
Objective - To interface motor using relay with Arduino/Raspberry Pi and write a
program to turn ON motor when push button is pressed.

Experimental requirement-
Tinkercad

Circuit diagram-

Program code-
#define LED 13
#define SW 8
void setup()
{
pinMode(LED, OUTPUT);
pinMode(SW, INPUT);
}
void loop()
{
if(digitalRead(SW))
{
digitalWrite(13, HIGH);
}
else
digitalWrite(13, LOW);
delay(1000); // Wait for 1000 millisecond(s)
}
Name – Kaushalendra Singh EC2 19EEAEC037

Result- Hence, we have interfaced motor using relay with Arduino UNO and motor is
turned ON when push button is pressed.
Name – Kaushalendra Singh EC2 19EEAEC037

EXPERIMENT-07
Objective - To interface OLED with Arduino/Raspberry Pi and write a program to print
temperature and humidity readings on it.

Experimental requirement- Fritzing

Circuit diagram-

Program code- #define


DHT11Pin 2 #define
DHTType DHT11
//OLED
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Name – Kaushalendra Singh EC2 19EEAEC037

DHT HT(DHT11Pin,DHTType);
float humi;
float tempC;
float tempF;

//OLED define
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

void setup() {
Serial.begin(9600);
//For DHT11
HT.begin();
//For OLED I2C
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
//display.display(); //Display logo
delay(1000);
display.clearDisplay();
}

void loop() {
delay(1000);
humi = HT.readHumidity();
tempC = HT.readTemperature();

tempF = HT.readTemperature(true);

Serial.print("Humidity:");
Serial.print(humi,0);
Serial.print("%");
Serial.print(" Temperature:");
Serial.print(tempC,1);
Serial.print("C ~ ");
Serial.print(tempF,1);
Serial.println("F");

display.clearDisplay();
oledDisplayHeader();

oledDisplay(3,5,30,humi,"%");
oledDisplay(2,70,16,tempC,"C");
Name – Kaushalendra Singh EC2 19EEAEC037

oledDisplay(2,70,44,tempF,"F");
display.display();
}
void oledDisplayHeader(){
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0, 0);
display.print("Humidity");
display.setCursor(60, 0);
display.print("Temperature");
}
void oledDisplay(int size, int x,int y, float value, String unit){
int charLen=12;
int xo=x+charLen*3.2;
int xunit=x+charLen*3.6;
int xval = x;
display.setTextSize(size);
display.setTextColor(WHITE);
if (unit=="%"){
display.setCursor(x, y);
display.print(value,0);
display.print(unit);
} else {
if (value>99){
xval=x;
} else {
xval=x+charLen;
}
display.setCursor(xval, y);
display.print(value,0);
display.drawCircle(xo, y+2, 2, WHITE); // print degree symbols ( )
display.setCursor(xunit, y);
display.print(unit);
}

Result- Hence, we have simulated OLED with NodeMCU-12E and have taken temperature
and humidity readings on it.
Name – Kaushalendra Singh EC2 19EEAEC037

EXPERIMENT-08
Objective - To interface Bluetooth with Arduino/Raspberry Pi and write a program to send
sensor data to smartphone using Bluetooth.

Experimental requirement-
1. NodeMCU-12E
2. Bread board
3. DHT11 sensor
4. Bluetooth module
5. Micro USB cable
6. Connecting wires
7. Serial Bluetooth Terminal
8. Arduino IDE

Circuit diagram-

Program code-
#include <Adafruit_Sensor.h>
Name – Kaushalendra Singh EC2 19EEAEC037

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

#define DHTPIN D4 // Digital pin connected to the DHT sensor


// Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 --
#define DHTTYPE DHT11
DHT_Unified dht(DHTPIN, DHTTYPE);

SoftwareSerial Bluetooth(3,1); //Rxd, Txd

void setup() {
Serial.begin(9600);
Bluetooth.begin(9600);
// Initialize device.
dht.begin();
Serial.println("DHT11 Sensor Example");
Bluetooth.println("Ready for command...");
}

void loop() {
// Delay between measurements.
delay(2000);
// Get temperature event and print its value.
sensors_event_t event;
dht.temperature().getEvent(&event);

if (isnan(event.temperature)) {
Serial.println("Error reading temperature!");
}
else { Serial.print("Temperature:
");
Serial.print(event.temperature);
Serial.print("°C ");
Bluetooth.print("Temp: ");
Bluetooth.print(event.temperature);
Bluetooth.println(" °C\t");

}
// Get humidity event and print its value.
dht.humidity().getEvent(&event);
if (isnan(event.relative_humidity)) {
Serial.println("Error reading humidity!");
}
else {
Serial.print("Humidity : ");
Name – Kaushalendra Singh EC2 19EEAEC037

Serial.print(event.relative_humidity);
Serial.println("%");
Bluetooth.print("Humid : ");
Bluetooth.print(event.relative_humidity);
Bluetooth.println(" %\t");
Bluetooth.println(" \t");
}
}

Result- Hence, we have connected Bluetooth module with NodeMCU-12E and have sent
sensor data to smartphone using Serial Bluetooth Terminal application.
Name – Kaushalendra Singh EC2 19EEAEC037

EXPERIMENT-09
Objective - 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.

Experimental requirement-
1. NodeMCU-12E
2. Bread board
3. Bluetooth module
4. 10kohm resistor
5. LED
6. Micro USB cable
7. Connecting wires
8. Serial Bluetooth Terminal
9. Arduino IDE

Circuit diagram-

Program code-
#include <SoftwareSerial.h>
#define LED 16
SoftwareSerial Bluetooth(3, 1); // RX, TX

char junk;
String inputString="";

void setup() // run once, when the sketch starts


{
Name – Kaushalendra Singh EC2 19EEAEC037

Serial.begin(9600);
Bluetooth.begin(9600); // set the baud rate to 9600, same should be of your Serial
Monitor
pinMode(LED, OUTPUT);
}

void loop()
{
if(Bluetooth.available()){
while(Bluetooth.available())
{
char inChar = (char)Bluetooth.read(); //read the input
inputString += inChar; //make a string of the characters coming on serial
}
Serial.println(inputString);
Bluetooth.println(inputString);

while (Bluetooth.available() > 0)


{ junk = Bluetooth.read() ; } // clear the serial buffer

if(inputString == "1"){ //in case of '1' turn the LED on


digitalWrite(LED, HIGH);
}
else if(inputString == "0"){ //incase of '0' turn the LED off
digitalWrite(LED, LOW);
}
inputString = "";
}
}

Output-

Result- Hence, we have coonected Bluetooth with NodeMCU-12E and turned LED
ON/OFF when ‘1’/’0’ is received from smartphone using Bluetooth.
Name – Kaushalendra Singh EC2 19EEAEC037

EXPERIMENT-10
Objective - Write a program on Arduino/Raspberry Pi to upload temperature and humidity
data to thingspeak cloud.

Experimental requirement-
1. NodeMCU-12E
2. Bread board
3. DHT11 sensor
4. Micro USB cable
5. Connecting wires
6. Arduino IDE

Circuit diagram-

Program code-
#include <DHT.h> // Including library for dht

#include <ESP8266WiFi.h>

String apiKey = "HVL169WWCU91QOE1"; // Enter your Write API key from


ThingSpeak

const char *ssid = "DOMAIN_2.5GHZ"; // replace with your wifi ssid and wpa2 key
const char *pass = "Qwerty1123!";
const char* server = "api.thingspeak.com";

#define DHTPIN 0 //pin where the dht11 is connected


Name – Kaushalendra Singh EC2 19EEAEC037

DHT dht(DHTPIN, DHT11);

WiFiClient client;

void setup()
{
Serial.begin(9600);
delay(10);
dht.begin();

Serial.println("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, pass);

while (WiFi.status() != WL_CONNECTED)


{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");

void loop()
{

float h = dht.readHumidity();
float t = dht.readTemperature();

if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}

if (client.connect(server,80)) // "184.106.153.149" or api.thingspeak.com


{

String postStr = apiKey;


postStr +="&field1=";
postStr += String(t);
postStr +="&field2=";
Name – Kaushalendra Singh EC2 19EEAEC037

postStr += String(h);
postStr += "\r\n\r\n";

client.print("POST /update HTTP/1.1\n");


client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);

Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" degrees Celcius, Humidity: ");
Serial.print(h);
Serial.println("%. Send to Thingspeak.");
}
client.stop();
Serial.println("Waiting...");

delay(1000);
}

Output-

Result-
Hence, we have uploaded temperature and humidity data to thingspeak cloud.
Name – Kaushalendra Singh EC2 19EEAEC037

EXPERIMENT-11
Objective - Write a program on Arduino/Raspberry Pi to retrieve temperature and
humidity data from thingspeak cloud.

Experimental requirement-
1. NodeMCU-12E
2. Bread board
3. DHT11 sensor
4. Micro USB cable
5. Connecting wires
6. Arduino IDE

Circuit diagram-

Program code-
#include "ThingSpeak.h"
#include <ESP8266WiFi.h>
const char ssid[] = "DOMAIN_2.5GHZ"; // your network SSID (name)
const char pass[] = "Qwerty1123!"; // your network password
WiFiClient client;
Name – Kaushalendra Singh EC2 19EEAEC037

//---------Channel Details --------- //


unsigned long counterChannelNumber = 1407742; // Channel ID
const char * myCounterReadAPIKey = "7T552SVDA85CS20J"; // Read API Key
const float FieldNumber1 = 1; // The field you wish to read
const float FieldNumber2 = 2; // The field you wish to read
int statusCode=0;
// //

void setup()
{
Serial.begin(115200);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
}

void loop()
{
// Network //
if (WiFi.status() != WL_CONNECTED)
{
Serial.print("Connecting to ");
Serial.print(ssid);
Serial.println("..... ");
while (WiFi.status() != WL_CONNECTED)

{
WiFi.begin(ssid, pass);
delay(5000);
}
Serial.println("Connected to Wi-Fi Succesfully.");
}
//--------- End of Network connection -------- //

// Channel 1 //
float temp = ThingSpeak.readLongField(counterChannelNumber, FieldNumber1,
myCounterReadAPIKey);
statusCode = ThingSpeak.getLastReadStatus();
if (statusCode == 200)
{
Serial.print("Temperature: ");
Serial.println(temp);
}
else
{
Serial.println("Unable to read channel / No internet connection");
Name – Kaushalendra Singh EC2 19EEAEC037

}
delay(100);
// End of Channel 1 //

// Channel 2 //
float humidity = ThingSpeak.readLongField(counterChannelNumber, FieldNumber2,
myCounterReadAPIKey);
statusCode = ThingSpeak.getLastReadStatus();
if (statusCode == 200)
{
Serial.print("Humidity: ");
Serial.println(humidity);
}
else
{
Serial.println("Unable to read channel / No internet connection");
}
delay(100);
// End of Channel 2 //
}

Output-

Result- Hence, we have retrieved temperature and humidity data from thingspeak cloud.
Name – Kaushalendra Singh EC2 19EEAEC037

EXPERIMENT-12
Objective - To interface LED/Buzzer with Raspberry Pi and write a program to
turn ON LED for 1 sec after every 2 seconds.

Experimental requirement-

• Raspberry Pi 3 setup with monitor and USB Mouse & Keyboard


• Breadboard
• Jumper wires
• Resistor pack
• Red LED

Circuit diagram-

Program code-
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
from time import sleep # Import the sleep function from the time module
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
Name – Kaushalendra Singh EC2 19EEAEC037

GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set initial
value to low (off)
while True: # Run forever
GPIO.output(8, GPIO.HIGH) # Turn on
sleep(1) # Sleep for 1 second
GPIO.output(8, GPIO.LOW) # Turn off
sleep(2) # Sleep for 1 second

Output-

Result- Hence, we have interfaced LED/Buzzer with Raspberry Pi and have turned ON
LED for 1 sec after every 2 seconds
Name – Kaushalendra Singh EC2 19EEAEC037

EXPERIMENT-13
Objective - Write a program to create UDP server on Arduino/Raspberry Pi and respond
with humidity data to UDP client when requested.

Experimental requirement-
1. NodeMCU-12E
2. Bread board
3. DHT11 sensor
4. Micro USB cable
5. Connecting wires
6. Arduino IDE
7. Packet sender

Circuit diagram-

Program code-
#include <ESP8266WiFi.h>

#include <WiFiUdp.h>

#include <Adafruit_Sensor.h>
Name – Kaushalendra Singh EC2 19EEAEC037

#include <DHT.h>
#include <DHT_U.h>
#define DHTTYPE DHT11
#define DHTPIN 0
DHT_Unified dht(DHTPIN, DHTTYPE);

int humidity;
const char* ssid = "Happy";
char reply[7];
const char* password = "happy123";

WiFiUDP Udp;

unsigned int localUdpPort = 5219; // local port to listen on

char ReceivedMessage[255]; // buffer for incoming packets

char Acknowledge[] = "Received your message: "; // a reply string to send back

void setup()

{
Serial.begin(9600);

Serial.println();

dht.begin();
Serial.printf("Connecting to %s ", ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED)

delay(500);
Serial.print(".");

Serial.println("Wi-Fi connected!");

Udp.begin(localUdpPort);
Name – Kaushalendra Singh EC2 19EEAEC037

Serial.printf("I am listening at IP %s, UDP port %d \n", WiFi.localIP().toString().c_str(),


localUdpPort);
Serial.println("DHT11 Begin");

void loop()

int packetSize = Udp.parsePacket();


sensors_event_t event;
dht.humidity().getEvent(&event);
if (isnan(event.relative_humidity)) {
Serial.println("Error reading humidity!");
delay(2000);
}
else {
humidity=event.relative_humidity;
}
if (packetSize)

// receive incoming UDP message

Serial.printf("Received %d message from %s, port %d \n", packetSize,


Udp.remoteIP().toString().c_str(), Udp.remotePort());

int len = Udp.read(ReceivedMessage, 255);

if (len > 0)

ReceivedMessage[len] = 0;

Serial.printf("UDP message: %s \n", ReceivedMessage);

delay(1000);
// send back a reply, to the IP address and port we got the packet from

Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Name – Kaushalendra Singh EC2 19EEAEC037

dtostrf(humidity,5,2,reply);
Udp.write(reply);

Udp.endPacket();
}
}

Result- Hence, we have created UDP server on Arduino/Raspberry Pi and have responded
with humidity data to UDP client when requested.

You might also like