IoT Practical Manual
IoT Practical Manual
x=1
numTimes=int(input("Enter tottal number of times to blink"))
speed=float(input("Enter length of each blink(seconds) : "))
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(5,GPIO.OUT)
GPIO.setup(10,GPIO.OUT)
GPIO.setup(19,GPIO.OUT)
GPIO.setup(26,GPIO.OUT)
GPIO.setup(29,GPIO.OUT)
def Blink(numTimes,speed):
for i in range(0,numTimes):
GPIO.output(5,True)
print ("Iteration ", (i+1))
GPIO.output(10,True)
print ("Iteration ", (i+1))
GPIO.output(19,True)
print ("Iteration ", (i+1))
GPIO.output(26,True)
print ("Iteration ", (i+1))
GPIO.output(29,True)
print ("Iteration ", (i+1))
GPIO.output(29,False)
print ("Iteration ", (i+1))
time.sleep(speed)
GPIO.output(26,False)
print ("Iteration ", (i+1))
T.Y.B.Sc. (I.T.) 2019
time.sleep(speed)
GPIO.output(19,False)
print ("Iteration ", (i+1))
time.sleep(speed)
GPIO.output(10,False)
print ("Iteration ", (i+1))
time.sleep(speed)
GPIO.output(5,False)
print ("Iteration ", (i+1))
time.sleep(speed)
Blink(numTimes,speed)
print("Done")
T.Y.B.Sc. (I.T.) 2019
TM1637 script
In order to control the LED, we use a special script with pre-defined functions. Various
functions are available in the script, for example you can display numbers and adjust the
intensity of the LEDs. Download the script with the command:
wget https://raspberrytips.nl/files/tm1637.py
Code:
import sys
import time
import datetime
import RPi.GPIO as GPIO
T.Y.B.Sc. (I.T.) 2019
import tm1637
Display = tm1637.TM1637(23,24,tm1637.BRIGHT_TYPICAL)
Display.Clear()
Display.SetBrightnes(1)
while(True):
now = datetime.datetime.now()
hour = now.hour
minute = now.minute
second = now.second
currenttime = [ int(hour / 10), hour % 10, int(minute / 10), minute % 10 ]
Display.Show(currenttime)
Display.ShowDoublepoint(second % 2)
time.sleep(1)
T.Y.B.Sc. (I.T.) 2019
1. Hardware Requirements
2. Software Requirements
Hardware requirements
To build this project, the following components/part are required;
Software Requirements
The software requirements for this project are basically the python modules
(matplotlib and drawnow) that will be used for data visualization and the Adafruit
module for interfacing with the ADS1115 ADC chip. I will show how to install these
modules on the Raspberry Pi as we proceed.
While this tutorial will work irrespective of the raspberry pi OS used, I will be using
the Raspberry Pi stretch OS and I will assume you are familiar with setting up the
Raspberry Pi with the Raspbian stretch OS, and you know how to SSH into the
raspberry pi using a terminal software like putty. If you have issues with any of this,
there are tons of Raspberry Pi Tutorials on this website that can help.
With all the hardware components in place, let's create the schematics and connect the
components together.
Circuit Diagram:
To convert the analog input signals to digital signals which can be visualized with the
Raspberry Pi, we will be using the ADS1115 ADC chip. This chip becomes important
because the Raspberry Pi, unlike Arduino and most micro-controllers, does not have an
on-board analog to digital converter(ADC). While we could have used any raspberry pi
T.Y.B.Sc. (I.T.) 2019
compatible ADC chip, I prefer this chip due to its high resolution(16bits) and its well
documented datasheet and use instructions by Adafruit. You can also check
our Raspberry Pi ADC tutorial to learn more about it.
sudo raspi-config
When the configuration panels open, select interface options, select I2C and click
enable.
T.Y.B.Sc. (I.T.) 2019
cd ~
Next, clone the Adafruit git folder for the library by running;
Change into the cloned file’s directory and run the setup file;
cd Adafruit_Python_ADS1x15
sudo python setup.py install
After installation, your screen should look like the image below.
T.Y.B.Sc. (I.T.) 2019
cd examples
Next, run the sampletest.py example which displays the value of the four channels on
the ADC in a tabular form.
Run the example using:
T.Y.B.Sc. (I.T.) 2019
python simpletest.py
If the I2C module is enabled and connections good, you should see the data as shown
in the image below.
If an error occurs, check to ensure the ADC is well connected to the PI and I2C
communication is enabled on the Pi.
You should get an outcome like the image below after running it.
T.Y.B.Sc. (I.T.) 2019
With all the dependencies installed, we are now ready to write the code.
Python Code for Raspberry Pi Oscilloscope:
The python code for this Pi Oscilloscope is fairly simple especially if you are familiar
with the python matplotlib module. Before showing us the whole code, I will try to
break it into part and explain what each part of the code is doing so you can have
enough knowledge to extend the code to do more stuffs.
At this stage it is important to switch to a monitor or use the VNC viewer, anything
through which you can see your Raspberry Pi’s desktop, as the graph being plotted
won’t show on the terminal.
With the monitor as the interface open a new python file. You can call it any name
you want, but I will call it scope.py.
With the file created, the first thing we do is import the modules we will be using;
import time
import matplotlib.pyplot as plt
from drawnow import *
import Adafruit_ADS1x15
Next, we create an instance of the ADS1x15 library specifying the ADS1115 ADC
adc = Adafruit_ADS1x15.ADS1115()
Next, we set the gain of the ADC. There are different ranges of gain and should be
chosen based on the voltage you are expecting at the input of the ADC. For this
T.Y.B.Sc. (I.T.) 2019
tutorial, we are estimating a 0 – 4.09v so we will be using a gain of 1. For more info on
gain you can check the ADS1015/ADS1115 datasheet.
GAIN = 1
Next, we need to create the array variables that will be used to store the data to be
plotted and another one to serve as count.
Val = [ ]
cnt = 0
Next, we make know our intentions of making the plot interactive known so as
to enable us plot the data live.
plt.ion()
Next, we start continuous ADC conversion specifying the ADC channel, in this case,
channel 0 and we also specify the gain.
It should be noted that all the four ADC channels on the ADS1115 can be read at the
same time, but 1 channel is enough for this demonstration.
adc.start_adc(0, gain=GAIN)
Next we create a function def makeFig, to create and set the attributes of the
graph which will hold our live plot. We first of all set the limits of the y-axis
using ylim, after which we input the title of the plot, and the label name before we
specify the data that will be plotted and its plot style and color using plt.plot(). We can
also state the channel (as channel 0 was stated) so we can identify each signal when the
four channels of the ADC are being used. plt.legend is used to specify where we want
the information about that signal(e.g Channel 0) displayed on the figure.
plt.ylim(-5000,5000)
plt.title('Osciloscope')
plt.grid(True)
plt.ylabel('ADC outputs')
T.Y.B.Sc. (I.T.) 2019
Next we write the while loop which will be used constantly read data from the ADC
and update the plot accordingly.
The first thing we do is read the ADC conversion value
value = adc.get_last_result()
Next we print the value on the terminal just to give us another way of confirming the
plotted data. We wait a few seconds after printing then we append the data to the list
(val) created to store the data for that channel.
print('Channel 0: {0}'.format(value))
time.sleep(0.5)
val.append(int(value))
drawnow(makeFig)
To ensure the latest data is what is available on the plot, we delete the data at index 0
after every 50 data counts.
cnt = cnt+1
if(cnt>50):
val.pop(0)
That’s all!
The complete Python code is given at the end of this tutorial.
If you used a different name other than scope.py, don’t forget to change this to match.
After a few minutes, you should see the ADC data being printed on the terminal.
Occasionally you may get a warning from matplotlib (as shown in the image below)
which should be suppressed but it doesn’t affect the data being displayed or the plot in
anyway. To suppress the warning however, the following lines of code can be added
after the import lines in our code.
Import warnings
import matplotlib.cbook
warnings.filterwarnings(“ignore”, category=matplotlib.cbook.mplDeprecation)
T.Y.B.Sc. (I.T.) 2019
Code:
import time
import matplotlib.pyplot as plt
#import numpy
from drawnow import *
# Import the ADS1x15 module.
import Adafruit_ADS1x15
# Create an ADS1115 ADC (16-bit) instance.
adc = Adafruit_ADS1x15.ADS1115()
GAIN = 1
val = [ ]
cnt = 0
plt.ion()
# Start continuous ADC conversions on channel 0 using the previous gain value.
adc.start_adc(0, gain=GAIN)
print('Reading ADS1x15 channel 0')
#create the figure function
def makeFig():
plt.ylim(-5000,5000)
plt.title('Osciloscope')
plt.grid(True)
plt.ylabel('ADC outputs')
plt.plot(val, 'ro-', label='Channel 0')
plt.legend(loc='lower right')
T.Y.B.Sc. (I.T.) 2019
while (True):
# Read the last ADC conversion value and print it out.
value = adc.get_last_result()
print('Channel 0: {0}'.format(value))
# Sleep for half a second.
time.sleep(0.5)
val.append(int(value))
drawnow(makeFig)
plt.pause(.000001)
cnt = cnt+1
if(cnt>50):
val.pop(0)
T.Y.B.Sc. (I.T.) 2019
/start
1.5 Create a new Bot
Look at your Pi, you can see the LED on and off when you send "on" and "off" to our bot.
Code:
import sys
import time
import random
import datetime
import telepot
import RPi.GPIO as GPIO
#LED
def on(pin):
GPIO.output(pin,GPIO.HIGH)
return
def off(pin):
GPIO.output(pin,GPIO.LOW)
return
# to use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BOARD)
# set up GPIO output channel
GPIO.setup(11, GPIO.OUT)
T.Y.B.Sc. (I.T.) 2019
def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
if command == 'on':
bot.sendMessage(chat_id, on(11))
elif command =='off':
bot.sendMessage(chat_id, off(11))
while 1:
time.sleep(10)
Required Components:
The following components will be needed to set up a raspberry pi as a wireless access
point:
1. Raspberry Pi 2
2. 8GB SD card
3. WiFi USB dongle
4. Ethernet cable
5. Power supply for the Pi.
6. Monitor (optional)
7. Keyboard (optional)
8. Mouse (optional)
followed by;
followed by;
Scroll to the bottom of the config file and add the following lines.
interface wlan0
static ip_address=192.168.1.200/24 #machine ip address
After adding the lines, the config file should look like the image below.
Restart the dhcpcd service to effect the changes made to the configuration using;
assigned to devices that connect to the wireless access point. To do this, we need to
edit the configuration file of the dnsmasq software but the config file of the software
contains way too much info and a lot could go wrong If not properly edited, so instead
of editing, we will be creating a new config file with just the amount of information
that is needed to make the wireless access point fully functional.
Before creating the new config file, we keep the old on safe by moving and renaming
it.
with the editor launched, copy the lines below and paste in or type directly into it.
interface = wlan0 #indicate the communication interface which is usually wlan0 for wire
less
dhcp-range = 192.168.1.201, 192.168.1.220, 255.255.255.0,24h #start addr(other than m
achine ip assigned above), end addr, subnet mask, mask
the content of the file should look like the image below.
T.Y.B.Sc. (I.T.) 2019
Save the file and exit. The content of this config file is just to specify the range of IP
address that can be assigned to devices connected to the wireless access point.
With this done, we will be able to give an identity to devices on our network.
The next set of steps will help us configure the access point host software, setup the
ssid, select the encrytpion etc.
interface=wlan0
driver=nl80211
ssid=piNetwork
hw_mode=g
channel=7
T.Y.B.Sc. (I.T.) 2019
wmm_enabled=0
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=mumbai123 # use a very secure password and not this
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
The content of the file should look like the image below.
Feel free to change the ssid and password to suit your needs and desire.
Save the config file and exit.
After the config file has been saved, we need to point the hostapd software to where
T.Y.B.Sc. (I.T.) 2019
find the line with daemon_conf commented out as shown in the image below.
Uncomment the DAEMON_CONF line and add the line below in between the quotes
in front of the “equal to” sign.
/etc/hostapd/hostapd.conf
Step 7: Fire it up
Since we disabled the two software initially, to allow us configure them properly, we
need to restart the system after configuration to effect the changes.
Use;
and add the following lines at the bottom of the system, just before the exit 0 statement
sudo reboot
As soon as the system comes back on, you should be able to access the wireless access
point using any Wi-Fi enabled device and the password used during the setup.
Accessing the Internet from the Raspberry Pi’s Wi-Fi Hotspot
To implement this, we need to put a “bridge” in between the wireless device and the
Ethernet device on the Raspberry Pi (the wireless access point) to pass all traffic
between the two interfaces. To set this up, we will use the bridge-utils software.
Install hostapd and bridge-utils. While we have installedhostapd before, run the
installation again to clear all doubts.
When a bridge is created, a higher level construct is created over the two ports being
bridged and the bridge thus becomes the network device. To prevent conflicts, we need
to stop the allocation of IP addresses by the DHCP client running on the Raspberry Pi
T.Y.B.Sc. (I.T.) 2019
to the eth0 and wlan0 ports. This will be done by editing the config file of the dhcpcd
client to include denyinterfaces wlan0 and denyinterfaces eth0 as shown in the image
below.
The file can be edited by running the command;
Note: From this point on, ensure you don’t disconnect the Ethernet cable from your
PC if you are running in headless mode as you may not be able to connect via SSH
again since we have disabled the Ethernet port. If working with a monitor, you have
nothing to fear.
Next, we create a new bridge called br0
Next, we connect the ethernet port (eth0) to the bridge (br0) using;
Next, we edit the interfaces file using sudo nano /etc/network/interfaces so various
devices can work with the bridge. Edit the interfaces file to include the information
below;
#Bridge setup
auto br0
iface br0 inet manual
bridge_ports eth0 wlan0
Lastly we edit the hostapd.conf file to include the bridge configuration. This can be
done by running the command: sudo nano /etc/hostapd/hostapd.conf and editing the
file to contain the information below. Note the bridge was added below the wlan0
interface and the driver line was commented out.
interface=wlan0
bridge=br0
ssid=piNetwork
hw_mode=g
channel=7
wmm_enabled=0
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=mcctest1
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
6
Raspberry Pi GPS Module Interfacing.
code:
import time
import serial
import string
import pynmea2
import RPi.GPIO as gpio
gpio.setmode(gpio.BCM)
port = "/dev/ttyAMA0" # the serial port to which the pi is connected.
if data[0:6] == '$GPGGA':
msg = pynmea2.parse(data)
print msg
time.sleep(2)
T.Y.B.Sc. (I.T.) 2019
The I2c module can be powered with either 5V or 3.3V but the screen works best if it
provided with 5V. However the Pi’s GPIO pins aren’t 5V tolerant so the I2C signals
need to be level shifted. To do this I used an I2C level shifter.
This requires a high level voltage (5V) and a low level voltage (3.3V) which the device
uses as a reference. The HV pins can be connected to the screen and two of the LV pins
to the Pi’s I2C interface.
Level I2C
Shifter Pi Backpack
LV 3.3V –
LV1 SDA –
LV2 SCL –
HV 5V VCC
HV1 SDA
HV2 SCL
While experimenting I found that it worked fine without the level shifting but I couldn’t
be certain this wasn’t going to damage the Pi at some point. So it’s probably best to play
it safe!
The example script will allow you to send text to the screen via I2C. It is very similar to
my scripts for the normal 16×2 screen. To download the script directly to your Pi you
T.Y.B.Sc. (I.T.) 2019
can use :
wget https://bitbucket.org/MattHawkinsUK/rpispy-misc/raw/master/python/lcd_i2c.py
In order to use I2C devices you must enable the interface on your Raspberry Pi. This can
be done by following my “Enabling The I2C Interface On The Raspberry Pi” tutorial. By
default the I2C backpack will show up on address 0x27.
Code:
import smbus
import time
LCD_BACKLIGHT = 0x08 # On
#LCD_BACKLIGHT = 0x00 # Off
# Timing constants
E_PULSE = 0.0005
E_DELAY = 0.0005
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)
# High bits
bus.write_byte(I2C_ADDR, bits_high)
lcd_toggle_enable(bits_high)
# Low bits
bus.write_byte(I2C_ADDR, bits_low)
lcd_toggle_enable(bits_low)
def lcd_toggle_enable(bits):
# Toggle enable
time.sleep(E_DELAY)
bus.write_byte(I2C_ADDR, (bits | ENABLE))
time.sleep(E_PULSE)
bus.write_byte(I2C_ADDR,(bits & ~ENABLE))
time.sleep(E_DELAY)
def lcd_string(message,line):
# Send string to display
lcd_byte(line, LCD_CMD)
for i in range(LCD_WIDTH):
T.Y.B.Sc. (I.T.) 2019
lcd_byte(ord(message[i]),LCD_CHR)
def main():
# Main program block
# Initialise display
lcd_init()
while True:
time.sleep(3)
time.sleep(3)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
finally:
lcd_byte(0x01, LCD_CMD)
T.Y.B.Sc. (I.T.) 2019
8
IoT based Web Controlled Home Automation using Raspberry Pi
Code:
try:
while True:
GPIO.output(relay_pin, 0)
sleep(5)
GPIO.output(relay_pin, 1)
sleep(5)
except KeyboardInterrupt:
pass
GPIO.cleanup()
T.Y.B.Sc. (I.T.) 2019
9
Interfacing Raspberry Pi with Pi Camera.
To capture image:
import picamera
from time import sleep
To capture video:
import picamera
from time import sleep
camera = picamera.PiCamera()
camera.resolution = (640, 480)
print()
#start recording using pi camera
camera.start_recording("/home/pi/demo.h264")
#wait for video to record
camera.wait_recording(20)
#stop recording
camera.stop_recording()
camera.close()
print("video recording stopped")
To Play the video:
Omxplayer demo.h264
T.Y.B.Sc. (I.T.) 2019
10
Interfacing Raspberry Pi with RFID.
sudo raspi-config
cd ~
wget http://dl.bintray.com/nfc-tools/sources/libnfc-1.7.1.tar.bz2
tar -xf libnfc-1.7.1.tar.bz2
T.Y.B.Sc. (I.T.) 2019
cd libnfc-1.7.1
./configure --prefix=/usr --sysconfdir=/etc
make
sudo make install
cd /etc
sudo mkdir nfc
sudo nano /etc/nfc/libnfc.conf
device.name = "_PN532_I2c"
device.connstring = "pn532_i2c:/dev/i2c-1"
6. Wiring
SEL SEL
0 1
H L
Connect the devices:
PN532 Raspberry
5V 5V 4
GND GND 6
SDA SDA0 3
SCL SCL0 5
If yes, it means both the module and the wiring work well.
Then type in nfc-list to check the NFC module:
T.Y.B.Sc. (I.T.) 2019
Run nfc-poll to scan the RFID tag and you can read information on the card:
sudo raspi-config
cd ~
wget http://dl.bintray.com/nfc-tools/sources/libnfc-1.7.1.tar.bz2
tar -xf libnfc-1.7.1.tar.bz2
cd libnfc-1.7.1
./configure --prefix=/usr --sysconfdir=/etc
make
sudo make install
6. Wiring
Toggle the switch to the SPI mode
SEL0 SEL1
L H
Connect the devices:
PN532 Raspberry
5V 5V
GND GND
SCK SCKL
MISO MISO
MOSI MOSI
NSS CE0
7. Run ls /dev/spidev0.* to check whether the SPI is opened or not.
If yes, it means both the module and the wiring work well.
Then type in nfc-list to check the NFC module:
/dev/spidev0.0 /dev/spidev0.1
If two devices are detected, it means the SPI is already opened.
Then type in nfc-list to check the NFC module:
device.connstring = "pn532_spi:/dev/spidev0.0:50000"
Run nfc-poll to scan the RFID tag and you can read information on the card:
Code:
import subprocess
import time
def nfc_raw():
lines=subprocess.check_output("/usr/bin/nfc-poll",
stderr=open('/dev/null','w'))
return lines
def read_nfc():
lines=nfc_raw()
return lines
try:
T.Y.B.Sc. (I.T.) 2019
while True:
myLines=read_nfc()
buffer=[]
for line in myLines.splitlines():
line_content=line.split()
if(not line_content[0] =='UID'):
pass
else:
buffer.append(line_content)
str=buffer[0]
id_str=str[2]+str[3]+str[4]+str[5]
print (id_str)
except KeyboardInterrupt:
pass
1. Raspberry Pi 3.
2. 5V 2A microUSB power supply.
3. 8GB or larger Class 10 microSD card with full-size SD adapter.
4. HDMI cable.
5. Access to a PC.
6. USB WiFi adapter (older models of Raspberry Pi) or Ethernet cable.
At this point, the HDMI cable is only to plug the Raspberry Pi into a display so you can
make sure your install worked. Some Raspberry Pi starter kits include everything you
need, but the list above covers the power, display, and something to install Windows 10
IoT Core on.
6. Select the WiFi network connection you want your Raspberry Pi to connect to, if
required. Only networks your PC connects to will be shown.
7. Click download and install.
The application will now download the necessary files from Microsoft and flash them to
your microSD card. It'll take a little while, but the dashboard will show you the progress.
T.Y.B.Sc. (I.T.) 2019
Once the image has been installed on the microSD card, it's time to eject it from your PC
and go over to the Raspberry Pi. First connect up the micro USB cable and power supply,
HDMI cable and USB WiFi adapter or Ethernet cable. Connect the HDMI cable to your
chosen display, insert the microSD card into the Raspberry Pi and power it up.