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

Microcontroller & IOT Lab Manual - Feb 2024

Uploaded by

tausifansari2907
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views

Microcontroller & IOT Lab Manual - Feb 2024

Uploaded by

tausifansari2907
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Microcontroller and IoT Lab REVA UNIVERSITY

BENGALURU, INDIA

SCHOOL OF COMPUTER SCIENCE AND ENGINEERING

Microcontroller and IOT Lab Manual


B22EF0406
Fourth Semester CSE/IOT
2023-2024(Even Semester)

Name

SRN

Branch CSE/IOT

Semester 4th sem

Section

Academic Year 2023-2024

School of Computer Science and Engineering Page 1


Microcontroller and IoT Lab REVA UNIVERSITY

Course Title MC&IOT Lab Course Type HC

Course Code Credits 1 Lab


Contact Work Total Number of
TLP Credits Hours Load Classes Assessment in
Per Semester Weightage
Theory - - -
Course Practice 1 2 2
Theory Practical CIE SEE
Structure - - - -
Total 1 2 2 - 26 25 25

Course Description:

This lab course aims to provide hands-on experience in designing, programming, and implementing
projects using microcontrollers and IoT technologies. Students will learn the fundamental concepts of
microcontrollers, interfacing sensors and actuators, and building IoT systems. The lab exercises will
involve hardware setup, programming, and real-world applications of microcontrollers-based projects.

Prerequisites:

1. Basic knowledge of programming concepts


2. Understanding of basic electronics and circuits

Course Objectives:

1. Understand the architecture and working principles of microcontrollers


2. Develop programming skills for microcontrollers
3. Learn sensor interfacing techniques
4. Acquire knowledge of IoT protocols and communication methods

5. Design and implement IoT projects using microcontrollers


6. Troubleshoot and debug microcontrollers-based systems

School of Computer Science and Engineering Page 2


Microcontroller and IoT Lab REVA UNIVERSITY

Course Outcomes (COs):


After the completion of the course, the student will be able to:

CO# Course Outcomes POs PSOs


CO-1 Identify different communication protocols used in 1,2,3,4,5,6,9,11,12 1,2,3
IoT applications and their characteristics.
CO-2 Demonstrate an understanding of sensor interfacing 1,2,3,4,5,6,9,11,12 1,2,3
principles and their application in data collection.
CO-3 Apply programming skills to write code for 1,2,3,4,5,6,9,11,12 1,2,3
microcontrollers to control sensors and actuators.
CO-4 Analyze and troubleshoot issues in microcontrollers- 1,2,3,4,5,6,9,11,12 1,2,3
based systems by identifying and resolving hardware
or software problems.
CO-5 Design and develop IoT projects by integrating 1,2,3,4,5,6,9,11,12 1,2,3
microcontrollers, sensors, actuators, and cloud
platforms.
CO-6 Assess the security considerations and potential 1,2,3,4,5,6,9,11,12 1,2,3
vulnerabilities in IoT systems implemented with
microcontrollers.

BLOOM’S LEVEL OF THE COURSE OUTCOMES:

Bloom’s Level
CO# Remember Understand Apply Analyze Evaluate Create
(L1) (L2) (L3) (L4) (L5) (L6)
CO-1 √

CO-2 √

CO-3 √

CO-4 √

CO-5 √

CO-6 √

School of Computer Science and Engineering Page 3


Microcontroller and IoT Lab REVA UNIVERSITY

COURSE ARTICULATION MATRIX:

PSO3
PSO1

PSO2
PO10

PO11

PO12
PO1

PO2

PO3

PO4

PO5

PO6

PO7

PO8

PO9
CO#/
Pos
CO-1 3 3 3 3 3 3 3 3 3 3 2 2
CO-2 3 3 3 3 3 3 3 3 3 3 2 2
CO-3 3 2 1 3 2 2 3 2 3 3 2 2
CO-4 2 2 2 2 2 2 2 2 2 3 2 2
CO-5 2 2 2 2 2 2 2 2 2 3 2 2
CO-6 3 2 3 2 2 2 2 2 2 3 2 2

Note:1-Low,2-Medium,3-High

School of Computer Science and Engineering Page 4


Microcontroller and IoT Lab REVA UNIVERSITY

PART-A
Expected
Tools and
Programs Problem statements Skill
Techniques
/Ability

LED Blinking: Write a program to control an LED connected to a


1 Raspberry Pi c/c++/python
microcontroller's GPIO pin. The LED should blink at a specific
frequency.

Button Input: Write a program to read the state of a push button


2 connected to a microcontroller's GPIO pin. Toggle the state of an Raspberry Pi c/c++/python
LED based on the button press.

Temperature and Humidity Sensing: Interface a temperature and


3 humidity sensor with the microcontrollers. Write a program to read Raspberry Pi c/c++/python
the sensor values and display them on an LCD or send them to a
computer via serial communication.

Motion Detection: Interface a motion sensor with the


