IoT Programming on the Raspberry Pi

DamienMagoni 587 views 81 slides Jan 25, 2020
Slide 1
Slide 1 of 81
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81

About This Presentation

A 5-part introductory course on IoT and programming a Raspberry Pi model B version 3 for reading a DHT11 sensor.


Slide Content

IoTProgramming on the
Raspberry Pi
Damien Magoni–Universityof Bordeaux
& Philip Perry–UniversityCollegeDublin
2017/09/28
Version 4

Attribution
•The materialcontainedinsideisintendedfor teaching.
•This document islicensedunderthe CC BY-NC-SA license.
•All figures and textborrowedfromexternalsources retainthe rights
of theirrespective owners.
2

Table of Contents
1.IoTdefinition, factsand perspectives
•Sensors
•Edgenodes
2.RaspberryPi operation
3.RaspberryPi interfaces
•GPIO ports
4.DHT11 operation
5.Retrievingdata fromthe DHT11 to the RaspberryPi in Python
3

Internet of Things
Part 1

What is IoT?
•Internet of Things (IoT) is the networked connection of “things”
•Things are not humans –they are machines
•Usually sensors at the edge of the network measure real-world values
•These values may be shared with other edge nodes or, more often,
passed up through the network to some “intelligent” node
•This intelligent node may pass commands back down to the edges
5

6

Importance of IoT
•Health care -cost reduction and service quality improvement
•Energy –more efficient usage (management) and cost reduction
•City infrastructure –efficiency, costs, quality of life
•Security –automated, accessible from anywhere
•Industry –automated factories
•Agriculture –livestock and crop monitoring
7

8

IoT Perspectives –end users
•End users may only see a “service” that tells them something that
they want to know
•Is my home secure?
•Is the basement flooded?
•Is there parking available at work now? Where?
•What is the traffic like? What route should I take?
•Smart cities and infrastructure
•Monitoring electricity distribution system
•Heating control in buildings
•Emergency services management
9

IoT Perspectives –equipment providers
•Hardware manufacturers may provide sensors, actuators, low power
edge nodes, networking equipment, servers
•Edge nodes can be simple or complex
•Raspberry Pi –multi-core processor with dedicated Input/Output(I/O) pins
•Arduino –microcontroller with dedicated peripherals
•Dedicated chips that simply sample data and pass them up the network
•The edge network is often wireless –WiFi, Bluetooth etc
•As we move closer to the core of the network, routers need to carry
more traffic –along with regular Internet traffic
10

IoT Perspectives -service providers
•Services may be deployed locally or in the cloud
•Smart watch sending heartrate to a smart phone. Timestamped and
geo-tagged data sent to cloud for well-being monitoring.
•Health monitoring for diabetes or heart conditions
•Smart cities monitoring services
•Or maybe a platform that you can build your own service –IBM
Watson or Microsoft Azure
•Some services provide the edge nodes and the central intelligence
11

IoT Growth
12

IoT Market Size
13

What is a Sensor?
•A device that measures a physical quantity
•The values measured by a sensor may be
•Analogue –a continuous variable such as temperature
•Binary –yes/no, on/off, high/low, wet/dry, hot/cold
•Quantised –usually a version of a continuous variable with a finite number of
discrete possible values, eg0.0, 0.1, 0.2, 0.3 etc, or Cold/Warm/Hot
•Digital –a quantised value that is captured at some point in time (depending
on the sampling frequency)
•Internet can only send/receive digital data
14

Types of Sensors
•Voltage, current, phase, power
•Temperature, humidity,
atmospheric pressure, wind
speed
•Heart rate, respiratory rate,
blood pressure, body
temperature
•Volume of traffic (cars), speed,
parking spaces
15

Whatisan EdgeNode?
•The edge node is the last node that can communicate using the
Internet Protocol (IP)
•It is connected to a network by using a layer 2 technology such as
•Ethernet (wired, needs a switch)
•WiFi(wireless, needs an access point)
•Bluetooth
•Cellular (needs a SIM card slot)
16

