Microcontroller & IOT Lab Manual - Feb 2024
Microcontroller & IOT Lab Manual - Feb 2024
BENGALURU, INDIA
Name
SRN
Branch CSE/IOT
Section
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:
Course Objectives:
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 √
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
PART-A
Expected
Tools and
Programs Problem statements Skill
Techniques
/Ability
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
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.
Create a Python script to read data from the sensors and display it
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:
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
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.
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:
3. HARDWARE DETAILS
Arduino UNO R3
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
Raspberry Pi 3 B+
Specifications:
4. INSTALLATION PROCEDURE
Choose the installation directory (we suggest to keep the default one)
The process will extract and install all the required files to execute properly the Arduino
Software (IDE)
Connect Uno board with an A B USB cable; sometimes this cable is called a USB printer cable.
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".
• 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.
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).
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.
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!
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
Aim: - Write a program to control an LED connected to a Microcontroller’s GPIO pin. The LED
should blink at a specific frequency.
gpio.setwarnings(False)
gpio. setmode(gpio.BOARD)
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)
Switch and LED's are combination of 4 LED's and 4 switches which are programmed to operate
LED's using the switches.
gpio.setwarnings(False)
gpio.setmode(gpio.BOARD)
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)
try:
while(True): #to avoid 100% CPU usage
time.sleep(1)
except KeyboardInterrupt: #cleanup GPIO settings before exiting
gpio.cleanup()
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:
import time
import Adafruit_DHT
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")
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.
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.
while True:
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
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.
import Adafruit_DHT
import time
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
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()
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.
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)
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)
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.
New channel button > Fill the details > Save Channel
Channels
Fields 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.
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.
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.
Specifications:
Input Voltage 3.3 – 5V.
Output Voltage 0 – 4.2V.
Input Current 35mA.
Output Signal Both Analog and Digital.
void setup()
{
pinMode(soil_pin, INPUT); //Set the Soil senssor to input mode;
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
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);
}
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.
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.
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.
int stepsperrevolution=200;
int motorstop=0;
int motorspeed=10;
Stepper myStepper(stepsperrevolution, 10,12,11,13);
Serial.begin(9600);
}
void loop() {
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);
}