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

EP0401 - IO Devices - Write-Ups: - S.P. Chong

The document provides information on connecting and programming various input/output (IO) devices with a Raspberry Pi. It includes diagrams of the RPi GPIO pins and lists common sensors and actuators such as LEDs, switches, motors, and sensors for moisture, motion and light. Code samples are provided for controlling outputs like LEDs and reading inputs from sensors to detect moisture, motion or button presses. Applications are described for each device type.

Uploaded by

Jack Tan
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)
98 views

EP0401 - IO Devices - Write-Ups: - S.P. Chong

The document provides information on connecting and programming various input/output (IO) devices with a Raspberry Pi. It includes diagrams of the RPi GPIO pins and lists common sensors and actuators such as LEDs, switches, motors, and sensors for moisture, motion and light. Code samples are provided for controlling outputs like LEDs and reading inputs from sensors to detect moisture, motion or button presses. Applications are described for each device type.

Uploaded by

Jack Tan
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/ 54

EP0401 – IO devices – write-ups

- S.P. Chong

6/1/2020 RPi - Python - write-ups on IO devices 1


RPi 3B+ GPIO pins You will need to refer
to this diagram when
connecting IO devices
to the RPi.

6/1/2020 RPi - Python - write-ups on IO devices 2


List of useful sensors / actuators Simple
LED / RGB LED
Simple digital /
Slide switch
Actuators analogue sensors
Potentiometer (covered in Lesson 3)
Servo motor Moisture sensor
Buzzer (similar connection & code to LED)
DC motor (with driver) IR sensor 
Stepper motor  PIR sensor Programming tricks UI
Relay / solenoid / SSR Tilt switch Random no. gen. Keypad
LDR System’s date & time LCD
Wireless comm. Force sensor  Voice playback
BT module  File I/O’s
More “exotic” sensor / actuators
WiFi (built-in)
Ultrasonic ranger Authentication
SIM card module 
Temperature & humidity sensor AM2302 (covered in Lesson 4) RFID reader
Those marked with 
3-axis sensor Fingerprint reader
are less likely to be used
in projects, and will not
GPS module
be covered.

6/1/2020 RPi - Python - write-ups on IO devices 3


Servo motor
Intro
• The arm of a servo motor can be made to Sample Code
swing over 180 degree i.e. from 9 o’clock to
3 o’clock positions.
• It is to be connected as shown below: the
GND wire can be black or brown, the control
signal wire can be orange or yellow.

Connection
Applications
• Position control The duty cycles for
different arm positions
• Sorting / diverting can be obtained by
It may • Remote control trial & error.
look like
car/boat/aeroplane
6/1/2020 this. RPi - Python - write-ups on IO devices
4
DC motor Applications
Intro • Movements – turning a
wheel / a conveyor belt
• A DC motor can rotate continuously when a • Cooling fan
current passes through it. • Pumping air or water
• However, an RPi output pin does not produce
enough current to drive it directly.
• So, a BJT transistor is often used, to increase Voltage depends on
the current. motor used.
• A diode is often needed to protect the circuit.

Connection
Sample Code
For a DC motor to turn
• Please refer next page. in both directions, a
“H-bridge” is needed.

5
6/1/2020 RPi - Python - write-ups on IO devices
DC motor (cont.) Sample Code

Using PWM to
control motor speed.

6
6/1/2020 RPi - Python - write-ups on IO devices
Solenoid Applications
Intro • Locking & unlocking
• Dispensing mechanism
• When a current passes through a coil, it • Kicking action
becomes an electromagnet and the • Pinching to control liquid flow
magnetic force can pull in (or push out) a
plunger. This is how solenoid works.
• Again, an UNO output pin does not produce
enough current to drive it directly. Connection
• So, a BJT transistor is often used, to Plunger.
increase the current.

Sample Code
• Please refer next page.
7
6/1/2020 RPi - Python - write-ups on IO devices
Solenoid (cont.) Sample Code

8
6/1/2020 RPi - Python - write-ups on IO devices
WiFi