Types of Edge Nodes
•Microcontroller-based (e.g.
Arduino, Galileo, etc.)
•Simple processor on a board with
I/O pins
•Single thread
•Microprocessor-based (e.g. Pi,
Odroid, Beagle, etc.)
•Often based on low power
consumption processors (eg. ARM)
•Linux OS
•Multi-threading introduces non-
real-time OS issues
17

Central Processing Unit (CPU)
•A CPU is the electronic circuitry within a computer that carries out
the instructions of a computer program by performing the basic
arithmetic, logical, control and input/output (I/O) operations
specified by the instructions
•The term CPU refers to a processor (more specifically to its processing
unit (ALU) and control unit), distinguishing it from external
components such as main memory and I/O circuitry
•Most modern CPUs are microprocessors, meaning they are contained
on a single integrated circuit chip
18

Microprocessors
•A microprocessoris a computer processor which incorporates the
functions of a computer's CPU on a single integrated circuit (IC)
•The microprocessor is a multipurpose, clock driven, register based,
digital IC which accepts binary data as input, processes it according to
instructions stored in its memory, and provides results as output
•They are used in personal computers or other general purpose
applications consisting of various discrete chips (CPU, memory, I/O
bridge, DSP, etc.)
19

Microcontrollers
•A microcontrolleris a small computer on a single integrated circuit
•A microcontroller contains one or more CPUsalong with memory and
programmable I/O peripherals
•Program (non-volatile) memory and some RAM is often included on chip
•Designed for embeddedapplications
•Must provide real-time (predictable) response to events in the embedded
system they are controlling
•When certain events occur, an interrupt system can signal the processor to
suspend processing the current instruction sequence and to begin an
interrupt service routine
20

Single BoardMicrocontroller
•A single-board microcontroller is a microcontroller built onto a single
printed circuit board (e.g., Arduino)
•This board provides all of the circuitry necessary for a useful control task
•Microprocessor, I/O circuits, clock generator, RAM, stored program memory, etc.
•A single-board microcontroller differs from a single-board computer (e.g.,
Raspberry Pi) in that it lacks the general-purpose user interface and mass
storage interfaces that a more general-purpose computer would have
•Compared to a microprocessor development board, a microcontroller
board would emphasize digital and analog control interconnections to
some controlled system, whereas a development board might by have only
a few digital or analog input/output devices
21

System-on-Chip (SoC)
•A SoCis an integrated circuit that integrates all components of a
computer or other electronic systems (e.g. Broadcom 283x)
•It integrates a microcontroller (or microprocessor) with advanced
peripherals like graphics processing unit (GPU), Wi-Fi module, or
coprocessor
•It may contain digital, analog, mixed-signal, and often radio-frequency
functions—all on a single substrate
•A typical application is in the area of embedded systems
22

RaspberryPi Operation
Part 2

Raspberry Pi Model B Version 3
•BroadcomBCM2837 SoC-
Architecture ARMv8-A (64/32-bit)
•Quad core CPU ARM Cortex-A53 64-
bit running at 1.2GHz
•1GB RAM (900MHz) + Micro SDHC
card slot (up to 32GB)
•Built in 10/100 Mbps Ethernet, 4x USB
ports, WiFi802.11n and Bluetooth 4.1
•General Purpose Input/Output(GPIO)
pins, serial UART, I2C bus, SPI bus
•Power rating 300 mA (1.5 W) average
when idle, 1.34 A (6.7 W) maximum
24

Poweringthe Pi
•Many problems with the Raspberry Pi can be traced to an inadequate
power supply
•Model A draws up to 500 mA, RPi3 can draw up to 1.3 A
•Not all USB power adapters are designed to offer this much power
•The USB standard states that devices should draw no more than 500 mA
•with even that level of power available only to the device following a process called
negotiation
•The Pi doesn’t negotiate for power, which can cause problems when trying
to power the Pi from a PC’s USB port
•While lower-power models such as the Pi Zero may work, higher-power
models like the Pi 2 and 3 should never be powered from a PC’s USB port
25