4 Raspberry Pi c/c++/python
microcontrollers. Write a program to detect motion and trigger an
action, such as turning on an alarm or activating a motor.
Arduino IDE/
Data Logging: Implement a program to log sensor data to an PlatformIO /
5 c/c++/python
external storage device (e.g., SD card). Store the data in a specific Raspberry Pi /
format for later analysis and visualization. Proteus
Arduino IDE/
Internet of Things (IoT) Data Transmission: Interface
PlatformIO /
6 microcontrollers with an IoT platform (e.g., MQTT or cloud c/c++/python
Raspberry Pi /
service). Write a program to collect sensor data and transmit it to
Proteus
the IoT platform for storage and analysis.
Arduino IDE/ c/c++/python
Water Level Monitoring: Interface a water level sensor with the
PlatformIO /
7 microcontrollers and display the current water level on an LCD or
Raspberry Pi /
send notifications when the water level reaches a certain threshold.
Proteus

Home Automation: Design a home automation system using the Arduino IDE/
microcontrollers and various sensors and actuators. Write programs PlatformIO /
8
based on user-defined rules and triggers to control lighting, Raspberry Pi / c/c++/python
temperature, and security systems. Proteus

School of Computer Science and Engineering Page 5


Microcontroller and IoT Lab REVA UNIVERSITY

PART-B: Mini Project


Smart Garden Irrigation Arduino IDE/ Python
Raspberry Pi / programming
1 Step 1: Set up the Hardware language

1. Connect the soil moisture sensor to the Raspberry Pi's


analog input pin (e.g., GPIO 0 or A0).
2. Connect the water pump to a GPIO pin (e.g., GPIO 17) on
the Raspberry Pi.
3. Connect a relay module between the Raspberry Pi's GPIO
pin and the water pump to control the pump's power.

Step 2: Install Necessary Libraries


Ensure you have the RPi.GPIO library installed, as it will be used to
control the GPIO pins

Step 3: Write the Python Code


Create a Python script (e.g., smart_garden_irrigation.py) and add the
code

Step 4: Run the Python Script


Open a terminal on your Raspberry Pi, navigate to the directory
containing the smart_garden_irrigation.py script

The program will continuously monitor the soil moisture level. If the
moisture goes below the specified threshold, the water pump will be
turned on to water the plants for a short duration.

weather monitoring station Arduino IDE/ Python


Step 1: Gather the Hardware Raspberry Pi / programming
2. Here's a list of the hardware components you'll need for the weather language
station:

1. Raspberry Pi (any model with GPIO pins, but Raspberry Pi


3 or newer is recommended)
2. DHT11 or DHT22 Temperature and Humidity Sensor
3. BMP180 or BMP280 Barometric Pressure Sensor
4. Breadboard and jumper wires
5. MicroSD card (8GB or more) with Raspbian (or Raspberry
Pi OS) installed
6. Power supply for the Raspberry Pi
7. Internet connection (Wi-Fi or Ethernet)

Step 2: Set Up the Raspberry Pi

1. Insert the microSD card with Raspbian into the Raspberry


Pi.
2. Connect the Raspberry Pi to a monitor, keyboard, and
mouse for initial setup.
3. Boot up the Raspberry Pi, follow the setup wizard to
connect to Wi-Fi, and update the system using the terminal
(sudo apt update && sudo apt upgrade).

School of Computer Science and Engineering Page 6


Microcontroller and IoT Lab REVA UNIVERSITY

Step 3: Wiring the Sensors

1. Connect the DHT11 or DHT22 sensor to the Raspberry Pi's


GPIO pins for temperature and humidity readings.
2. Connect the BMP180 or BMP280 sensor to the Raspberry
Pi's GPIO pins for barometric pressure readings.
3. Double-check the wiring and connections to ensure
everything is properly connected.

Step 4: Install Required Libraries

1. Open the terminal on the Raspberry Pi.


2. Install the necessary libraries for the sensors:

For DHT11/DHT22 sensor:


pip install adafruit-circuitpython-dht

For BMP180/BMP280 sensor:


pip install adafruit-circuitpython-bmp180
or
pip install adafruit-circuitpython-bmp280

Step 5: Write the Python Code

Create a Python script to read data from the sensors and display it

Step 6: Run the Python Script

1. Save the Python script (e.g., weather_station.py) on the


Raspberry Pi.
2. Open a terminal, navigate to the script's location, and run
the script using:
The data should now be displayed in the terminal as it is read
from the se

Step 7: Display Data on a Web Server


To display the data on a web server, you can create a simple web
application using Flask. Make sure Flask is installed on the
Raspberry Pi..

Next, modify the Python script to expose the sensor data through
a web interface:
Create a new folder in the same directory as the Python script
called "templates." Inside this folder, create a new file called
"index.html" with the following content:

<! DOCTYPE html>


<html>
<head>
<title>Weather Station</title>
</head>
<body>
<h1>Weather Station</h1>
<p>Temperature: {{temperature }} °C</p>
<p>Humidity: {{ humidity }}%</p>
<p>Pressure: {{ pressure }} Pa</p>
<p>Altitude: {{ altitude }} meters</p>
</body>
</html>

