100% found this document useful (1 vote)
553 views

IOT Architecture & Protocols Lab Manual

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
553 views

IOT Architecture & Protocols Lab Manual

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

Department of Electronics & Communication Engineering

IOT ARCHITECTURE AND


PROTOCOLS LABORATORY
(22PC0EC25)
III B.Tech-ECE I-Semester (2024-‘25)

LABORATORY MANUAL
(Master Copy)

SCHOOL OF ENGINEERING & TECHNOLOGY


GURU NANAK INSTITUTIONS TECHNICAL CAMPUS
(Autonomous)(Affiliated to JNUTH, Approved by AICTE) (NAAC A+& NBA Accredited)
Khanapur, Ibrahimpatnam, RR Dist, Hyderabad-501506
Department of Electronics & Communication Engineering

IOT ARCHITECTURE AND


PROTOCOLS LABORATORY
(22PC0EC25)
III B.Tech-ECE I-Semester (2024-‘25)

LABORATORY MANUAL
(Master Copy)

SCHOOL OF ENGINEERING & TECHNOLOGY


GURU NANAK INSTITUTIONS TECHNICAL CAMPUS
(Autonomous, Affiliated to JNUTH, Approved by AICTE)

Ibrahimpatnam, RR Dist-501506
www.gniindia.org
Department of Electronics & Communication Engineering
IOT ARCHITECTURE AND
PROTOCOLS LABORATORY
(22PC0EC25)
III B.Tech-ECE I-Semester (2024-‘25)
LABORATORY MANUAL

SCHOOL OF ENGINEERING & TECHNOLOGY


GURU NANAK INSTITUTIONS TECHNICAL CAMPUS
(Affiliated to JNUTH, Approved by AICTE)

Ibrahimpatnam, RR Dist-501506
www.gniindia.org

Authorized by
Prepared by:
Document No:
GNITC/ECE/LM/IOT N V S MURTHY
Asst.Prof
HOD-ECE
GURU NANAK INSTITUITONS TECHNICAL CAMPUS
SCHOOL OF ENGINEERING & TECHNOLOGY

Department of Electronics & Communication Engineering

IOT ARCHITECTURE AND PROTOCOLS LABORATORY


(22PC0EC25)
III B.Tech-ECE I-Semester (2024-‘25)
LABORATORY MANUAL

CONTENT PAGE

S.No Description Page No

1 Syllabus I

2 PEO’s & PO’s II

3 List of Experiments III

4 Experiment Planner IV
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (Autonomous)

ELECTRONICS & COMMUNICATION ENGINEERING

III Year B.Tech. ECE I-Sem L T P C

0 0 2 1

IOT ARCHITECTURE AND PROTOCOLS LABORATORY (22PC0EC25)

1. Demonstrate blinking of an LED at every 5 seconds and to control the brightness of an


LED.
2. Read Humidity and Room Temperature using DHT sensor and display the readings.
3. Demonstrate Switching lights on/off remotely using Arduino/ Node MCU /Raspberry Pi.
4. Voice-based Home Automation for switching lights on/off using Google Assistant,
IFTTT and MQTT.
5. Interfacing DHT sensor with Raspberry pi/ equivalent and upload temperature and
humidity values to the cloud.
6. Design an obstacle detection unit using ultra sonic sensor.
7. Capture images from web camera using Raspberry Pi/ equivalent and apply filters in
increase image quality.
8. Access a remote computer from Raspberry Pi and display the remote screen.
9. Design an automatic water sprinkler based on soil moisture using Arduino /Node MCU
/Raspberry Pi.
10. Write an arduino program to demonstrate interrupts
11. Write an arduino program to demonstrate UART communication protocol
12. Write an arduino program to demonstrate I2C communication protocol
13. Write an arduino program to demonstrate SPI communication protocol
To be a world –class educational and research institution in the service of humanity by
promoting high quality Engineering, Management and Pharmacy education.

MISSION OF THE INSTITUTION [GNITC]:

M1: Imbibe soft skills and technical skills.

M2: Develop the faculty to reach the international standards.

M3: Maintain high academic standards and teaching quality that promotes the analytical thinking
and independent judgment.

M4: Promote research, innovation and Product development by collaboration with reputed foreign
universities.

M5: Offer collaborative industry programs in emerging areas and spirit of enterprise.

QUALITY POLICY:

GNITC is committed to provide quality education through dedicated and talented faculty, world class
infrastructure, labs and updated research center to the students. Quality teaching-learning process and
system will help students to attain placements and prepare them for higher studies.

DEPARTMENT OF ELECTRONICS & COMMUNICATION ENGINEERING

VISION OF THE DEPARTMENT-:

To be a premier department of Electronics and Communication Engineering in the region by


providing high quality education.

MISSION OF THE DEPARTMENT-:

1. Nurture young individuals into knowledgeable, skillful and ethical professionals in their pursuit of
electronics and communication engineering.
2. Transform the students through excellent teaching learning process and sustain high performance
by innovations.
3. Extensive partnerships and collaborations with foreign universities.
4. Develop Industry-Interaction for innovation and product development.
ECE DEPARTMENT PEOs/Pos/PSOs

PROGRAM EDUCATIONAL OBJECTIVES (PEOs):


PEO1: Produce Industry ready graduates having the ability to apply knowledge across the
disciplines and in emerging areas of Electronics and Communication Engineering for
higher studies, employability and handle the realistic problems.

PEO2: Graduates shall have good communication skills, possess ethical conduct, sense of
responsibility to serve the society and protect the environment.

PEO3: Graduates shall have soft skills, managerial skills, leadership qualities and understand
the need for lifelong learning for a successful professional career.

PROGRAM OUTCOMES (POs) :

Engineering Graduates will be able to:


1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.

3. Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive clear
instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and leader
in a team, to manage projects and in multidisciplinary environments.

12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change..

PSOs:

PSO1: Solve, Design and analyze circuits in the field of Communication Engineering

PSO2: Design and implement Circuits in the field of Digital Signal Processing, Embedded Systems
and Antenna using various modern software tools

COURSE OBJECTIVES:

This Course focuses on hands-on IoT concepts such as sensing, actuation and communication. It
covers the Hands On Experience with Raspberrypi, NodeMCU,Arduino UNO and development
of Internet of Things (IoT) prototypes—including devices for sensing, actuation, processing, and
communication—to help you develop skills and experiences

COURSE OUTCOMES:

At the end of this course students will demonstrate the ability to

S.NO DESCRIPTION

1 CO1: Utilize the different sensors like room temperature, DHT, Humidity etc.,S

2 CO2: Interface the sensors and processor for transmission of data.

3 CO3: Capture the images and process it on Arduino /Node MCU / Raspberry Pi.

4 CO4: Know the utilization of various protocols like I2c, UART communication
etc.,
5. CO5: Utilize the cloud platform and APIs for IoT application
MAPPING OF COs versus PSOs and POs:

0: No mapping, 1: Slight (Low) , 2: Moderate (Medium), 3: Substantial (High)

Sr. PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
No.
1 CO1 2 1 1 1 0 0 0 0 0 0 1 0 3 1

2 CO2 2 1 1 1 0 0 0 0 0 0 0 0 3 3

3 CO3 2 1 1 1 1 0 0 0 1 0 0 0 2 3

4 CO4 3 2 1 1 1 0 0 0 2 0 0 0 2 2

5 CO5 3 1 1 1 1 1 1 0 1 0 1 1 1 1