Checkingthe Power
•The powerLEDof the Pi acts as an in-built voltage test
•If the power LED is flashing or unlit, the power supply is providing less
than 4.65 V (below the 5 V USB standard) and should be replaced
•To check the power your Pi is receiving, use a USB power meter (a
form of multimeter) designed to sit in-between the USB power supply
and the Pi and measure the voltage and amperage
•The voltage reading on the USB power meter should be between 4.65
V and 5.2 V
26

RaspberryPi Operating System
•Raspbianisthe official OS, basedon the Debian Linux distribution
•Alsoavailable: Ubuntu, Windows 10 IoT, OSMC, etc.
•Chooseand downloadfromhere
www.raspberrypi.org/downloads
•Unzipthe file and makea block copy on a FAT32 SD card
sudoddbs=4m if=/home/user/2017-09-07-raspbian-stretch.imgof=/dev/sd[x]
(or /dev/mmcblk[x])
27

RPiBoot Process
•No BIOS or battery backed
memory by default
•Uses specific, efficient but closed
source bootloadersdeveloped
by Broadcom
•Bootloadersand configuration
files are located in the /boot
directory of the RPiimage
28

Boot Diagnostics
•Common cause for a Pi to fail to boot is a problem with the SD card
•The Pi relies on files stored on the SD card for everything
•If the Pi can’t talk to the card, it won’t display anything on the screen or
show any signs of life at all
•If the Pi’s PWR light glows when you connect the power supply but nothing
else happens and the ACT (activity) light isn’t flickering to indicate data
access, there is an SD card problem
•Ensure that the card works when connected to a PC and that it shows the
partitions and files expected of a well-flashed card
•If the card works on a PC but not on the Pi, it may be a compatibility
problem
29

User Accounts
•By default, Raspbianis configured with two user accounts
•pi: normal user account (password raspberry)
•root: superuser/ administrator account with additional permissions
•Raspbianby default is configured so that the root account can't be
logged into using a password
•Use sudocommand instead
30

RPiConfiguration
•The primary configuration file for the RPiis /boot/config.txt
•Configure Raspbianwith
sudoraspi-config
•Changes made using the raspi-configtool are reflected in this file
•You can manually edit this file to enable/disable bus hardware, overclock
the processors, etc.
sudonano/boot/config.txt
•Another file/boot/cmdline.txtis for passing arguments (e.g., tty
params, rootfstype, etc.) to the Linux kernel on boot
sudonano/boot/cmdline.txt
31

UsefulRaspbianLinux Commands
•Start the GUI desktop
startx
•Update the system
sudoapt-getupdate
sudoapt-getupgrade
sudoapt-getinstall<package-name>
•Shutdownthe system
sudoshutdown–h now
32

Configure the WiredNetwork
•Check withifconfig
•Disableand re-enablenetwork
interface
•sudoifdowneth0
•sudoifupeth0
•Configure a connectionby
editing/etc/dhcpcd.conf
•Addlines
interface eth0
static ip_address=192.168.0.13
static routers=192.168.0.254
static domain_name_servers=8.8.8.8
8.8.4.4
static domain_search=local
•Restart the network stack
sudoservice networking restart
33

Configure the Wireless Network
•scan for nearby wireless access
points
sudoiwlistscan | less
•Check network interface
iwconfigwlan0
•Use wpasupplicantto connect
the Pi to almost any wireless
network (WPA, WPA2)
•Edit the configuration file
sudonano
/etc/wpa_supplicant/wpa_supplicant.conf
•Add lines
network={
[Tab] ssid="Your_SSID"
[Tab] key_mgmt=WPA-PSK
[Tab] psk="Your_WPA_Key"
}
•Restart interface
ifupwlan0
34