School of Computer Science and Engineering Page 7


Microcontroller and IoT Lab REVA UNIVERSITY

Step 8: Access the Web Interface

1. Run the modified Python script again on the Raspberry Pi:


2. Open a web browser on any device connected to the same
network as the Raspberry Pi.
3. Enter the Raspberry Pi's IP address in the browser's address
bar, and you should see the weather data displayed on the
web page.

Intrusion Detection System Arduino IDE/ Python


Step 1: Gather the Hardware Raspberry Pi / programming
3. Here's a list of the hardware components you'll need for the intrusion language
detection system:

1. Raspberry Pi (any model with GPIO pins, but Raspberry Pi


3 or newer is recommended)
2. Raspberry Pi Camera Module (or USB webcam)
3. Breadboard and jumper wires (if using a PIR motion
sensor)
4. Passive Infrared (PIR) Motion Sensor (optional)
5. MicroSD card (8GB or more) with Raspbian (or Raspberry
Pi OS) installed
6. Power supply for the Raspberry Pi
7. Internet connection (Wi-Fi or Ethernet)

Step 2: Set Up the Raspberry Pi

1. Insert the microSD card with Raspbian into the Raspberry


Pi.
2. Connect the Raspberry Pi to a monitor, keyboard, and
mouse for initial setup.
3. Boot up the Raspberry Pi, follow the setup wizard to
connect to Wi-Fi, and update the system using the terminal
(sudo apt update && sudo apt upgrade).

Step 3: Install Required Libraries

1. Open the terminal on the Raspberry Pi.


2. Install the necessary libraries for the camera module and
email notifications:
Step 4: Connect the Camera Module
If you are using the official Raspberry Pi Camera Module, attach it
to the CSI port on the Raspberry Pi. Make sure it's properly
connected.

Step 5: Write the Python Code


Create a Python script to detect motion using the camera module and
send notifications via email.

Step 6: Run the Python Script

1. Save the Python script (e.g., intrusion_detection.py) on the


Raspberry Pi.
2. Open a terminal, navigate to the script's location, and run
the script using:
Step 7: Test the Intrusion Detection
Move in front of the camera to trigger the motion detection. When
motion is detected, an image will be captured and sent to the
specified email address.

School of Computer Science and Engineering Page 8


Microcontroller and IoT Lab REVA UNIVERSITY

Note: Email notifications require access to an SMTP server and valid


email credentials for sending emails. If you don't have access to an
SMTP server, you can also use third-party email services or APIs
that provide email functionality.
IoT-based vehicle tracking system Arduino IDE/ programming
Step 1: Gather the Hardware Raspberry Pi / language
4. Here's a list of the hardware components you'll need for the vehicle
tracking system:
1. Arduino board (Arduino Uno, Arduino Nano, or similar)
2. GPS module (such as NEO-6M or NEO-M8N)
3. GSM module (SIM800L or similar) for sending GPS data
to a server
4. Breadboard and jumper wires
5. Antenna for the GPS and GSM modules
6. SIM card with a data plan (for the GSM module)
7. Power supply (battery or DC adapter) for the Arduino and
modules

Step 2: Connect the Hardware

1. Connect the GPS module to the Arduino board using


jumper wires. Typically, the GPS module communicates
with Arduino through UART (Serial Communication).
2. Connect the GSM module to the Arduino board using
jumper wires. Ensure you connect the required TX and RX
pins between the GSM module and Arduino for
communication.
3. Connect the antennas to the GPS and GSM modules.

Step 3: Set Up Arduino IDE

1. Download and install the Arduino IDE from the official


Arduino website.
2. Connect your Arduino board to your computer using a USB
cable.
3. Open the Arduino IDE and set the correct board and port
under the "Tools" menu.

Step 4: Install Required Libraries

1. In the Arduino IDE, go to "Sketch" > "Include Library" >


"Manage Libraries."
2. Search and install the necessary libraries for GPS and GSM
modules. For GPS, you may need a library like TinyGPS++
or Adafruit GPS library. For GSM, you may need a library
like Adafruit FONA.

Step 5: Write the Arduino Code


Now, you'll write the Arduino code to read GPS data and send it to
a server via the GSM module.

Step 6: Upload the Code to Arduino


Verify and upload the Arduino code to your Arduino board using the
Arduino IDE.

Step 7: Set Up the Server


You need a server to receive and store the GPS data sent by Arduino.
You can use a cloud-based server, a web hosting service, or set up
your own server. The server should have an endpoint to handle
HTTP requests and store the received GPS data in a database.

School of Computer Science and Engineering Page 9


Microcontroller and IoT Lab REVA UNIVERSITY

Step 8: Test the Vehicle Tracking System


Power up the Arduino with the GPS and GSM modules and place it
in the vehicle. The Arduino will read GPS data and send it to the
server via the GSM module. You can then check the server to see the
received GPS data and track the vehicle's location in real time.