Use built-in WiFi

6/1/2020 RPi - Python - write-ups on IO devices 9


Applications
Moisture sensor
• Rain detection
Intro • Soil moisture detection
• Water level detection
• A moisture sensor behaves as a “normally open
switch”. If there is moisture, the switch will be closed.
• Connected as shown below, if it is open, the RPi will Sample Code
read a LOW. If it is closed, the RPi will read a HIGH. • Please refer next page.
• The same code can be used to
Connection read any digital input device
It may that gives either a HIGH or a
look like LOW.
this.

6/1/2020 RPi - Python - write-ups on IO devices 10


Moisture sensor (cont.)
Sample Code

6/1/2020 RPi - Python - write-ups on IO devices 11


https://lastminuteengineers.com/pir-sensor-arduino-tutorial/

PIR sensor Check this out.


Applications
Intro
• Intruder detection
• A PIR (Passive Infra Red) sensor can be used to detect • Energy saving light
motion of an animal or a human. • Automated greeting
• Powered up as shown below, if motion is detected,
the RPi will read a HIGH. If there is no motion, the RPi
will read a LOW. Sample Code

Connection • Please refer next page.


Specs: 4.5-12V
Tested to work with 3.3V.
It may
look like
this.

6/1/2020 RPi - Python - write-ups on IO devices 12


PIR sensor
(cont.)
Sample Code
Notes:
1. In the retriggerable mode (jumper at
“H”), if not motion is detected, output
will go low after a short period.
2. Once output goes low, there is a short
period (e.g. 2.5s) where motion will not
be detected.

6/1/2020 RPi - Python - write-ups on IO devices 13


Tilt Switch Applications
Intro • Tilt detection
• A tilt switch consists of 2 terminals & a metal ball. • Vandalism prevention
• The ball can short the 2 terminals, when the tilt
switch is in a certain position. Sample Code
• Connected as shown below, it can produce a HIGH at
the RPi input (when the terminals are shorted by the • Please refer next page.
ball). • The same code can be used to
read any digital input device
It may that gives either a HIGH or a
look like LOW.
this.

Connection
6/1/2020 RPi - Python - write-ups on IO devices 14
Tilt Switch (cont.)
Sample Code

6/1/2020 RPi - Python - write-ups on IO devices 15


Sample Code
LDR (Light Dependent Resistor)
• Please refer next page.
Intro
• The resistance of an LDR decreases, with increasing light • The same code can be used to
read any analog input device
intensity. Connected as shown below, if it is brighter, voltage connected to the ADC MCP3008.
at X will be higher.
• The ADC (Analogue to Digital Converter) converts this into
10-bit result (0-1023) and RPi reads this using SPI (Serial Applications
Peripheral Interface) – see next page. • Automatic lighting
Connection analogRead result = • Smoke detection
1023 * VX / 3.3V • Burglar alarm system

It may
look like
this.
Voltage division
Voltage at X, VX =
6/1/2020 3.3V * 10k / (10k + R1) RPi - Python - write-ups on IO devices 16
A -> D Conversion
LDR (cont.)

SPI

6/1/2020 RPi - Python - write-ups on IO devices 17


LDR (cont.)
Sample Code

Assuming the LDR


circuit is connected to
channel 0.
6/1/2020 RPi - Python - write-ups on IO devices 18
Ultrasonic Ranger Intro
• Ultrasound, which human can’t hear, can be used to measure distance.
• When a short pulse is produced at Trig by the RPi, the transmitter will send a pulse
train out. This will be reflected by the obstacle. From the time of flight (divided by 2!) &
the speed of ultrasound, the obstacle distance can be computed. The distance is
conveyed to the RPi at Echo, in the form of a high pulse.
• The speed of (ultrasound) sound is 343m/s. So 343m=1s, 1cm=29us, 1cm 2-way=58us.

Applications Connection
• Obstacle detection
• Height / distance measurement

Sample Code
See next page…
6/1/2020 RPi - Python - write-ups on IO devices 19
Ultrasonic Ranger
(cont.)
Sample Code