MAPPING OF PROGRAM EDUCATIONAL OBJECTIVES (PEO’S) AND PROGRAM


OUTCOMES (PO) FOR ELECTRONICS AND COMMUNICATION ENGINEERING

Program Program Outcomes


Educational
Objectives

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2

PEO1 3 3 3 3 3 2 1 1 1 2 2 2 3 3

PEO2 1 1 1 1 1 3 3 3 2 3 1 1 1 2

PEO3 1 1 1 1 2 1 1 2 3 3 3 3 2 2

II
GURU NANAK INSTITUITONS TECHNICAL CAMPUS
SCHOOL OF ENGINEERING & TECHNOLOGY
Department of Electronics & Communication Engineering
IOT ARCHITECTURE AND PROTOCOLS LABORATORY (22PC0EC25)
III B.Tech-ECE I-Semester (2024-‘25)
LABORATORY MANUAL
LIST OF EXPERIMENTS
SNo Name of Experiment Page No.
Demonstrate blinking of an LED at every 5 seconds and to 1
1 control the brightness of an LED.

Read Humidity and Room Temperature using DHT sensor and display the 5
2
readings.
Demonstrate Switching lights on/off remotely using Arduino/ Node MCU 13
3
/Raspberry Pi.
Voice-based Home Automation for switching lights on/off using Google 22
4
Assistant, IFTTT and MQTT.
Interfacing DHT sensor with Raspberry pi/ equivalent and upload 28
5
temperature and humidity values to the cloud.
Design an obstacle detection unit using ultra sonic sensor. 30
6
Capture images from web camera using Raspberry Pi/ equivalent and 40
7
apply filters in increase image quality.
Access a remote computer from Raspberry Pi and display the remote 55
8
screen
Design an automatic water sprinkler based on soil moisture using Arduino 61
9
/Node MCU /Raspberry Pi.
10 Write an arduino program to demonstrate interrupts 65

11 Write an arduino program to demonstrate UART communication protocol 70

12 Write an arduino program to demonstrate I2C communication protocol 75

13 Write an arduino program to demonstrate SPI communication protocol 78

III
GURU NANAK INSTITUITONS TECHNICAL CAMPUS
SCHOOL OF ENGINEERING & TECHNOLOGY

Department of Electronics & Communication Engineering


IOT ARCHITECTURE AND PROTOCOLS LABORATORY
(22PC0EC25)
III B.Tech-ECE II-Semester (2024-‘25)
LABORATORY MANUAL

Lab Experiment Planner


Batches: A & B Total Number of Experiments: 12

Total Number of Batches: 12 (with a maximum of ‘3’ students/batch)

2024

Experiment/

Exp-10

Exp-11

Exp-12
Exp-1

Exp-2

Exp-3

Exp-4

Exp-5

Exp-6
Section
Section-1 (A) 1/7 8/7 15/7 22/7 5/8 12/8 19/8 26/8 9/9

Section-1 (B) 1/7 8/7 15/7 22/7 5/8 12/8 19/8 26/8 9/9

Section-2 (A) 9/7 16/7 23/7 30/7 6/8 13/8 20/8 27/8 10/9

Section-2 (B) 9/7 16/7 23/7 30/7 6/8 13/8 20/8 27/8 10/9

Section-3 (A) 3/7 10/7 17/7 24/7 31/7 7/8 14/8 21/8 28/8

Section-3 (B) 3/7 10/7 17/7 24/7 31/7 7/8 14/8 21/8 28/8

Section-4 (A) 4/7 11/7 18/7 25/7 7/8 14/8 21/8 28/8 12/9

Section-4 (B) 4/7 11/7 18/7 25/7 7/8 14/8 21/8 28/8 12/9

Section-5 (A) 5/7 19/7 26/7 2/8 16/8 16/8 23/8 23/8 30/8

Section-5 (B) 5/7 19/7 26/7 2/8 16/8 16/8 23/8 23/8 30/8

Section-6 (A) 7/7 14/7 21/7 28/7 4/8 11/8 18/8 25/8 8/9

Section-6 (B) 1/7 8/7 15/7 22/7 5/8 12/8 19/8 26/8 9/9

IV
Arduino IDE 2.0 Installed

Before proceeding make sure you have Arduino IDE 2.0 installed in your computer.
Go to the Arduino website and download the version for your operating system.

▪ Windows: run the file downloaded and follow the instructions in the installation guide.
▪ Mac OS X: copy the downloaded file into your application folder.
▪ Linux: extract the downloaded file, and open the arduino-ide file that will launch the IDE.

If you have doubts, you can go to the Arduino Installation Guide.

To install the ESP8266 board in your Arduino IDE, follow these next instructions:
1. In your Arduino IDE 2.0, go to File > Preferences.
2. Copy and paste the following line to the Additional Boards Manager URLs field.
http://arduino.esp8266.com/stable/package_esp8266com_index.json
Adding ESP8266 Board Manager

In the Additional Boards Manager enter below URL.

http://arduino.esp8266.com/stable/package_esp8266com_index.json

As highlighted in the figure and enter OK.


Selecting Board

Now open the tools in that select Board: “Arduino/Genuino Uno” and click on the Boards Manager as
shown in the figure

ESP8266 Board Package

The Boards Manager window opens, scroll the window page to bottom till you see the module with the
name ESP8266. Once we get it, select that module and select version and click on the Install button. When
it is installed it shows Installed in the module as shown in the figure and then closes the window.
Selecting ESP8266 Arduino Board

To run the esp8266 with Arduino we have to select the Board: “Arduino/Genuino Uno” and then
change it to NodeMCU 1.0 (ESP-12E Module) or other esp8266 modules depending on what you have
to select and select port, Upload the program.
EXPERIMENT 1:

AIM: TO TEST LED WITH NODE MCU

CIRCUIT DIAGRAM:

CODE:
int led = D1; // LED pin
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
digitalWrite(led, HIGH); delay(1000);
digitalWrite(led, LOW); delay(1000);
}
CONNECT C6 TO C13
EXPERIMENT 2:

AIM: TO TEST LED & SWITCH WITH NODE MCU

CIRCUIT DIAGRAM

CODE:

int led = D6; // LED pin


int button = D3; // push button is connected
int temp = 0; // temporary variable for reading the button pin status
void setup() {
pinMode(led, OUTPUT); // declare LED as output
pinMode(button, INPUT); // declare push button as input
}
void loop() {
temp = digitalRead(button);
if (temp == HIGH) {
digitalWrite(led, LOW);
Serial.println("LED Turned OFF");
delay(1000);
}
else {
digitalWrite(led, HIGH);
Serial.println("LED Turned ON");
}
}

CONNECT C6 TO SWITCHES AND C4 TO LESS & press s1 led 1 will turn on


EXPERIMENT 3:

AIM: TO TEST DHT 11 ON OLED WITH NODE MCU

CIRCUIT DIAGRAM:

CODE:

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
#define DHTPIN D4 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
dht.begin();
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
delay(2000);
display.clearDisplay();
display.setTextColor(WHITE);
}
void loop() { delay(5000);
float t = dht.readTemperature();
float h = dht.readHumidity();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
}
display.clearDisplay();
display.setTextSize(1);
display.setCursor(0,0);
display.print("Temperature: ");
display.setTextSize(2);
display.setCursor(0,10);
display.print(t);
display.print(" ");
display.setTextSize(1);
display.cp437(true);
display.write(167);
display.setTextSize(2);
display.print("C");
display.setTextSize(1);
display.setCursor(0, 35);
display.print("Humidity: ");
display.setTextSize(2);
display.setCursor(0, 45);
display.print(h);
display.print(" %");
display.display();
}
CONNECT C5 TO C8 & C3 TO C10
EXPERIMENT 4:

AIM: TO TEST ULTRASONIC WITH NODE MCU

CIRCUIT DIAGRAM:

CODE:
const int trigPin = D5; //trig
const int echoPin = D4; //Echo
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(115200); // Starts the serial communication
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
delay(2000);
}

CONNECT C3 TO C9
EXPERIMENT 5:

AIM: TO TEST LDR WITH NODE MCU

CIRCUIT DIAGRAM:

CODE:
int light_pin = D4;
void setup() {
pinMode(light_pin, INPUT);
Serial.begin(115200);
}
void loop() {
int light_data = digitalRead(light_pin);
if(light_data==0){
Serial.println("Light Detected!");
}
else{
Serial.println("Light not Detected!");
}
delay(100);
}

CONNECT C3 TO C11 & SEE RESULT IN SERIAL MONITOR


EXPERIMENT 6:

AIM: TO TEST SOIL MOISTURE SENSOR WITH NODE MCU

CIRCUIT DIAGRAM:

CODE:

#include <ESP8266WiFi.h> //adding esp266 wifi library


#include <ThingSpeak.h> //adding thingspeak library
int SM_pin = A0; // Arduino pin A0
const char *ssid = "PCS Labs";
const char *pass = "pcs@2468";
float soil = 0;
WiFiClient client;
long myChannelNumber = ******;
const char myWriteAPIKey[] = "**********";
void setup() {
pinMode(SM_pin, INPUT);
Serial.begin(115200);
WiFi.begin(ssid, pass);
while(WiFi.status() != WL_CONNECTED)
{
delay(200);
Serial.print("..");
}
Serial.println();
Serial.println("NodeMCU is connected!");
Serial.println(WiFi.localIP());
ThingSpeak.begin(client);
}

void loop() {
int SM_value = analogRead(SM_pin);
Serial.print("SOIL MOISTURE Value : ");
Serial.println(SM_value);
ThingSpeak.writeField(myChannelNumber, 3, SM_value, myWriteAPIKey);
Serial.println("data sent to cloud");
delay(1000);
}

CONNECT C1 TO C12 ATTACH CONNECTOR AND SEE RESULTS ON THINGSPEAK.


Experiment 1:

AIM: To Interface Liquid Crystal Display (LCD) with Arduino uno.

PIN DIAGRAM:

• Click on Start > Arduino Application > type code

Connections from Arduino uno to LCD Module CN18 TO CN29

5
Code :
#include <LiquidCrystal.h> // include the library code:
// with the arduino pin number it is connected to
const int rs = 6, en = 7, d4 =2, d5 = 3, d6 = 4, d7 = 5;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
lcd.begin(16, 2); // set up the LCD's number of columns and rows:
lcd.print(" WELCOME TO "); // Print a message to the LCD.
lcd.setCursor(0,1); // setting cursor
lcd.print("PHYSITECH IoTKit");
delay(2000);
lcd.clear();
lcd.print(" WELCOME TO ");
}
void loop() {
lcd.display();// Turn on the display:
delay(5000);
}
Upload code from sketch option and then connect CN22 TO C29 & CN23 TO C31

6
Experiment 2:

AIM: To Interface Light Emitting Diode (LED) with Arduino uno.

PIN DIAGRAM:

• Click on Start > Arduino Application > type code


Code
void setup() {
// put your setup code here, to run once:
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(2,HIGH); // turn on led
digitalWrite(3,HIGH); // turn on led
digitalWrite(4,HIGH); // turn on led
digitalWrite(5,HIGH); // turn on led
delay(800); // delay for repeatation of on and off
digitalWrite(2,LOW); // turn off led
digitalWrite(3,LOW); // turn off led
digitalWrite(4,LOW); // turn off led
digitalWrite(5,LOW); // turn off led
}
Upload code from sketch option and then connect CN23 TO CN11

7
Experiment 3:

AIM: To Interface Switch and LED’s Arduino uno.

PIN DIAGRAM:

Connections from Arduino uno to Led’s and switches

8
Code:
const int buttonPin1 = 6; // number of pushbutton 1 pin
int buttonState1 = LOW; // set the default variable value for pushbutton1 status
const int ledPin1 = 5; // number of the LED 1 pin
const int buttonPin2 = 7; // number of pushbutton 2 pin
int buttonState2 = LOW; // set the default variable value for pushbutton2 status
const int ledPin2 = 4; // number of the LED 2 pin
const int buttonPin3 = 8; // number of pushbutton 3 pin
int buttonState3 = LOW; // set the default variable value for pushbutton3 status
const int ledPin3 = 3; // number of the LED 3 pin
const int buttonPin4 = 9; // number of pushbutton 4 pin
int buttonState4 = LOW; // set the default variable value for pushbutton4 status
const int ledPin4 = 2; // number of the LED 4 pin
void setup() { // Set Pins to Outputs Or Inputs
pinMode(buttonPin1, INPUT); // initialize the pushbutton pins as an inputs:
pinMode(ledPin1, OUTPUT); // initialize the LED pins as an outputs:
pinMode(buttonPin2, INPUT); // initialize the pushbutton pins as an inputs:
pinMode(ledPin2, OUTPUT); // initialize the LED pins as an outputs:
pinMode(buttonPin3, INPUT); // initialize the pushbutton pins as an inputs:
pinMode(ledPin3, OUTPUT); // initialize the LED pins as an outputs:
pinMode(buttonPin4, INPUT); // initialize the pushbutton pins as an inputs:
pinMode(ledPin4, OUTPUT); // initialize the LED pins as an outputs:
Serial.begin(9600); // initialize serial communication at 9600 baud
}

void loop() {
buttonState1 = digitalRead(buttonPin1); // read current states of the pushbutton value:
buttonState2 = digitalRead(buttonPin2); // read current states of the pushbutton value:
buttonState3 = digitalRead(buttonPin3); // read current states of the pushbutton value:
buttonState4 = digitalRead(buttonPin4); // read current states of the pushbutton value:

9
// check if the pushbutton is pressed buttonState# == HIGH/LOW
// if pressed change buttonState == HIGH to turn on ledPin#
// else if buttonState == LOW then digitalWrite(ledPin#, LOW) Keeps Led off.
if (buttonState1 == HIGH) { //check buttonState
digitalWrite(ledPin1, LOW); //if HIGH turn LED on:
} else {
digitalWrite(ledPin1, HIGH); // turn LED off:
}
Serial.println(buttonState1); //Print buttonState to serial
if (buttonState2 == HIGH) { //check buttonState
digitalWrite(ledPin2, LOW); //if HIGH turn LED on:
} else {
digitalWrite(ledPin2, HIGH); // turn LED off:
delay(10);
}
Serial.println(buttonState2); //Print buttonState to serial
if (buttonState3 == HIGH) { //check buttonState
digitalWrite(ledPin3, LOW); //if HIGH turn LED on:
} else {
digitalWrite(ledPin3, HIGH); // turn LED off:
delay(10);
Serial.println(buttonState3); //Print buttonState to serial
}
if (buttonState4 == HIGH) { //check buttonState
digitalWrite(ledPin4, LOW); //if HIGH turn LED on:
} else {
digitalWrite(ledPin4, HIGH); // turn LED off:
delay(10);
Serial.println(buttonState4); //Print buttonState to serial
}
}