Connectingto the RPiusingthe Network
•Show IP address
ipaddr
•Connectusinga CLI withSSH
[email protected]
•Connectusinga GUI withVNC
sudoapt-getinstalltightvncserver
•When the server starts, it will tell you which virtual desktop has
been started. This will normally be session 1
New 'X' desktop is raspberrypi:1
•On the client, indicate the remote host as
192.168.0.111:1
35

ZeroconfNetworking
•Avahiisa free zero-configuration
networking (zeroconf)
implementation, includinga system
for multicast DNS/DNS-SD service
discovery
•Avahienables programs to publish
and discover services and hosts
running on a local network
•A user can plug a computer into a
network and have Avahi
automatically advertise the
network services running on the
machine which could enable access
to files and printers
•On the RPi
sudoapt-getinstallavahi-daemon
•On the remotemachine
[email protected]
36

Bluetooth Connection
•Switch your Bluetooth device onand activate pairingmode
•Typically involves holding down a button or key, see device’s documentation
•With the device in pairing mode, click the Bluetooth iconon the
Raspbiantaskbar (near the clock at the right edge of the screen)
•Click on AddDeviceto launch the Add New Device menu
•Find your chosen device in the list, and then click Pair
•The Pi will launch the pairing procedure (differs from device to
device), follow onscreen instructions to pair the two devices together
37

RaspberryPi Interfaces
Part 3

RaspberryPi GPIO Ports
•GPIO stands for General Purpose Input Output
•It is a term used to refer to ports that can be used either as inputs or
outputs
•The GPIO pins on the Raspberry Pi are connected directly to the GPIO
ports on the processor
•The processor runs at 3.3V and as such the GPIO ports are designed
for 3.3V
•The GPIO ports do not include any built-in protection!!
•Giving an input that is above 3.3V, or drawing too much current from
an output, can permanently damage the Raspberry Pi!!
39

RaspberryPi 3 Pinout
40

+5V from the Raspberry Pi GPIO
•The 5V connection on the GPIO connector is a fixed 5V power supply
that can be used to power a low-power circuit from the Raspberry Pi
•It is possible to connect an external 5V supply to that pin and use that
to power the Raspberry Pi
•The amount of current that can be taken from this supply is limited
but it could be used to power low-power electronic circuits
•Do not shorten accidentally one of those 5V pins 2 and 4 with any
other GPIO pins or you will damage the SoC!!
41

Default GPIO Pins
•The GPIO port provides at least eight pins for general-purpose use by
default: Pin 7, Pin 11, Pin 12, Pin 13, Pin 15, Pin 16, Pin 18, and Pin 22
•These pins can be toggled between three states: high, where they are
providing a positive voltage of 3.3 V; low, where they are equal to ground
or 0 V; and input
•The two outputs equate to the 1 and 0 of binary logic and can be used to
turn other components on or off
•The GPIO port has pins dedicated to particular buses
•Pi’s internal logic operates at 3.3 V, in contrast to many microcontroller
devices (e.g., Arduino), which typically operate at 5 V!!
•Devices designed for the Arduinomay not work with the Pi unless a level
translator or optical isolator is used between the two
42

Universal Asynchronous Receiver/Transmitter
(UART) Serial Bus
•UART serial bus provides a simple two-wire serial interface
•When a serial port is configured in the cmdline.txt file, this serial bus is
used as the port for the messages
•Connecting the Pi’s UART serial bus to a device capable of displaying the data
reveals messages from the Linux kernel
•The UART serial bus can be accessed on Pins 8 and 10, with Pin 8
carrying the transmit signal and Pin 10 carrying the receive signal
(speed is set in cmdline.txtat 115,200 bps)
43