The obstacle distance


is displayed on the
monitor.

6/1/2020 RPi - Python - write-ups on IO devices 20


Temp & Humidity Sensor

Refers to Lesson 4

6/1/2020 RPi - Python - write-ups on IO devices 21


3-axis Sensor
Sample Code
Intro
See next few pages…
• This device uses both SPI & I2C (or TWI) interface.
Here, we will stick to I2C (or Inter-Integrated Circuit)
• By connecting to a RPi, movement in the X, Y, Z
directions can be detected.

Connection Applications
• Motion detection
• Fall alert
• Vandalism prevention

6/1/2020 RPi - Python - write-ups on IO devices 22


Refer to this link
3-axis Sensor (cont.) to find out more:

https://www.anstack.com/blog/2016/07/05/accelerometer-intro.html
Sample Code
We will use the adxl345 module from pimoroni.
At a terminal, type
git clone https://github.com/pimoroni/adxl345-python

This will download the folder “adxl345-python”, with the file “adxl345.py”.
Modify the print statements at the end of this file as follows:
After modification, this file can be
run to print out the acceleration in
the X, Y & Z-axes once.

6/1/2020 RPi - Python - write-ups on IO devices 23


3-axis Sensor (cont.)
Sample Code
You can also write the following program, to use the getAxes function from the adxl345 module,
to get the acceleration in the X, Y & Z-axes, once every second.

This file should be in the same folder


as the adxl345.py file.

6/1/2020 RPi - Python - write-ups on IO devices 24


Sample Run
GPS module
Intro
• A GPS module allows an
It may take a while
item’s location (longitude & to “latch-on”.
latitude) to be known.
• The module will keep sending Time, latitude,
info to an RPi connected via a longitude, date.
serial port.
Connection

Applications
See next slide on
• Various tracking sample code.
applications

6/1/2020 RPi - Python - write-ups on IO devices 25


GPS module (cont.)
Sample Code

See this website to learn to


interpret the info received.

https://www.gpsinformation.org/dale/nmea.htm

You may need to


Enable Serial Port
& reset the RPI.

$GPRMC gives the


longitude & latitude info.
6/1/2020 RPi - Python - write-ups on IO devices 26
Applications
Random number generator
• Lucky draw
Intro • Randomly pick a song /
• To encourage recycling, a person putting an empty drink voice message to play
can into a machine may or may not get a sweet, • Randomly select an LED
depending on his luck. This is when the random number to light up
generator is useful.

Sample Code
Sample run:

6/1/2020 RPi - Python - write-ups on IO devices 27


System’s date & time Applications
• Alarm clock
Intro
• Timed switching on and off of
• RPi allows the system’s date & time to something e.g. automatic plant
be accessed easily. watering or pet feeding
• If the RPi is connected to the internet, • Data logging with timestamp
update is automatic.

Sample run:

Sample Code

6/1/2020 RPi - Python - write-ups on IO devices 28


Connection
It may
Keypad also look
like this.
Intro
• A keypad can be used to enter numbers 0-9,
* and #.
• A 4x3 keypad consists of 12 switches.
• However, a scanning algorithm can be used
and treats the 12 switches as 4 row signals +
3 column signals.
• So, if you press ‘8’, 3rd row is connected to 2nd
column etc.
Applications
Sample Code
• Entering password
• Please refer next page. • Configuring system
• Making choices from a menu / selection
29
6/1/2020 RPi - Python - write-ups on IO devices
Keypad (cont.)

Sample code
for hard keypad, change to:
ROW=[13,21,20,26]
COL=[19,6,16]

Press each key, and


you will see this on
the screen.

30
6/1/2020 RPi - Python - write-ups on IO devices
It may
LCD (TWI) also look
like this.
Intro
• An LCD can be used to prompt for password, or display
info & instruction etc.
• We will use the 4-pin version below, to reduce the
number of RPi pins needed for connection.
• FYI, this is using TWI (or Two Wire Interface – not very Applications
easy to understand).
• Info / instruction
• Some setup steps are required – see next few pages.
display
• Password prompt
Sample Code Connection