TEXTBOOKS
1. Muhammad Ali Mazidi, Janice Gillispie Mazidi, Rolin D. McKinlay. The 8051 Microcontrollers and
Embedded Systems Using Assembly and C. Pearson/Prentice Hall, 2006

2. Richard Blum. Arduino Programming in 24 Hours, Sam's Teach Yourself. Pearson Education, Inc. 2015

3. Perry Lea."Internet of Things for Architects: Architecting IoT solutions by implementing sensors,
communication infrastructure, edge computing, analytics, and security". Packt Publishing Ltd, 2018

1. Introduction of IOT Evaluation Board

School of Computer Science and Engineering Page 10


Microcontroller and IoT Lab REVA UNIVERSITY

The 2in 1 IoT Development Kit is designed to be a comprehensive tool to accelerate learning
IoT Fundamentals and apply the concepts to get a Hands-On experience by performing
different experiments. It can also be used by students and faculty alike to implement projects
based on IoT concepts. Flexibility is at the heart of the Kit, and accordingly the students and
faculty can not only use the hardware on the board in imaginative ways, but also innovatively
write programs to try their own use cases.
This user manual provides the descriptions of the features and also examples of use cases,
to guide the students to use it effectively.
The 2 in 1 IoT Development Kit can have an Arduino UNO R3 or a Raspberry Pi 3 B+
controllers, based on the order. In cases, where it was ordered with both, it can be used with
one controller at a time. The kit has both open source micro-controllers. It helps the students
to perform IoT related experiments based on either Arduino or Raspberry pi 3 B+. The kit
has on board sensors which help the students to develop number of applications on IoT. As
the kit has on board ESP8266 Wi-Fi module the students can send the different sensors
information to the cloud. Using Raspberry Pi 3 B+ one can login to the kit from a remote
location using SSH tools. One can flash code into the Arduino using Arduino IDE. The
Raspberry Pi 3 B+ works on Raspbian OS which is installed on to the SD Card. Using
Arduino IDE one can write the program in Embedded C Language. For Raspberry Pi 3 B+
one can write the programs in different Languages like Python, Embedded C, Node JS, Java,
etc.

1. IoT DEVELOPMENT KIT SPECIFICATIONS

School of Computer Science and Engineering Page 11


Microcontroller and IoT Lab REVA UNIVERSITY

Fig. 2: 1-in-1 Iot Development Kit.

Hardware Description:
1. 16×2 LCD Display
2. Humidity sensor
3. Light sensor
4. Ultrasonic sensor
5. Gas sensor
6. Soil Moisture sensor
7. Bluetooth
8. Raspberry Pi 3 B+
9. 7 – Segment display
10. Power Supply
11. UART
12. Relay
13. Buzzer
14. Stepper Motor Interface
15. 4*4 Matrix Keypad
16. LED and Switch
17. WiFi ESP8266
18. ADC MCP3008
19. RTC
20. Arduino Uno

Specifications:

School of Computer Science and Engineering Page 12


Microcontroller and IoT Lab REVA UNIVERSITY

• Board is driven using either Raspberry Pi 3 B+ or Arduino UNO R3 controllers.


• Facilitates MQTT or HTTP application protocol connection to various IoT cloud
platforms such as ThingSpeak, AWS IoT, Microsoft Azure, IBM Bluemix, etc.
• It can be connected to a Private Cloud including X trans Cloud.
• On board voltage regulator for generating 3.3V from +5V input through power
supply /adapter.
• On board Wi-Fi connectivity through ESP8266 for Arduino and internal Wi-Fi
connectivity for Raspberry Pi 3 B+.
• On board digital and analog sensors like Temperature & Humidity, Gas, Light,
Ultrasonic distance sensor and Soil moisture sensor.
• On board ADC MCP3008 for Raspberry Pi 3 B+ to connect analog sensors and
internal ADC for Arduino.
• On board 16×2 character LCD.
• On board 4×4 keypad matrixes.
• On board 32.768 kHz quartz crystal RTC DS1307 powered by coin cell battery of 3V.
• 4 LED's and 4 Switches.
• 2-digit 7 segment display.
• On board stepper motor driver to drive 5V stepper motor.
• One Buzzer.
• Connector slot for external Bluetooth module for Arduino.
• Provided extra connectors for connecting external analog and digital sensors.
• I2C, SPI communication protocols.
• On board UART connector.
• UART Software serial communication.
• On board Relay to drive external device.
• Several of the outputs to the on-board controller can be accomplished through events
from cloud such as turning on LED’s or sending a test message to the display is
possible.
• Outputs can be programmed to be event or threshold driven.
• Performance of IoT experiments and design / implementation of student projects
possible including provision to write their own programs.

3. HARDWARE DETAILS

School of Computer Science and Engineering Page 13


Microcontroller and IoT Lab REVA UNIVERSITY

Arduino UNO R3

Arduino is an open-source hardware, software and content platform with a global


community.

Specifications:

• Micro-controller: ATmega328.
• Operating Voltage: 5V.
• Input Voltage (recommended): 7-12V.
• Input Voltage (limits): 6-20V.
• Digital I/O Pins: 14 (of which 6 provide PWM output).
• Analog Input Pins: 6.
• DC Current per I/O Pin: 40 mA.
• DC Current for 3.3V Pin: 50 mA.
• Flash Memory: 32 KB of which 0.5 KB used by boot-loader.
• SRAM: 2 KB (ATmega328).
• EEPROM: 1 KB (ATmega328).
• Clock Speed: 16 MHz

Fig. 3.1: Arduino UNO R3 Board.

Raspberry Pi 3 B+

School of Computer Science and Engineering Page 14


Microcontroller and IoT Lab REVA UNIVERSITY

Specifications:

• Quad Core 1.2GHz Broadcom BCM2837 64bit CPU.


• 1GB RAM.
• BCM43438 wireless LAN and Bluetooth Low Energy (BLE) on board.
• 100 mbps Base Ethernet.
• 40-pin extended GPIO.
• 4 USB 2.0 ports.
• 4 Pole stereo output and composite video port.
• Full size HDMI.
• CSI camera port for connecting a Raspberry Pi 3 B+ camera.
• DSI display port for connecting a Raspberry Pi 3 B+ touchscreen display.
• Micro SD port for loading your operating system and storing data.
• Upgraded switched Micro USB power source up to 2.5A.

Fig. 3.2: Raspberry Pi 3 B+.

4. INSTALLATION PROCEDURE

School of Computer Science and Engineering Page 15


Microcontroller and IoT Lab REVA UNIVERSITY

Install the Arduino Software (IDE) on Windows PCs


Get the latest version from https://www.arduino.cc/en/Main/Software. You can choose
between the Installer (.exe) and the Zip packages.
When the download finishes, proceed with the installation and please allow the driver installation
process when you get a warning from the operating system.

Fig. 4.1: Arduino initial setup.

Choose the components to install.

Fig. 4.2: Select folder Arduino installation.

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

School of Computer Science and Engineering Page 16


Microcontroller and IoT Lab REVA UNIVERSITY

Fig. 4.3: Arduino IDE installing

The process will extract and install all the required files to execute properly the Arduino
Software (IDE)

Using Arduino Uno with Arduino Desktop IDE

Connect Uno board with an A B USB cable; sometimes this cable is called a USB printer cable.

Fig. 4.4: A B USB Cable.

Install the Board Drivers

If you used the Installer, Windows – from XP up to 10 – will install drivers automatically as
soon as you connect your board.

Troubleshooting:
If you downloaded and expanded the Zip package or, for some reason, the board wasn't
properly recognized, please follow the procedure below.
• Click on the Start Menu, and open up the Control Panel.
• While in the Control Panel, navigate to System and Security. Next, click on System.
Once the System window is up, open the Device Manager.
• Look under Ports (COM & LPT). You should see an open port named "Arduino
UNO (COMxx)". If there is no COM & LPT section, look under "Other Devices" for
"Unknown Device".

School of Computer Science and Engineering Page 17


Microcontroller and IoT Lab REVA UNIVERSITY

• Right click on the "Arduino UNO (COMxx)" port and choose the "Update Driver
Software" option.
• Next, choose the "Browse my computer for Driver software" option.
• Finally, navigate to and select the driver file named "arduino.inf", located in the
"Drivers" folder of the Arduino Software download (not the "FTDI USB Drivers"
sub- directory). If you are using an old version of the IDE (1.0.3 or older), choose
the Uno driver file named "Arduino UNO.inf"
• Windows will finish up the driver installation from there.

Getting Started with Sketch


Open the LED blink example sketch: File > Examples >01.Basics > Blink.

Fig. 4.5: Arduino IDE Examples

Select the Board Type and Port


You'll need to select the entry in the Tools > Board menu that corresponds to your Arduino or
Genuino board.

Select the serial device of the board from the Tools | Serial Port menu. This is likely to be
COM3 or higher (COM1 and COM2 are usually reserved for hardware serial ports).

School of Computer Science and Engineering Page 18


Microcontroller and IoT Lab REVA UNIVERSITY

To find out, you can disconnect your board and re-open the menu; the entry that disappears
should be the Arduino or Genuino board. Reconnect the board and select that serial port.

Fig. 4.7: Arduino IDE Select Port

Upload the Program


Now, simply click the "Upload" button in the environment. Wait for few seconds - you should
see the RX and TX LEDs on the board flashing. If the upload is successful, the message "Done
uploading." will appear in the status bar.

Fig: 4.8 Arduino IDE Upload Project

A few seconds after the upload finishes, you should see the pin 13 LED on the board starts
blinking (in orange). If it does, congratulations!

Installing Raspbian OS for Raspberry Pi 3 B+


Using Raspbian Stretch OS Image Downloaded in. zip format
1. Download the image file in the form Zip file from the following
link https://www.raspberrypi.org/downloads/raspbian/

School of Computer Science and Engineering Page 19


Microcontroller and IoT Lab REVA UNIVERSITY