Upload code from sketch option and then connect CN28 TO CN13 & CN23 TO CN11

10
Experiment 4:

AIM: To Interface Soil Moisture sensor with Arduino uno.

PIN DIAGRAM:

• Click on Start > Arduino Application > type code

11
Code

int soil_pin = A1;


void setup() {
pinMode(soil_pin, INPUT);
Serial.begin(9600);
}

void loop() {
int soil_value = analogRead(soil_pin);
Serial.print("Soil Value : ");
Serial.println(soil_value);
delay(1000);
}
Upload code from sketch option and then connect CN8 TO CN16

12
Experiment 5:

AIM: To Interface Gas sensor with Arduino uno.

PIN DIAGRAM:

Connections from Arduino uno to Gas sensor

13
Code:
int gas_pin = A0;
void setup() {
pinMode(gas_pin, INPUT);
Serial.begin(9600);
}
void loop() {
int gas_value = analogRead(gas_pin);
Serial.print("Gas Value : ");
Serial.println(gas_value);
delay(1000);
}

Upload code from sketch option and then connect CN7 TO CN17

14
Experiment 6:

AIM: To Interface Bluetooth with Arduino uno.

PIN DIAGRAM:

Connections from Arduino uno to Buletooth sensor

15
Code:
#include<SoftwareSerial.h>
#define TxD 11
#define RxD 10
SoftwareSerial bluetoothSerial(TxD, RxD);
char c;
void setup() {
bluetoothSerial.begin(9600);
Serial.begin(9600);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
}

void loop() {
if(bluetoothSerial.available())
{c=bluetoothSerial.read();
Serial.println(c);
if(c=='1'){
digitalWrite(12, HIGH);
}
if(c=='2'){
digitalWrite(13, HIGH);
}
if(c=='3'){
digitalWrite(12, LOW);
}
if(c=='4'){
digitalWrite(13, LOW);
}
}

16
}

Upload code from sketch option and then connect CN5 TO CN19

Experiment 7:

AIM: To Interface DHT11 Module with Arduino uno.

PIN DIAGRAM:

Connections from Arduino uno to DHT 11 Sensor

17
Code:
#include <dht.h>
#include <dht.h>
#include <DHT.h>
dht DHT;
#define DHT11_PIN 4
void setup(){
Serial.begin(9600);
}
void loop()
{
int chk = DHT.read11(DHT11_PIN);
Serial.print("Temperature = ");
Serial.println(DHT.temperature);
Serial.print("Humi dity = ");
Serial.println(DHT.humidity);
delay(2000);
}
Upload code from sketch option and then connect CN4 TO CN26

18
Experiment 8:

AIM: To Interface Ultrasonic SR04 Module with Arduino uno.

PIN DIAGRAM:

Connections from Arduino uno to Ultrasonic sensor

19
Code:
const int trigPin = 6;
const int echoPin = 7;
// defines variables
long duration;
int distance;

void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}

void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
delay(2000);
}
Upload code from sketch option and then connect CN6 TO CN25

20
Experiment 9:

AIM: To Interface Relay Module with Arduino uno.

PIN DIAGRAM:

Connections from Arduino uno from Relay Module

21
Code:
int RELAY = 13;
void setup() {
pinMode(RELAY,OUTPUT);
digitalWrite(RELAY,LOW);
Serial.begin(9600);
}
void loop()
{
digitalWrite(RELAY,LOW);
Serial.println("RELAY OFF");
delay(1000);
digitalWrite(RELAY,HIGH);
Serial.println("RELAY ON");
delay(2000);
}
Upload code from sketch option and then connect CN9 TO CN20

22
Experiment 10:

AIM: To Interface Servo Module with Arduino uno.

PIN DIAGRAM:

Connections from Arduino uno to Servo motor

23
Code:
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
Upload code from sketch option and then connect CN3 TO C21

24
Experiment 11:

AIM: To Interface ESP8266 Module with Arduino uno.

PIN DIAGRAM:

Connections from Arduino uno board to ESP8266 Module

25
Code:

#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
#include<SerialESP8266wifi.h>
#include<ThingSpeak.h>
#include<DHT.h>
#include<ArduinoJson.h>
#include <Wire.h>
String rawData;
#define RX 2
#define TX 3
const int rs = 16, en = 17, d4 =13, d5 = 12, d6 = 11, d7 = 10;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
#define DHTTYPE DHT11
#define dht_pin 4
#define light_pin 5
#define trig_pin 7
#define echo_pin 6
#define gas_pin A0
#define soil_pin A1
float temp = 0.0;
float humidity = 0.0;
int light = 1;
float distance = 0.0;
long duration;
int gas_value = 0;
int moisture_value = 0;

String AP = "PAL_DEMO_SYSTEM"; // CHANGE ME