Inter-Integrated Circuit (I2C) Bus
•I2C bus is designed to provide communications between multiple
integrated circuits (ICs)
•In the Pi, this bus connects to the Broadcom BCM2835 SoCprocessor
•These pins are connected to pull-up resistors located on the Pi, meaning no external
resistors are required to access the I2C functionality
•The I2C bus can be accessed on Pins 3 and 5, with Pin 3 providing the Serial
Data Line (SDA) signal and Pin 5 providing the Serial Clock Line (SCL) signal
•The I2C bus available on these pins is actually only one of two provided by
the BCM2835 chip (bus 1 on RPi3)
•The second I2C bus is reserved for use by the Pi Camera Module and Touchscreen
Display
44

Serial Peripheral Interface (SPI) Bus
•SPI is a synchronous serial bus that offers improved performance compared
with I2C
•SPI is a four-wire bus with multiple Chip Select lines, which allow it to
communicate with more than one target device
•The Pi’s SPI bus is available on Pins 19, 21, and 23, with a pair of Chip Select
lines on Pin 24 and Pin 26
•Pin 19 provides the SPI Master Output, Slave Input (MOSI) signal
•Pin 21 provides the SPI Master Input, Slave Output (MISO) signal
•Pin 23 provides the Serial Clock (SLCK) used to synchronisecommunication
•Pins 24 and 26 provide the Chip Select signals for up to two independent
slave devices
45

1-Wire
•The 1-Wire interface is another alternative to I2C and SPI, offering
connectivity to and communication with sensors and other external
hardware
•Typically, 1-Wire is used to connect simple sensors—such as devices
for reading the temperature or humidity of the environment—to the
Raspberry Pi, and is rarely used by add-on boards
46

Add-OnHardware
•100s of compatible add-on devices which connect through the
multifunction GPIO header
•Add-on boards for RPisare called Hardware Attached on Top (HAT) and
should follow the HAT standard to ensure compatibility
•The standard covers both the physical and electrical design of the add-on
board
•The board must attach to the 40-pin GPIO header and include mounting holes that
line up with those on the Pi Model B+ and newer. It must also be rectangular,
measuring 65 mm by 56 mm
•EEPROM module on the board which contains information about how the board
works, how the Pi’s GPIO pins are used, and a device tree for setting the board up
within the operating system
47

SenseHAT
•Multifunction I/O board designed
for use in the AstroPi programme
(orbiting the Earth as part of a
science bundle sent up to the ISS)
•Onboard sensors provide board’s
orientation and position via a
gyroscope, accelerometer,
magnetometer, ambient air
pressure, temperature, and
humidity levels
•Onboard 8x8 matrix of LEDs
provides an output, and interaction
is possible through the use of the
Sense HAT’s five-way joystick
48

Pi Camera Module v2
•Connect to the Camera Serial
Interface (CSI)
•Measures 25 mm on its longest
edge and weighs 3 g
•8Mpx sensor, fixed-focus lens
•Full HD video capture, 30 fps
•NoIRversion without IP filter
(needs external IR LEDs)
•H.264 hardware acceleration
49

Usingthe Camera
•Install the frame buffer image viewer
sudoapt-getinstallfbi
•View images using the tool
fbi-a imagename.jpg
•Still image capture with raspistillas JPEG (-efor other formats)
•raspistill-o testcapture.jpg
•Videocapture (size in px, duration in ms) withraspividas H.264
raspivid –t 60000 -w 1280 -h 720 -o hdvideo.h264
50

Digital Humidity& Temperature
Sensor/Module
Part 4

DHT11 Temperature and Humidity Sensor
•Measurehumidityand temperatureof the surroundingenvironment
•Humiditymeasurementrange : 20% ~95%
•Humiditymeasurementerror: ±5%
•Temperaturemeasurementrange : 0℃~50℃
•Temperaturemeasurementerror: ±2 ℃
•Operating voltage : 3.3 V~5 V
•Digital output form
•PCB Dimension: 32 mm x 14 mm
52