2. Download the win32 Disk Imager Software to write the image file to SD Card from
the following link. https://sourceforge.net/projects/win32diskimager/
3. Now insert the SD Card in SD card slot and connect it to PC/Laptop.
4. Open Win32 Disk Imager, choose the .img or image file you want to write as
Image File and choose the SD drive as Device and press Write.
5. The write may take a while. Once it is done, remove the SD card and insert it into
the device you want to use with.
Initial Setup for Raspberry Pi 3 B+
1. Once Raspberry Pi 3 B+ is booted up to GUI, Connect the keyboard and Mouse to
USB slots.
2. Change the following
a. language: English
b. Country and Time Zone: India and Kolkata
3. From menu-->Preferences-->Raspberry Pi 3 B+
Configuration. Then Go To Interfaces
Enable Camera, SSH, VNC, SPI, I2C, Serial Port. Don't Enable Remaining Things.
4. Connect to WiFi.
5. Check the date and Time.
6. Open the Terminal.
Execute following default commands.
a. sudo apt-get update
b. sudo apt-get upgrade
7. 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.
8. Execute the program at terminal only by following command
sudo python <program-name>.py

Experiment 1: LED Blinking:

Aim: - Write a program to control an LED connected to a Microcontroller’s GPIO pin. The LED
should blink at a specific frequency.

School of Computer Science and Engineering Page 20


Microcontroller and IoT Lab REVA UNIVERSITY

# Connect CN9 to CN4


import time
import RPi.GPIO as gpio

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

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


led3 = 3 # pin is connected to LED and it should be OUT
led2 = 12 # pin is connected to LED and it should be OUT
led1 = 15 # pin is connected to LED and it should be OUT

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)

while(True):

gpio.output(led1, True)
gpio.output(led2, True)
gpio.output(led3, True)
gpio.output(led4, True)
time.sleep (1)

gpio.output(led1, False)
gpio.output(led2, False)
gpio.output(led3, False)
gpio.output(led4, False)
time.sleep (1)

Experiment 2: Button Input:


Aim: - Write a program to read the state of a push button connected to a microcontroller's GPIO pin.
Toggle the state of an LED based on the button press.

Hardware Details: Switches and LED’s

School of Computer Science and Engineering Page 21


Microcontroller and IoT Lab REVA UNIVERSITY

Switch and LED's are combination of 4 LED's and 4 switches which are programmed to operate
LED's using the switches.

# Connect CN9 to CN4


import time
import RPi.GPIO as gpio

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

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


led3 = 3 # pin is connected to LED and it should be OUT
led2 = 12 # pin is connected to LED and it should be OUT
led1 = 15 # pin is connected to LED and it should be OUT
switch4 = 23 # pin is connected to SWITC and it should be IN
switch3 = 21 # pin is connected to SWITC and it should be IN
switch2 = 19 # pin is connected to SWITC and it should be IN
switch1= 24 # 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)

School of Computer Science and Engineering Page 22


Microcontroller and IoT Lab REVA UNIVERSITY

gpio.output(led1, False)

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

Experiment 3: Temperature and Humidity Sensing:


Aim: - Interface a temperature and humidity sensor with the microcontrollers.
Write a program to read the sensor values and display them on an LCD or send them to a computer
via serial communication.

Hardware Details: Temperature and Humidity Sensor

School of Computer Science and Engineering Page 23


Microcontroller and IoT Lab REVA UNIVERSITY

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's fairly 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.

Specifications:

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%

# Connect RM2 to RM19

import time
import Adafruit_DHT

#Set the type of sensor and the pin for sensor


sensor = Adafruit_DHT.DHT11
pin = 4

while (1):
try:
humidity, temperature = Adafruit_DHT.read_retry (sensor, pin)
print ("Humidity ="+str(humidity))
print ("Temperature ="+str(temperature))
except ValueError:
print ("Unable to read data")

Experiment 4: Motion Detection:

Aim: - Interface a motion sensor with the microcontrollers.


Write a program to detect motion and trigger an action, such as turning on an alarm or activating a
motor.

Hardware Details: Ultrasonic sensor

School of Computer Science and Engineering Page 24


Microcontroller and IoT Lab REVA UNIVERSITY

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.

Fig.: Schematic Pin Diagram of Ultrasonic Distance Sensor.

Fig: Ultrasonic Distance Sensor .

Specifications:
● 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.

# Connect from RM4 to RM21


# Connect from CN9 to CN4
import RPi.GPIO as GPIO #Import GPIO library
import time #Import time library
GPIO.setmode(GPIO.BCM) #Set GPIO pin numbering
GPIO.setwarnings(False)

TRIG = 19 #Associate pin 23 to TRIG


ECHO = 26 #Associate pin 24 to ECHO
print ("Distance measurement in progress")

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


GPIO.setup(ECHO,GPIO.IN)
GPIO.setup(2, GPIO.OUT, initial=0)

School of Computer Science and Engineering Page 25


Microcontroller and IoT Lab REVA UNIVERSITY

GPIO.setup(3, GPIO.OUT, initial=0)

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.001) #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 <= 20:


GPIO.output(2,GPIO.HIGH)
GPIO.output(3,GPIO.HIGH)
time.sleep(0.2)

else:
GPIO.output(2, GPIO.LOW)
GPIO.output(3, GPIO.LOW)
time.sleep(0.2)
if distance > 2 and distance < 232: #Check whether the distance is within range
print ("Distance:”, distance - 0.5,"cm")
else:
print ("Out Of Range”) #display out of range

Experiment 5: Data Logging:

Aim: - Implement a program to log sensor data to an external storage device (e.g., SD card). Store the
data in a specific format for later analysis and visualization.

# Connect from RM2 to RM19

import Adafruit_DHT
import time

School of Computer Science and Engineering Page 26


Microcontroller and IoT Lab REVA UNIVERSITY

sensor=Adafruit_DHT.DHT11
sensor_pin=4

running=True

file=open('sensor_reading.txt','w')
file.write('time and date,temperature(C),temperature(F),humidity\n')

while running:
try:
humidity,temperature=Adafruit_DHT.read_retry(sensor,sensor_pin)
temperature_f=temperature * 9/5.0 + 32

if humidity is not None and temperature is not None:

print('Temperature='+str(temperature)+','+'Temperature
Fahrenheit='+str(temperature_f)+','+'Humidity='+str(humidity))

file.write(time.strftime('%H:%M:%S
%d/%m/%Y')+','+str(temperature)+','+str(temperature_f)+','+'Humidity='+str(humidity)+'\n')

time.sleep(1)

else:
print('Failed to get reading.Try again!')
time.sleep(1)

except KeyboardInterrupt:
print('program stopped')
running=False
file.close()

Experiment 6: Internet of Things (IoT) Data Transmission:

Aim: - Interface a microcontroller with an IoT platform (e.g., MQTT or cloud service).
Write a program to collect sensor data and transmit it to the IoT platform for storage and analysis.

# Connect from RM2 to RM19


import RPi.GPIO as GPIO
import time
import math
import Adafruit_DHT as dht
import urllib2

School of Computer Science and Engineering Page 27


Microcontroller and IoT Lab REVA UNIVERSITY

myAPI = 'M37F81T4C543NP68'
# URL where we will send the data, Don't change it
baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI

GPIO.setmode(GPIO.BCM)

sensor = dht. DHT11


dht11_pin = 4 # The Temperature and Humidity Sensor goes on digital port 2.

temp=0.0
humidity = 0.0

print("***********************")
print("")
print("IOT Development Kit")
print("")
print("***********************")

while True:
try:
print("Scanning for sensors data....")
time.sleep(2)
print("---------------------")
#print()
humidity, temp = dht.read_retry(sensor, dht11_pin)

if math.isnan(temp) == False and math.isnan(humidity) == False:


#print("Temperature and Humidity sensor value")
print("------------------")
print("Temperature = %.02f C"%(temp))
print("------------------")
print("Humidity = %.02f%%"%(humidity))
print("------------------")

conn = urllib2.urlopen(baseURL + '&field1=%s&field2=%s' % (temp, humidity))

print("Data Sent to cloud")


time.sleep(1)
except:
print("exception")
break

THINGSPEAK CLOUD INTRODUCTION:

School of Computer Science and Engineering Page 28


Microcontroller and IoT Lab REVA UNIVERSITY

ThingSpeak is a cloud platform providing various services exclusively targeted for building
IoT applications. It offers the capabilities of real-time data collection, visualizing the
collected data in the form of charts, ability to create plugins and apps for collaborating with
web services, social network and other APIs. We will consider each of these features in
detail below.
The core element of ThingSpeak is a ‘ThingSpeak Channel’. A channel stores the data that
we send to ThingSpeak and comprises of the below elements:
• 8 fields for storing data of any type – These can be used to store the data from
a sensor or from an embedded device.
• 3 location fields – Can be used to store the latitude, longitude and the
elevation. These are very useful for tracking a moving device.
• 1 status field – A short message to describe the data stored in the channel.

To use ThingSpeak, we need to sign up and create a channel. Once we have a channel, we
can send the data, allow ThingSpeak to process it and also retrieve the same. Let us start
exploring ThingSpeak by signing up and setting up a channel.
Using https://thingspeak.com/ the link user can connect to the ThingSpeak Cloud.

Here are the few screenshots of ThingSpeak Cloud.


Create Channel: Once the user login to ThingSpeak account. Tap on the channel tab in
the menu. follow these steps.

New channel button > Fill the details > Save Channel

School of Computer Science and Engineering Page 29


Microcontroller and IoT Lab REVA UNIVERSITY

Fig: Create new channel

Channels

Fig: All channels

School of Computer Science and Engineering Page 30


Microcontroller and IoT Lab REVA UNIVERSITY

Fields Data

Fig: Graphical Representation of sensor data

API Reference

ThingSpeak is an IoT platform that uses channels to store data sent from apps or devices. With
the settings described in Channel Configurations, you create a channel, and then send and
retrieve data to and from the channel. You can make your channels public to share data. Using
the REST API calls such as GET, POST, PUT, and DELETE, you can create a channel and
update its feed, update an existing channel, clear a channel feed, and delete a channel. You can
also use the MQTT Publish method to update a channel feed and MQTT Subscribe to receive
messages when a channel updates. Learn more about when to Choose between REST API and
MQTT API while updating a channel.

MATLAB analysis and visualization apps enable you to explore and view your channel data.
ThingSpeak enables you to interact with social media, web services, and devices.

Experiment 7: Water Level Monitoring:

School of Computer Science and Engineering Page 31


Microcontroller and IoT Lab REVA UNIVERSITY

Aim: - Interface a water level sensor with the microcontrollers and display the current water level on
an LCD or send notifications when the water level reaches a certain threshold.

Hardware Details: 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.

Fig.: Schematic Pin Diagram of Soil Moisture Sensor.

Fig.: Ultrasonic Sensor.

Specifications:
Input Voltage 3.3 – 5V.
Output Voltage 0 – 4.2V.
Input Current 35mA.
Output Signal Both Analog and Digital.

// Connect RM6 - RM23 on the kit for Soil moisture sensor


// Connect CN9-CN4 on the kit for LED

School of Computer Science and Engineering Page 32


Microcontroller and IoT Lab REVA UNIVERSITY

int soil_pin = A1; // Arduino pin A1


int led1 = A4;
int led2 = A5;

void setup()
{
pinMode(soil_pin, INPUT); //Set the Soil senssor to input mode;
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);

Serial.begin(9600); //Set the serial monitor baud rate


}

void loop()
{
int moisture_value = analogRead(soil_pin); // read the soil sensor value
if (moisture_value >= 500){ // moisture threshold value
digitalWrite(led1,HIGH);
digitalWrite(led2,HIGH);
delay(500);
}

else{
digitalWrite(led1,LOW);
digitalWrite(led2,LOW);
delay(500);
}

Serial.print("Soil Moisture value : ");


Serial.println(moisture_value); // display the moisture value on serial monitor

Experiment 8: Home Automation

School of Computer Science and Engineering Page 33


Microcontroller and IoT Lab REVA UNIVERSITY

Aim: - Design a home automation system using the microcontrollers and various sensors and
actuators. Write programs based on user-defined rules and triggers to control lighting, temperature,
and security systems.

Hardware Details: LDR (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.

Fig.: Schematic Pin Diagram of Light Sensor

Fig.: Light Sensor.

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

Stepper Motor

Stepping motor is a brush-less synchronous electric motor that converts digital pulses into mechanical
shaft rotation. The motor's position can then be commanded to move and hold at one of these steps
without any position sensor for feedback (an open-loop controller), as long as the motor is carefully
sized to the application in respect to torque and speed.

School of Computer Science and Engineering Page 34


Microcontroller and IoT Lab REVA UNIVERSITY

Fig.: Schematic Pin Diagram of Stepper Motor Interface.

//Connect RM3 to RM20 for light sensor


//Conect CN9 to CN4 for LED
//Conect CN9 to CN7 for Stepper motor

#include <Stepper.h> //Arduino Stepper Motor library


#include <dht.h> // Arduino Temperature and Humidity Sensor library

#define DHT11_PIN 4 //define temperature sensor pin

int stepsperrevolution=200;
int motorstop=0;
int motorspeed=10;
Stepper myStepper(stepsperrevolution, 10,12,11,13);

dht DHT; //Create a dht variable

int light_pin = 5; //Arduino pin D5

const int ledPin1 = A5; // number of the LED 1 pin


const int ledPin2 = A4; // number of the LED 2 pin

void setup() { // Set Pins to Outputs Or Inputs


pinMode(light_pin, INPUT); // Light Sensor as Input
pinMode(ledPin1, OUTPUT); // initialize the LED pins as an outputs:
pinMode(ledPin2, OUTPUT); // initialize the LED pins as an outputs:

digitalWrite(ledPin1, LOW); // initialize LED off:


digitalWrite(ledPin2, LOW); // initialize LED off:
myStepper.setSpeed(motorspeed);

Serial.begin(9600);
}

School of Computer Science and Engineering Page 35


Microcontroller and IoT Lab REVA UNIVERSITY

void loop() {

int light_data = digitalRead(light_pin);


if (light_data){
digitalWrite(ledPin1, HIGH); //if HIGH turn LED on:
digitalWrite(ledPin2, HIGH); //if HIGH turn LED on:
}
else
{
digitalWrite(ledPin1, LOW); // turn LED off:
digitalWrite(ledPin2, LOW); // turn LED off:
}

DHT.read11(DHT11_PIN);
int temp=DHT.temperature;
if (temp >= 27){ // moisture threshold value
myStepper.step(stepsperrevolution);
}
else
myStepper.step(motorstop); //stop the motor

Serial.print("Temperature = ");
Serial.println(DHT.temperature);
Serial.print("Humidity = ");
Serial.println(DHT.humidity);
delay(500);
}

School of Computer Science and Engineering Page 36

You might also like