String PASS = "kirankumar@1"; // CHANGE ME
String API = "GK9KOUPZEFVY23HC"; // CHANGE ME
String HOST = "api.thingspeak.com";
String PORT = "80";
int countTrueCommand;
int countTimeCommand;
boolean found = false;
SoftwareSerial esp8266(RX,TX);
StaticJsonBuffer<200> jsonBuffer;
DHT dht(dht_pin,DHTTYPE);
void setup()
{
Serial.begin(9600);
esp8266.begin(115200);

26
sendCommand("AT",5,"OK");
sendCommand("AT+IPR = 9600",5,"OK");
sendCommand("AT+UART_DEF=9600,8,1,0,0",5,"OK");
Serial.begin(9600);
esp8266.begin(9600);
lcd.begin(16, 2);
lcd.print("welcome");
//Serial.begin(9600);
//esp8266.begin(9600);
dht.begin();
pinMode(light_pin,INPUT);
pinMode(trig_pin,OUTPUT);
pinMode(echo_pin,INPUT);
pinMode(gas_pin,INPUT);
pinMode(soil_pin,INPUT);
//sendCommand("AT",5,"OK");
//sendCommand("AT+IPR = 9600",5,"OK");
//sendCommand("AT+UART_DEF=9600,8,1,0,0",5,"OK");
sendCommand("AT",5,"OK");
sendCommand("AT+CWMODE=1",5,"OK");
sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK");
}
void loop() {
temp = dht.readTemperature();
Serial.print("Temperature : ");
Serial.println(temp);
humidity = dht.readHumidity();
Serial.print("Humidity : ");
Serial.println(humidity);
lcd.setCursor(0,0);
lcd.print("T:");
lcd.print(temp);
lcd.print(" H:");
lcd.print(humidity);
light = digitalRead(light_pin);
Serial.print("Light : ");
Serial.println(light);
digitalWrite(trig_pin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trig_pin, HIGH);
delayMicroseconds(10);
digitalWrite(trig_pin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echo_pin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
Serial.print("Distance : ");

27
Serial.print(distance);
Serial.println(" cm");
gas_value = analogRead(gas_pin);
Serial.print("Gas Value : ");
Serial.println(gas_value);
lcd.setCursor(0,1);
lcd.print("D:");
lcd.print(distance);
lcd.print(" G:");
lcd.print(gas_value);
moisture_value = analogRead(soil_pin);
Serial.print("Moisture Level: ");
Serial.println(moisture_value);
String getData = "GET /update?api_key="+ API
+"&field1="+temp+"&field2="+humidity+"&field3="+light+"&field4="+distance+"&field5
="+gas_value+"&field6="+moisture_value;
//String getData = "GET
/channels/695467/fields/1/last.json?api_key=Z4Y31YEM9I2VUNBH";
sendCommand("AT+CIPMUX=1",5,"OK");
delay(1000);
sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK");
delay(1000);
sendCommand("AT+CIPSEND=0," +String(getData.length()+4),4,">");
delay(1000);
esp8266.println(getData);
delay(1500);
// if(esp8266.available()>0)
// {
// Serial.println("OKKKKK");
// rawData = esp8266.readString();
// delay(1000);
// Serial.println(rawData);
// delay(1000);
// }
countTrueCommand++;
sendCommand("AT+CIPCLOSE=0",5,"OK");
Serial.println();
Serial.println("Data sent to cloud Success");
lcd.clear();
}
void sendCommand(String command, int maxTime, char readReplay[]) {
Serial.print(countTrueCommand);
Serial.print(". at command => ");
Serial.print(command);
Serial.print(" ");
while(countTimeCommand < (maxTime*1))
{
esp8266.println(command);//at+cipsend
if(esp8266.find(readReplay))//ok

28
{
found = true;
break;
}
countTimeCommand++;
}
if(found == true)
{
Serial.println("TRUE");
countTrueCommand++;
countTimeCommand = 0;
}

if(found == false)
{
Serial.println("Fail");
countTrueCommand = 0;
countTimeCommand = 0;
}

found = false;
}

Connect CN10 TO 15
Connect required sensors to be monitor like LDR, Ultrasonic, DHT11 and Gas sensor with
ESP 8266 and Arduino uno.
Open thinspeak web site and lodin to your account channel and monitor the data

29
Experiment 12:

AIM: To Interface Light Dependent Resistor with Arduino uno.

PIN DIAGRAM:

Connections from Arduino to Light dependent resistor (LDR )Sensor

30
Code:
int light_pin =13;
void setup() {
pinMode(light_pin, INPUT)
pinMode(11, OUTPUT);
Serial.begin(9600);
}
void loop() {
int light_data = digitalRead(light_pin);
if(light_data==0){
Serial.println("Light Detected!");
digitalWrite(11, LOW);
}
else{
Serial.println("Light not Detected!");
digitalWrite(11, HIGH);
}
delay(500);
}

31
Experiment 13:

AIM: To Interface Buzzer with Arduino uno.

PIN DIAGRAM:

Connections from Arduino uno to Buzzer module

32
Code:
/*
* Example testing sketch to test Relay
*
*/
//Define pin
// RM26 - RM27 connected
// CN10 - CN7
int BUZZER = 13;
void setup() {
pinMode(BUZZER,OUTPUT);
digitalWrite(BUZZER,LOW);
Serial.begin(9600);
}

void loop()
{
digitalWrite(BUZZER,LOW);
Serial.println("BUZZER OFF");
delay(1500);

digitalWrite(BUZZER,HIGH);
Serial.println("BUZZER ON");
delay(1500);
}

33
Experiment 1: RASPBERRY PI 3 B+ Operating System flashing.

o Processor - SoC type Broadcom BCM2837B0 (ARMv8-A, 32/64-bit),


Quadcore.
o Graphic Processor Unit (GPU) - Broadcom Video Core IV 1080p60
o CPU unit - ARM Cortex-A53 Quad core 1.4 GHz
o RAM - 1 GB
o 4 x USB 2.0 ports
o 40 pin extended GPIO (General Purpose Input/Output)
o 4 pole Stereo output and Composite video port
o Full size HDMI output

INSTALLING RASPBIAN OS FOR RASPBERRY PI 3 B+ PROCEDURES:


https://www.raspberrypi.org/software/

2
Click on start and search Raspberry pi imager
• Select operating system as raspberry pi os (32Bit)
• Select SD CARD and click on WRITE
• Insert SD card in pi and update the raspberry pi.
• After write finished remove SD card.
• Change the following
• When you start your Raspberry Pi for the first time, the Welcome to
Raspberry Pi application will pop up and guide you through the initial setup.
Click Next to start the setup.

Language: English, Country and Time Zone: India and Kolkata

Enter a new password for your Raspberry Pi and click next. In this step, you need to plug a

keyboard into the Raspberry Pi to help you input the new password.
Connect to your WiFi network by selecting its name, entering the
password, and clicking next.
Click Next let the wizard check for updates to Raspbian and install them (this might
take a little while).

3
• From menu-->Preferences-->Raspberry Pi 4 B+ Configuration. Then Go To
Interfaces
• Enable Camera, SSH, VNC, SPI, I2C, Serial Port. Do not Enable Remaining Things.
• Connect to Wi-Fi. > Check the date and Time.
• Open the Terminal. > Execute following default commands.
• sudo apt-get update > sudo apt-get up grade
• Now you can write your programs at Thonny Python IDE. Menu→ Programming
• →Thonny Python IDE.
• File → New ….. You can write your Program here and save.
• Execute the program at terminal only by following command sudo python <program-
name>.py
PI PROGRAMMING:
Start Thonny by clicking on the Raspberry Pi icon followed by Programming >
Thonny Python IDE

Save program by .py extension on desktop


> click on terminal as shown in above picture
> cd Desktop/ cd code/ # we store code on desktop as code
> python filename.py. # to execute program

4
Sensor Description
1. Soil Moisture Sensor

The dielectric constant of soil increases as the water content of the soil increases.
The sensor is designed to estimate soil volumetric water content based on the
dielectric constant of the soil. The dielectric constant can be thought of as the soil's
ability to transmit electricity. The dielectric constant of soil increases as the water
content of the soil increases. This response is due to the fact that the dielectric
constant of water is much larger than the other soil components, including air.
Thus, measurement of the dielectric constant gives a predictable estimation of
water content.

Soil moisture

Specification:

• Input Voltage 3.3 – 5V.


• Output Voltage 0 – 4.2V.
• Input Current 35mA.
• Output signal both analog and digital.
Light Sensor
A Light Sensor generates an output signal indicating the intensity of light by measuring
the radiant energy that exists in a very narrow range of frequencies basically called “light”,
and which ranges in frequency from “Infrared” to “Visible” up to “Ultraviolet” light
spectrum.

The light sensor converts this “light energy” whether visible or in the infrared parts of the
spectrum into an electrical signal output. From “Infrared” to “Visible” up to “Ultraviolet”
light spectrum. Sensitivity can be adjusted through potentiometer.

5
Light sensor
Specificatio
n:
• Using photosensitive resistance sensor sensitive type.
• Working Voltage: 3.3V-5V.
• Output form: Digital Switch shows (0 for Brightness and 1 for darkness).
• Fixed Bolt Hole, easy installation.

Temperature and Humidity Sensor:


The DHT11 is a digital temperature and humidity sensor. It uses a humidity sensor
and a thermistor to measure the surrounding air, and spits out a digital signal on the
data pin. It is simple to use, but requires careful timing to grab data. You can only get
new data from it once every 2 seconds, so when using our library, sensor readings

can be up to 2 seconds old.


DHT11

Specification:
• Operating Voltage: 3.5V to 5.5V.
• Operating current: 0.3mA (measuring) 60uA (standby) Output: Serial data.
• Temperature Range: 0°C to 50°C. Humidity Range: 20% to 90%
• Resolution: Temperature and Humidity both are 16-bit. Accuracy: ±1°C and ±1%
Ultrasonic Distance Sensor:
An ultrasonic sensor is to measures the distance of an object using ultrasonic sound
waves. An ultrasonic sensor uses a transducer to send and receive ultrasonic pulses
that relay back information about an object’s proximity. High-frequency sound waves
reflect from boundaries to produce distinct echo patterns.

6
Ultrasonic sonic sensor
Specification:
• Working Voltage: DC 5V.
• Working Current: 15mA.
• Working Frequency: 40Hz.
• Max Range: 4m.
• Min Range: 2cm.
• Measuring Angle: 15 degree.
• Trigger Input Signal: 10µS TTL pulse.
• Echo Output Signal Input TTL level signal and the range in proportion.

RCWL-0516:
RCWL-0516 is a Doppler radar microwave motion sensor that can act as an alternative
to a PIR motion sensor. This get repository is an attempt to collect the rather scant
information on this board in one place.

Specification:
• Equipped with RCWL-9196 chip supporting 4-28V wide voltage input, high
level signal output when detecting the motion with active repeat trigger

7
• 360 degree no blind angle detection with 5-7m detecting distance, the
detection not affected by the surroundings, better performance than the IR
sensor
• Support night detecting function turn on /off, adjustable repeat trigger time and
detecting distance by add the SMD components to the corresponding pins
• Working Voltage: DC 4-28V, Board Size: 35.9 X 17.3mm/1.41 X 0.68inch

GAS Sensor
Gas Sensors (MQ2) are useful to detect the gas leakage (home and industry). It is
suitable for detecting the Smoke, CO, H2, LPG, CH4 and Alcohol. Due to fast response
time and its high sensitivity, measurement can be taken as soon as possible.
Potentiometer is used to adjust the sensitivity of the sensor.

Gas Sensor
Specification:
• Operating Voltage is +5V.
• Can be used to Measure or detect LPG, Alcohol, Propane, Hydrogen, CO
and even methane.
• Analog output voltage: 0V to 5V.
• Digital Output Voltage: 0V or 5V (TTL Logic).
• Preheat duration 20 seconds.
• Can be used as a Digital or analog sensor.
• The Sensitivity of Digital pin can be varied using the potentiometer
Analog to Digital converter:
The MCP3008 is a low cost 8-channel 10-bit analog to digital converter. The precision
of this ADC is similar to that of an Arduino Uno, and with 8 channels you can read
quite a few analog signals from the Pi. This chip is a great option if you just
need to read
simple analog signals, like from a temperature or light sensor.

8
Light Emitting Diode:
LEDs (Light Emitting Diodes) are semiconductor light sources that combine a P-type
semiconductor (larger hole concentration) with an N-type semiconductor (larger
electron concentration). Applying a sufficient forward voltage will cause the electrons
and holes to recombine at the P-N junction, releasing energy in the form of light.

9
Switches:
Switching happens reliably at specific and repeatable positions of the actuator, which
is not necessarily true of other mechanisms. They are very common due to their low
cost but high durability, greater than 1 million cycles and up to 10 million cycles for
heavy-duty models. This durability is a natural consequence of the design.

4x4 keypad:

10
TESTING of LDR SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Light Dependent Resistors (LDR) with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C1 to C13

Click on pi icon select programming Thonny

Write code as per requirement and save it with .py extension example ldr.py on

desktop. And then Run program output will display on Shell as shown below

11
CODE
#CONNECT C1 TO C14 WITH 4 PIN FEMALE CONNECTOR AND RUN
PROGRAM
import RPi.GPIO as GPIO
import time

light = 37 #Board number

def setup():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(light,GPIO.IN)

def read_light():
while True:

12
def destroy(): #When program ending, the function is executed.
GPIO.cleanup()

if name == ' main ': #Program starting from here


try:
setup()

read_light()

except KeyboardInterrupt:

destroy() light_state = GPIO.input(light)

if light_state == 0:

print("Light Detected")

elif light_state == 1:

print("Light Not Detected")

time.sleep(.3)

def destroy(): #When program ending, the function is executed.


GPIO.cleanup()

if name == ' main ': #Program starting from here


try:
setup()
read_light()
except KeyboardInterrupt:
destroy()

13
TESTING of DHT11 SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Digital Humidity and Temperature (DHT) with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C12 to C7

Click on pi icon select programming Thonny

Write code as per requirement and save it with .py extension example dht11.py on

desktop. And then Run program output will display on Shell as shown below

14
CODE
#Before executing this program intsall Adafruit_DHT11 Library using follwing

command #sudo apt-get install Adafruit_DHT11

#connect rmc from c12 to

c7 import time

import Adafruit_DHT

#Set the type of sensor and the pin for

sensor sensor = Adafruit_DHT.DHT11

pin = 4 # gpio 4 board pin 7

while(1):

15
try:

humidity, temperature = Adafruit_DHT.read_retry(sensor,

pin) print ("Humidity ="+str(humidity))

print ("Temperature

="+str(temperature)) except ValueError:

print ("Unable to read data")

Note if unable to find bcm try with beagle bone then go for

Go to file > USR > LOCAL > LIB > 3.9 > distpackages > Adafruit_DHT > Platform_detect.py >

Right click on Adafruit_DHT open in terminal > ls > platfoem_detect.py is available

Type sudo nano platform_detech.py and add bcm2711 like below > ctrl+x to save & exit.

16
TESTING of SOILMOISTURE SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Soil Moisture with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C11 to C8

Click on pi icon select programming Thonny

Write code as per requirement and save it with .py extension example dht11.py on

desktop. And then Run program output will display on Shell as shown below

17
CODE
import RPi.GPIO as

GPIO import time

soil = 13 #Board number

relay = 12

def setup(): GPIO.setmode(GPIO.BOARD)

GPIO.setup(soil,GPIO.IN)

GPIO.setup(relay,GPIO.OUT)

def read_soil():
while True:

soil_state = GPIO.input(soil)

if soil_state == 0:
18
print("soil Moisture Not

Detected") print("Relay on")

GPIO.output(relay,True)

elif soil_state == 1:

print("Soil Moisture

Detected") print("Relay off")

GPIO.output(relay,False)

time.sleep(.3)

def destroy(): #When program ending, the function is executed.

GPIO.cleanup()

if name == ' main ': #Program starting from

here try:

setup()

read_soil()

except

KeyboardInterrupt:

destroy()

19
TESTING of RCWL MOTION DETECHTOR SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Motion Detecting sensor (RCWL) with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C16 to C9

20
CODE
import RPi.GPIO as GPIO

import time

rcwl = 11 #Board

number def setup():

GPIO.setmode(GPIO.BOARD)

GPIO.setup(rcwl,GPIO.

IN) def read_rcwl():

while True:

21
rcwl_state = GPIO.input(rcwl) if rcwl_state == 0:

print("motion not Detected") elif rcwl_state ==1:

print("motion Detected")

time.sleep(.3)

def destroy(): #When program ending, the function is executed.

GPIO.cleanup()

if name == ' main ': #Program starting from here try:

setup()

read_rcwl()

except

KeyboardInterrupt: destroy()

22
TESTING of ULTRASONIC SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Ultrasonic sensor with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C15 to C10

23
CODE
# Program to test Ultrasonic Distance

Sensor # Connect from c15 to c10

import RPi.GPIO as GPIO #Import GPIO library import time #Import time library

GPIO.setmode(GPIO.BCM) #Set GPIO pin numbering

TRIG = 19 #Associate pin 35 to TRIG

ECHO = 13 #Associate pin 33 to ECHO

print ("Distance measurement in progress")

GPIO.setup(TRIG,GPIO.OUT) #Set pin as GPIO out

GPIO.setup(ECHO,GPIO.IN)

24
while True:

GPIO.output(TRIG, False) #Set TRIG as LOW print ("Waitng For Sensor To Settle")

time.sleep(2) #Delay of 2 seconds

GPIO.output(TRIG, True) #Set TRIG as HIGH

time.sleep(0.00001) #Delay of 0.00001

seconds GPIO.output(TRIG, False) #Set

TRIG as LOW

while GPIO.input(ECHO)==0: #Check whether the ECHO is LOW

pulse_start = time.time() #Saves the last known time of LOW pulse

while GPIO.input(ECHO)==1: #Check whether the ECHO is HIGH

pulse_end = time.time() #Saves the last known time of HIGH pulse

pulse_duration = pulse_end - pulse_start #Get pulse duration to a variable

distance = pulse_duration * 17150 #Multiply pulse duration by 17150 to get

distance distance = round(distance, 2) #Round to two decimal points

if distance > 2 and distance < 400: #Check whether the distance is

within range print ("Distance:",distance - 0.5,"cm")

else:

print ("Out Of Range") #display out of range

output can be seen in shell as distance.

25
TESTING of MQ2 GAS SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Gas Sensor with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C14 to C8

26
CODE
import RPi.GPIO as

GPIO import time

gas = 13 #Board number

relay = 12

def setup(): GPIO.setmode(GPIO.BOARD)

GPIO.setup(gas,GPIO.IN)

GPIO.setup(relay,GPIO.OUT)

27
def

read_gas():

while True: gas_state = GPIO.input(gas)

if gas_state == 0:

print("GAS Detected")

print("Relay on")

GPIO.output(relay,True)

elif gas_state == 1:

print("GAS NOT Detected")

print("Relay off")

GPIO.output(relay,False)

time.sleep(.3)

def destroy(): #When program ending, the function is executed.

GPIO.cleanup()

if name == ' main ': #Program starting from

here try:

setup()

read_gas

()

except

KeyboardInterrupt:

destroy()

28
TESTING of RELAY SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Relay Sensor with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C2 to C28

29
CODES:
import time
import RPi.GPIO as gpio

gpio.setwarnings(False)
gpio.setmode(gpio.BOARD)
gpio.setup(36, gpio.OUT)

try:
while(1):
gpio.output(36,0)
print("Relay OFF")
time.sleep(1)
gpio.output(36,1)
print("Relay ON")
time.sleep(1)
#gpio.cleanup()
except KeyboardInterrupt:
gpio.cleanup()
exit

30
TESTING of BUZZER SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Buzzer Sensor with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C2 to C27

31
CODES:
import time
import RPi.GPIO as gpio
gpio.setwarnings(False)
gpio.setmode(gpio.BOARD)
gpio.setup(36, gpio.OUT)
try:
while(1):
gpio.output(36,0)
print("Buzzer OFF")
time.sleep(1)
gpio.output(36,1)
print("Buzzer ON")
time.sleep(1)
#gpio.cleanup()
except KeyboardInterrupt:
gpio.cleanup()
exit

32
TESTING of IR SENSOR WITH RASPBERRY
PI CIRCUIT DIAGRAM
AIM: To Interface IR Sensor with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C8 to C22

33
CODES:
import RPi.GPIO as GPIO
import time
sensor1 = 11
sensor2 = 13
#sensor3 = 13
#sensor4 = 15
buzzer = 40

GPIO.setmode(GPIO.BOARD)
GPIO.setup(sensor1,GPIO.IN)
GPIO.setup(sensor2,GPIO.IN)
#GPIO.setup(sensor3,GPIO.IN)
#GPIO.setup(sensor4,GPIO.IN)
GPIO.setup(buzzer,GPIO.OUT)

GPIO.output(buzzer,False)
print "IR Sensor Ready .... "
print " "
try:
while True:
if GPIO.input(sensor1):
GPIO.output(buzzer,True)
print "Object Detected-1"

while GPIO.input(sensor1):
time.sleep(0.3)
else: GPIO.output(buzzer,False)

if GPIO.input(sensor2):
GPIO.output(buzzer,True)
print "Object Detected-2"

while GPIO.input(sensor2):
time.sleep(0.3)
else: GPIO.output(buzzer,False)

except KeyboardInterrupt:
GPIO.cleanup()

34
TESTING of LCD SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface LCD Sensor with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C9 to C31 and C10 to C 29

35
CODES:.

# Connect from CN9 to CN31 and c10 to c29


import RPi.GPIO as GPIO
import time
LCD_RS = 35
LCD_E = 33
LCD_D4 = 23
LCD_D5 = 21
LCD_D6 = 19
LCD_D7 = 24

# Define some device constants


LCD_WIDTH = 16 # Maximum characters per line
LCD_CHR = True
LCD_CMD = False

LCD_LINE_1 = 0x80 # LCD RAM address for the 1st line


LCD_LINE_2 = 0xC0 # LCD RAM address for the 2nd line

# Timing constants
E_PULSE = 0.0005
E_DELAY = 0.0005

def main():
# Main program block
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD) # Use BCM GPIO numbers
GPIO.setup(LCD_E, GPIO.OUT) # E
GPIO.setup(LCD_RS, GPIO.OUT) # RS
GPIO.setup(LCD_D4, GPIO.OUT) # DB4
GPIO.setup(LCD_D5, GPIO.OUT) # DB5
GPIO.setup(LCD_D6, GPIO.OUT) # DB6
GPIO.setup(LCD_D7, GPIO.OUT) # DB7
# Initialise display
lcd_init()

while True:

# Send some test


lcd_string("Rasbperry Pi",LCD_LINE_1)
lcd_string("16x2 LCD Test",LCD_LINE_2)
time.sleep(3) # 3 second delay

36
# Send some text
lcd_string("1234567890123456",LCD_LINE_1)
lcd_string("abcdefghijklmnop",LCD_LINE_2)

time.sleep(3) # 3 second delay


# Send some text
lcd_string("RaspberryPi-spy",LCD_LINE_1)
lcd_string(".co.uk",LCD_LINE_2)
time.sleep(3)
# Send some text
lcd_string("Follow me on",LCD_LINE_1)
lcd_string("Twitter @RPiSpy",LCD_LINE_2)
time.sleep(3)

def lcd_init():
# Initialise display
lcd_byte(0x33,LCD_CMD) # 110011 Initialise
lcd_byte(0x32,LCD_CMD) # 110010 Initialise
lcd_byte(0x06,LCD_CMD) # 000110 Cursor move direction
lcd_byte(0x0C,LCD_CMD) # 001100 Display On,Cursor Off, Blink Off
lcd_byte(0x28,LCD_CMD) # 101000 Data length, number of lines, font size
lcd_byte(0x01,LCD_CMD) # 000001 Clear display
time.sleep(E_DELAY)

def lcd_byte(bits, mode):


# Send byte to data pins
# bits = data
# mode = True for character
# False for command

GPIO.output(LCD_RS, mode) # RS

# High bits
GPIO.output(LCD_D4, False)
GPIO.output(LCD_D5, False)
GPIO.output(LCD_D6, False)
GPIO.output(LCD_D7, False)
if bits&0x10==0x10:
GPIO.output(LCD_D4, True)
if bits&0x20==0x20:
GPIO.output(LCD_D5, True)
if bits&0x40==0x40:
GPIO.output(LCD_D6, True)
if bits&0x80==0x80:
GPIO.output(LCD_D7, True)
37
# Toggle 'Enable' pin
lcd_toggle_enable()

# Low bits
GPIO.output(LCD_D4, False)
GPIO.output(LCD_D5, False)
GPIO.output(LCD_D6, False)
GPIO.output(LCD_D7, False)
if bits&0x01==0x01:
GPIO.output(LCD_D4, True)
if bits&0x02==0x02:
GPIO.output(LCD_D5, True)
if bits&0x04==0x04:
GPIO.output(LCD_D6, True)
if bits&0x08==0x08:
GPIO.output(LCD_D7, True)

# Toggle 'Enable' pin


lcd_toggle_enable()

def lcd_toggle_enable():
# Toggle enable
time.sleep(E_DELAY)
GPIO.output(LCD_E, True)
time.sleep(E_PULSE)
GPIO.output(LCD_E, False)
time.sleep(E_DELAY)

def lcd_string(message,line):
# Send string to display

message = message.ljust(LCD_WIDTH," ")

lcd_byte(line, LCD_CMD)
for i in range(LCD_WIDTH):
lcd_byte(ord(message[i]),LCD_CHR)
if name == ' main ':
try:
main()
except KeyboardInterrupt:
pass
finally:
lcd_byte(0x01, LCD_CMD)
lcd_string("Goodbye!",LCD_LINE_1)
38
GPIO.cleanup()

TESTING of LED & SWITCH SENSOR WITH


RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface LED & Switch Sensor with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C4 to C24 and C9 to C 25

39
CODES:

# Program to test LED and Switches


# Connect CN9 to CN4
# Dont forget to short the jumper pins
import time
import RPi.GPIO as gpio

gpio.setwarnings(False)
gpio.setmode(gpio.BOARD)

led4 = 23 # pin is connected to LED and it should be OUT


led3 = 21 # pin is connected to LED and it should be OUT
led2 = 19 # pin is connected to LED and it should be OUT
led1 = 24 # pin is connected to LED and it should be OUT
switch4 = 22 # pin is connected to SWITC and it should be IN
switch3 = 18 # pin is connected to SWITC and it should be IN
switch2 = 16 # pin is connected to SWITC and it should be IN
switch1= 12 # pin is connected to SWITC and it should be IN

gpio.setup(led1,gpio.OUT,initial=0)
gpio.setup(led2,gpio.OUT,initial=0)
gpio.setup(led3,gpio.OUT,initial=0)
gpio.setup(led4,gpio.OUT,initial=0)
gpio.setup(switch1,gpio.IN)
gpio.setup(switch2,gpio.IN)
gpio.setup(switch3,gpio.IN)
gpio.setup(switch4,gpio.IN)

def glow_led(event):
if event == switch1 :
gpio.output(led1, True)
time.sleep(0.2)
gpio.output(led1, False)

40
elif event == switch2 :
gpio.output(led2, True)
time.sleep(0.2)
gpio.output(led2, False)

elif event == switch3 :


gpio.output(led3, True)
time.sleep(0.2)
gpio.output(led3, False)

elif event == switch4 :


gpio.output(led4, True)
time.sleep(0.2)
gpio.output(led4, False)

gpio.add_event_detect(switch1, gpio.RISING , callback = glow_led, bouncetime = 1)


gpio.add_event_detect(switch2, gpio.RISING , callback = glow_led, bouncetime = 1)
gpio.add_event_detect(switch3, gpio.RISING , callback = glow_led, bouncetime = 1)
gpio.add_event_detect(switch4, gpio.RISING , callback = glow_led, bouncetime = 1)

try:
while(True):
#to avoid 100% CPU usage
time.sleep(1)
except KeyboardInterrupt:
#cleanup GPIO settings before exiting
gpio.cleanup()

41
TESTING of KEYPAD MATRIX SENSOR
WITH RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Keypad Matrix Sensor with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C2 to C22 and C3 to C23

42
Codes:
# Connect CN9 to CN5
#sudo apt-get install pad4pi
import RPi.GPIO as GPIO
import time
from pad4pi import rpi_gpio
KEYPAD = [
["1","2","3","A"],
["4","5","6","B"],
["7","8","9","C"],
["*","0","#","D"],
]
ROW_PINS =[21,20,16,12] # pin num 40,38,36,32
COL_PINS =[7,8,25,24] # pin num 26,24,22,18
factory = rpi_gpio.KeypadFactory()
keypad = factory.create_keypad(keypad=KEYPAD, row_pins=ROW_PINS,
col_pins=COL_PINS)
def printKey(key):
print(key)
time.sleep(0.2)
keypad.registerKeyPressHandler(printKey)

def destroy(): #When program ending, the function is executed.


GPIO.cleanup()
if name == ' main ': #Program starting from here
try:
while True:
time.sleep(0.5)
except KeyboardInterrupt:
destroy()
except :
keypad.cleanup()

43
TESTING of ANALOG to DIDGTAL SENSOR WITH RASPBERRY
AIM: To Interface MCP3008 & Potentiometer with Raspberry Pi.

CIRCUIT DIAGRAM:

Connect as per picture below on PHYSITECH trainer C18 to POT OUT and C20 to C9

44
CODE:

import busio
import digitalio
import board
import time
import adafruit_mcp3xxx.mcp3008 as MCP
from adafruit_mcp3xxx.analog_in import AnalogIn

led = digitalio.DigitalInOut(board.D25) # board pin 22


led.direction = digitalio.Direction.OUTPUT
led1= digitalio.DigitalInOut(board.D24) # board pin 18
led1.direction = digitalio.Direction.OUTPUT
led2 = digitalio.DigitalInOut(board.D23) # board pin 16
led2.direction = digitalio.Direction.OUTPUT
led3 = digitalio.DigitalInOut(board.D18) # board pin 12
led3.direction = digitalio.Direction.OUTPUT

# create the spi bus


spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)

# create the cs (chip select)


cs = digitalio.DigitalInOut(board.CE0)

# create the mcp object


mcp = MCP.MCP3008(spi, cs)

# create an analog input channel on pin 0


value1 = AnalogIn(mcp, MCP.P0)

while True:
value1 = AnalogIn(mcp, MCP.P0)
#print('Raw ADC Value: ', chan.value)
print('ADC Voltage: ' + str(value1.voltage) + 'V')
time.sleep(0.5)
if(value1.voltage<.5):
print('EMPTY')
led.value = False
led1.value = False
led2.value = False
led3.value = False
if(value1.voltage>0.5) & (value1.voltage<1):
print('LOW')
led.value = True
45
led1.value = False
led2.value = False
led3.value = False
if(value1.voltage>1) & (value1.voltage<2):
print('MEDIUM')
led.value = True
led1.value = True
led2.value = False
led3.value = False
if(value1.voltage>2) & (value1.voltage<3):
print('HIGH')
led.value = True
led1.value = True
led2.value = True
led3.value = False
if(value1.voltage>3):
print('FULL')
led.value = True
led1.value = True
led2.value = True
led3.value = True

Output will appear on shell vary potentiometer to observe variation of input signal.

46

You might also like