• Please refer next few pages.

31
6/1/2020 RPi - Python - write-ups on IO devices
LCD (TWI) (cont.)
Setup

Enable the I2C (TWI)


interface by first selecting
the following menu item.

Then, select Enable


and click OK. After
this, reset the RPi.

32
6/1/2020 RPi - Python - write-ups on IO devices
LCD (TWI) (cont.)
Setup (cont.)
You can find out the I2C
address of the connected
LCD by using this command.
The i2c-tools can be installed
this way, if necessary.

Install smbus, which


allows python code to
access i2c bus.

33
6/1/2020 RPi - Python - write-ups on IO devices
http://www.circuitbasics.com/raspberry-pi-i2c-lcd-set-up-and-programming/
LCD (TWI) (cont.)
Setup (cont.)
Access this webpage...

copy the code here and save it


as I2C_LCD_driver.py

34
6/1/2020 RPi - Python - write-ups on IO devices
LCD (TWI) (cont.) Sample code
Setup (cont.)

Change the bus to 1. The above code will


prompt for password.
And the address to what you
have seen earlier – i2cdetect.

35
6/1/2020 RPi - Python - write-ups on IO devices
Connection
Voice playback module
Intro
• To play back voice / music, place the mp3 or wav files
in a thumb-drive and insert this into a USB port, or
place them in the SD card (with the RPi OS).

Sample Code
The code below uses omxplayer to play back a Switch to the correct Connect an earpiece or active
audio output. speaker to the audio output.
media file, including video, voice / music.

Applications
• Voice prompt / instruction
/ alert
Text can be converted to mp3 file at www.fromtexttospeech.com • Attract attention
6/1/2020 RPi - Python - write-ups on IO devices • Entertainment 36
Intro
File I/O’s • The RPi OS (Operating System) is on an SD card, which can be
used to store other data files. This sample code shows how a file
can be opened for writing, appending & reading.

Applications
Sample Code • Data logging

This diagram explains


the try-except method:

6/1/2020 RPi - Python - write-ups on IO devices 37


File I/O’s (cont.)
Sample Run
test1 does not exist for reading,
but the try-except method
prevents the execution from being
thrown out.

test1 does not exist, so create one


for writing. After this, it should
contain data1.

test1 exists, so open it for


appending. After this, it should
contain data1data2.

Indeed…

test1 exists, open it for writing. This


will purge old content, however.

6/1/2020 RPi - Python - write-ups on IO devices After this, it should contain data3. 38
File I/O’s (cont.) Assuming a thumb drive is inserted
and the test1 file is moved into it.
How about thumb drive?

GRAY 4G is how the thumb drive was


named, during formatting.

The file in the thumb drive can be


referred to as /media/pi/GRAY 4G/test1,
as follows:

6/1/2020 RPi - Python - write-ups on IO devices 39


RGB LED
Sample Code
Intro
• Please refer next page.
• An RGB LED consists of 3 LED’s, one red, one
green and one blue. As you may already
know, these are the primary colours. Applications
• By connecting them to any 3 of RPi’s GPIO
pins and producing different duty cycles / • Mood lighting
PWM waveforms at these pins, many colours • Event alert / indication
can be produced.

Connection

6/1/2020 RPi - Python - write-ups on IO devices 40


RGB LED (cont.) Sample Code

6/1/2020 RPi - Python - write-ups on IO devices 41


Slide Intro
switch • A slide switch consists of 3 terminals & a ‘slider’.
• When the slider is on the left, it will short the left & centre terminals.
• When the slider is on the right, it will short the centre & right terminals.

Applications
• Selection
• Control input
Sample Code
Connection

6/1/2020 RPi - Python - write-ups on IO devices 42


Potentiometer

Refers to Lesson 3

6/1/2020 RPi - Python - write-ups on IO devices 43


Buzzer

Similar connection & code to LED

Refers to Lesson 3