DHT11 SensorPinout
•Left-to-right
•Pin 1: VCC
•Pin 2: DATA
•Pin 3: null
•Pin 4: GND
53

Power and Interconnection
•DHT11’s power supply is 3 to
5.5V DC
•When power is supplied to the
sensor, do not send any
instruction to the sensor in
within 1second in order to pass
the unstable status
•MCU = µcontroller unit
54

DHT11 Module Pinout
•Sensorsolderedon PCB
•Left-to-right
•Pin 1: VCC (V)
•Pin 2: DATA (S)
•Pin 3: GND (G)
55

JumperWires
•DupontCable
•10cm length
•2.54mm pin width
•1 pin female to female for
arduino/raspberry pi
56

Communication Process
•Serial Interface (Single-Wire Two-Way)
•Single-bus data format is used for communication and
synchronization between MCU and DHT11 sensor
•One communication process is about 4ms
•Data consists of decimal and integral parts
•A complete data transmission is 40bit, and the sensor sends higher
data bit first
•The sensor can be queried once per second maxi
57

Data Format and Checksum
•The data is transmitted in this format: 8bit integral RH data + 8bit
decimal RH data + 8bit integral T data + 8bit decimal T data + 8bit
check sum
•If the data transmission is correct, the check sum should be equal to
the lower8bit of the result of (8bit integral RH data + 8bit decimal RH
data + 8bit integral T data + 8bit decimal T data)
58

OverallCommunication Process
•When MCU (black) sends a start signal, DHT11 (green) changes from the
low-power-consumption mode to the running-mode, waiting for MCU
completing the start signal
•Once it is completed, DHT11 sends a response signal of 40-bit data to MCU
•Without the start signal from MCU, DHT11 will not reply
•Once data is collected, DHT11 will change to the low-power-consumption
mode until it receives a start signal from MCU again
59

MCU Sends out Start Signal to DHT
•The default status of the DATA pin is high-voltage level
•When the communication between MCU (black) and DHT11 (green) starts,
MCU will pull down the DATA pin for 18ms, this is called Start Signal, to
ensure DHT11 has detected the signal
•Then MCU will pull up DATA pin for 20-40µs to wait for DHT11’s response
60

DHT ResponseSignal to MCU
•Once the DHT detects the start signal, it will send out a low-voltage
level response signal, which lasts 80µs
•Then the DHT sets the voltage level from low to high and keeps it for
80µs, and prepares for data transmission
61

Data «0» Indication
•When DHT is sending data to MCU, every bit of data begins with the
50µs low-voltage-level and the length of the following high-voltage-
level signal determines whether data bit is "0" or "1“
•Data bit “0” has 26-28µs high-voltage length
62

Data «1» Indication
•Data bit “1” has 70µs high-voltage length
•When the last bit data is transmitted, DHT11 pulls down the voltage level and
keeps it for 50µs
•Then the voltage will be pulled up by the resistor to set it back to the free status
•If the response signal from DHT is always at high-voltage-level, the DHT is not
responding properly, check the connection
63

RetrievingData fromthe DHT11
to the RaspberryPi
Part 5

The Design Process in a Nutshell
•Designing a circuit is a multi-step process
1.Start with the idea
2.Research the available components,
3.Design it into a circuit showing how components will be connected
4.Prototype the circuit by making a temporary circuit before creating the final
finished one
•The final circuit could be built on an off-the-shelf board such as
stripboardor made into a complete printed circuit board, depending
on your budget and the complexity of the circuit
65

An IterativeProcess
•Each of these stages can be repeated as necessary until you come to
the final design
•As you move through the stages, the potential cost increases both in
terms of money and the time
•The earlier you identify any potential problems the less it will cost
•Don’t be afraid to go back to the start rather than trying to continue
with a design that isn’t working
66