6/1/2020 RPi - Python - write-ups on IO devices 44


Intro
RFID reader • RFID (or Radio Frequency Identification) uses
electromagnetic fields to automatically identify and track
Applications “tags” attached to objects.
• When a tag is placed near a “reader”, the UID (Unique ID)
• Authentication e.g.
of the tag can be read by a Raspberry Pi.
door access,
• A library (collection of files) for the RFID reader has to be
attendance marking,
used with the sample codes on the next few pages.
cashless payment

Connection Sample Code


RFID reader.
CS

See next page…

RFID tags.

6/1/2020 RPi - Python - write-ups on IO devices 45


RFID reader (cont.)
The database is in the form
of a txt file, listing the
Sample Code Unique ID’s of the
registered RFID tags on
Clearing Database.py – this should be run at the beginning. separate lines.

CS

6/1/2020 RPi - Python - write-ups on IO devices 46


RFID reader (cont.)
Sample Code
Register Cards.py – to register authorized cards.

A new card presented to the


reader will result in a new Unique
CS

ID entry in the authlist.txt file.

6/1/2020 RPi - Python - write-ups on IO devices 47


RFID reader (cont.)

Sample Code
Identify Cards.py – to check card against database.

A card presented to the reader will


CS

have its Unique ID checked against


entries in the authlist.txt file.

6/1/2020 RPi - Python - write-ups on IO devices 48


Fingerprint reader This is a distributor for the reader.

http://www.diymalls.com/Optical-Fingerprint-Reader-Sensor
Intro
• Adafruit, an electronic parts manufacturer & seller, has a very good write-up on the reader:
https://learn.adafruit.com/adafruit-optical-fingerprint-sensor
• You can also refer to the following:
https://tutorials-raspberrypi.com/how-to-use-raspberry-pi-fingerprint-sensor-authentication/
• The library installation & connections are not simple – refer next pages.

It looks Applications
like this.
• Authentication e.g.
door access,
attendance marking,
cash-less payment
6/1/2020 RPi - Python - write-ups on IO devices 49
Fingerprint reader (cont.)

Connection
• You need to get a 6-pin FTDI (USB to UART) adaptor cable, as
shown on the right.
• Connect this to the fingerprint reader as shown below.
• Then plug the FTDI cable to one of the Raspberry Pi’s USB ports.

6/1/2020 RPi - Python - write-ups on IO devices 50


Fingerprint reader (cont.)
The steps shown below will
Library installation install these files in this location.

At a Raspberry Pi terminal, issue the following commands to install the library:


• sudo bash
-- to execute the other commands as root
• wget -O - http://apt.pm-codeworks.de/pm-codeworks.de.gpg | apt-key add -
• wget http://apt.pm-codeworks.de/pm-codeworks.list -P /etc/apt/sources.list.d/
-- to add the necessary package sources
• apt-get update
• apt-get install python-fingerprint --yes
-- to update the available packages and to install the Python library
• Exit
• -- to return to the normal shell

6/1/2020 RPi - Python - write-ups on IO devices 51


Fingerprint reader (cont.) Warning: Only Python2 code is available.

Testing the sample codes


• Change directory to /usr/… /examples, as shown below.
• Then type python2 ./example_index.py to display the fingerprint templates:

This shows that no fingerprint


has been captured so far.

6/1/2020 RPi - Python - write-ups on IO devices 52


Fingerprint reader (cont.)
Testing the sample codes
• Now type python2 ./example_enroll.py to add a fingerprint template:

You need to place your finger


on the reader, remove it, and
then place it back again.

Now position #0 of the


reader’s memory is occupied
by your fingerprint template.
6/1/2020 RPi - Python - write-ups on IO devices 53
Fingerprint reader (cont.)
Testing the sample codes
• Type python2 ./example_search.py to search through the fingerprint templates:

If there is a match between the finger


The higher the accuracy score, on the reader, and the stored
the better the match. templates, this is the result.

If there is no match, this is the result.

6/1/2020 RPi - Python - write-ups on IO devices 54

You might also like