ElectronicEquipment
•An electronic breadboardprovides a grid of holes spaced at 2.54 mm
intervals into which components can be inserted and removed
•Below each grid is a series of electrical contacts which allow
components in the same row to be connected together without wires
•Jumper wires are used to connect one row to another, or to connect
the breadboard to the Pi’s GPIO port (use solid-core wire rather than
stranded-core wire)
•Stripboardis a single-use breadboard where components need to be
soldered into place making a permanent electronic circuit
67

Resistors
•A resistoris a passive two-
terminal electrical component
that implements electrical
resistance as a circuit element
•Resistors are measured in ohms,
written as the symbol Ω
•Resistance value in ohms is
calculated from the color bands
that adorn the resistor’s surface
68

RaspberryPi 2/3 40-pin I/Os
•Hardware interfaces for the Raspberry Pi 3 are exposed through the
40-pin header J8 on the board
•24x -GPIO pins
•1x -Serial UARTs (RPi3 only includes mini UART) + 2x -SPI bus + 1x -I2C bus
•2x -5V power pins + 2x -3.3V power pins + 8x -Ground pins
69

Connections with GPIOs on RPi3
RaspberryPi DHT11 Module
3.3v P1 P1 VCC (V)
GND P6 P3 GND (G)
GPIO4 (GPCLK0)P7 P2 DATA (S)
70

RPi.GPIOPython Library
•This package provides a python class to control the GPIO pins on a RPi
•This module is unsuitable for real-time or timing critical applications
•It can not be predicted when Python will be busy garbage collecting
•It also runs under the Linux kernel which is not suitable for real time applications as it is
multitasking O/S and another process may be given priority over the CPU, causing jitter
in your program
•For true real-time performance and predictability, use a µcontroller (e.g., Arduino)
https://pypi.python.org/pypi/RPi.GPIO
•The package’s documentation is here
https://sourceforge.net/p/raspberry -gpio-python/wiki/Examples /
71

RPIO Python Library
•RPIO.py extends RPi.GPIOand uses the BCM GPIO numbering scheme by
default
•https://pythonhosted.org/RPIO /
•GPIO interruptswithdebouncing
•Interrupts are used to receive notifications from the kernel when GPIO state changes
occur
•If debounce_timeout_msis set, interrupt callbacks will not be started until the
specified milliseconds have passed since the last interrupt
•Minimized cpuconsumption, fast notification times, ability to trigger on specific edge
transitions (rising, falling or both)
•TCP socket interrupts
•GPIO input & output
•Hardware PWM
72

Initialisation and Data CollectingCode
import RPi.GPIOas GPIO
import time
defbin2dec(string_num):
return str(int(string_num, 2))
data = []
# BCM numberingsystem
GPIO.setmode(GPIO.BCM)
GPIO.setup(4,GPIO.OUT)
GPIO.output(4,GPIO.HIGH)
time.sleep(0.025) #25ms
# 20ms startsignal
GPIO.output(4,GPIO.LOW)
time.sleep(0.02)
# set input pin to high level
GPIO.setup(4, GPIO.IN,
pull_up_down=GPIO.PUD_UP)
# polling DHT 500x
for i in range(0,500):
# readbinarydata fromDHT
data.append(GPIO.input(4))
# variables initialisation
count = 0
bit_count= 0
HumidityBits= ""
TemperatureBits = ""
crc= ""
73

Reading the Values fromthe Data
try:
..# skip all first 1’s (DHT response)
while data[count] == 1:
....count = count + 1
# read first 32 bits
for iin range(0, 32):
bit_count= 0
# skip 0’s
while data[count] == 0:
......count = count + 1
....# read 1’s
while data[count] == 1:
......bit_count= bit_count+ 1
count = count + 1
if bit_count>3: #if 1’s length is>3(70µs)
if i>=0 and i<8: #read integral H part
........HumidityBits= HumidityBits+ "1"
if i>=16 and i<24: #read integral T part
TemperatureBits = TemperatureBits + "1"
else: #if 1’s length is<4(27µs)
if i>=0 and i<8:
HumidityBits= HumidityBits+ "0"
if i>=16 and i<24:
TemperatureBits = TemperatureBits + "0“
except:
print "ERR_DATA_READ"
exit(0)
74

CheckingCRC and Printing Results
# read last 8 bits for the CRC
try:
..for iin range(0, 8):
....bit_count= 0
while data[count] == 0 :
......count = count + 1
while data[count] == 1:
bit_count= bit_count+ 1
count = count + 1
if bit_count> 3:
crc= crc+ "1"
else:
crc= crc+ "0"
except:
print "ERR_CRC_READ"
exit(0)
# convertbinarystrings to decimal
Humidity= bin2dec(HumidityBits)
Temperature= bin2dec(TemperatureBits)
# check CRC and print
if (int(Humidity) + int(Temperature) –
int(bin2dec(crc)) == 0):
print"Humidity:"+ Humidity+"%"
print"Temperature:"+ Temperature+"C"
else:
print"ERR_CRC_CALC"
exit(0)
75

Comments
•Reading 500 samplesisarbitrary
•Reading up to three1’s for defining
a 0 and more for defininga 1 is
arbitrary
•Yourmileagemayvary-> seepost on
the right
•Printthe data[ ] arrayto seethe
signals
•Shouldweskip the first 0’s?
•The CRC computation iswrong
•Why? Correct it
•Use interruptions insteadof polling
•“I discovered the following:
•-a "0" data/crcbit is a row of 7-8
consecutive '1' samples
•-a "1" data/crcbit is a row of 21-22
consecutive '1' samples
•I changed the trigger to 13
consecutive samples : below, it's a
0 and above, it's a 1
•Obviously, I need far more samples
(avg1050-1150) so I take 1300, just
to make sure”
76

References
•Original source code
•Providesalso(muchbetter) C code (withcorrect checksum )
http://www.uugear.com/portfolio/dht11 -humidity-
temperature-sensor-module/
•Advanced code for the DHT22
•Uses anotherlibrary(pigpio) withcallbacks
https://www.raspberrypi.org/forums/viewtopic.php?p=51557
5#p515575
77

UsingAdaFruitAPI
import Adafruit_DHT
sensor= 11
pin = 27
whileTrue:
humidity, temperature= Adafruit_DHT.read_retry (sensor, pin)
# GPIO27 (BCM notation)
print("Humidity={}%; Temperature={}C".format(humidity, temperature))
•Adafruittutorial
https://learn.adafruit.com/dht -humidity-sensing-on-raspberry-pi-with-gdocs-
logging/wiring
•DaskalTutorial
http://invent.module143.com/daskal_tutorial/raspberry -pi-3-gpio-dht11-
digital-temperature-humidity-sensor/
78

WiringPiC Library
•WiringPiis a PIN based GPIO access library written in C for the
BCM2835 used in the Raspberry Pi
•Released under the GNU LGPLv3 license
•Usable from C, C++ and RTB (BASIC), the documentation is here
http://wiringpi.com/
•The C libraryishere
https://git.drogon.net/
•Python wrappersare here
https://github.com/WiringPi/WiringPi -Python
79

Running a Program as a Service
•On Raspbian, the startup and running processes are controlled using
systemd
•To register the program as a service, you need a special service file stored
in the /etc/systemd/system/ directory; it must end with the suffix
.serviceand needs to be created as the root user using sudo
sudovi /etc/systemd/system/dht11.service
•To startthe service
sudosystemctlstartdht11
•To stop the service
sudosystemctlstop dht11
80

Service File Content
[Unit]
Description=DHT11 control program
[Service]
Type=simple
ExecStart=/usr/bin/python3 /home/pi/dht11/dht11.py
User=pi
[Install]
WantedBy=default.target
81