0% found this document useful (0 votes)
67 views68 pages

Internet of Things and Raspberry Pi

The document provides an overview of the Internet of Things (IoT) and the use of Raspberry Pi in various IoT applications, emphasizing the integration of Python programming and data acquisition from sensors. It covers topics such as digital sensor interfaces (SPI, I2C, 1-Wire), NoSQL databases like MongoDB, and cloud services like ThingSpeak, along with practical examples of using Raspberry Pi for data collection and processing. Additionally, it discusses the importance of cybersecurity in IoT implementations.
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)
67 views68 pages

Internet of Things and Raspberry Pi

The document provides an overview of the Internet of Things (IoT) and the use of Raspberry Pi in various IoT applications, emphasizing the integration of Python programming and data acquisition from sensors. It covers topics such as digital sensor interfaces (SPI, I2C, 1-Wire), NoSQL databases like MongoDB, and cloud services like ThingSpeak, along with practical examples of using Raspberry Pi for data collection and processing. Additionally, it discusses the importance of cybersecurity in IoT implementations.
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/ 68

https://www.halvorsen.

blog

Internet of Things
and Raspberry Pi
Hans-Petter Halvorsen
Table of Contents
• Introduction
• Internet of Things
• Raspberry Pi
• Raspberry Pi and Python Programming
• DAQ and IoT Sensors
• Digital Sensor Interfaces
– SPI
– I2C
– 1-Wire
• NoSQL and MongoDB
• ThingSpeak
• MQTT (“IoT Communication Protocol”)
• Raspberry Pi with MATLAB
Introduction
• With Internet of Things (IoT) and Cloud Services
Datalogging has reach a new era.
• The Data are typically stored in the Cloud using
traditional SQL databases or more modern systems
like NoSQL databases or different IoT cloud
services (e.g., ThingSpeak, MongoDB Atlas, etc.).
• We will use Raspberry Pi. Raspberry Pi is popular to
use in different IoT applications.
• We will primarily use Python, but also MATLAB as
programming languages.
Topics
• Internet of Things (IoT)
• Microcomputers, Raspberry Pi and Linux
• Python (Raspberry Pi + Python are Powerful!)
• IoT Sensors, Digital Interfaces: SPI/I2C
• NoSQL (MongoDB)
• ThingSpeak (IoT Cloud Service)
• MQTT (IoT Communication Protocol)
• Raspberry Pi with MATLAB
Delivery
• Retrieve data from Temperature Sensors, e.g., TMP36 or/and
an I2C/1-Wire Temperature sensor. Use the Python
programming language.
• Lowpass Filter to remove noise from the signal
• Alarm Handling
• The data should be stored in a MongoDB database (NoSQL),
either locally or in the cloud.
• The data should be also be stored in the cloud service
ThingSpeak
• MQTT Communication
• Cyber Security: Give an overview of how Raspberry Pi OS
(Linux) handles Security. For more details, see the web site
https://www.halvorsen.blog

Internet of Things

Hans-Petter Halvorsen Table of Contents


Internet of Things (IoT)
IoT – Consumer oriented, Smart Home Solutions, etc.
IIoT – Industrial use of IoT Technology.
Industrial Internet of Things (IIoT) is another word for Industry 4.0
Internet of Things (IoT)
Computers and Devices Cars and Vehicles
Process Industry

Artificial Intelligence (AI)


IT Internet
Smartphones

Data Security People

Home
Soon everything will be connected to the Internet – even your Coffee Maker
Internet of Things (IoT)
Relevant Topics:
Sensor Technology

Datalogging and Monitoring

Machine Learning
Database Systems Internet of Things (IoT)

Cloud Computing Industrial Internet of Things


and Industry 4.0 Cyber Security
https://www.halvorsen.blog

Raspberry Pi

Hans-Petter Halvorsen Table of Contents


Raspberry Pi
Raspberry Pi is a tiny (about 9x6cm), low-cost ($35+),
single-board computer that supports embedded Linux
operating systems
The recommended Operating System is
called Raspberry Pi OS (Linux based)

https://www.raspberrypi.org
Raspberry Pi vs. Arduino
• Raspberry PI is a Microcomputer • Arduino is a Microcontroller
• It has an ordinary Operating System (OS) • Arduino has a Bootloader and not an
• You can connect USB devices, Keyboard, ordinary operating system
Mouse, Monitors, etc. • Arduino is NOT a computer, only a small
• It has a “hard-drive“ in form of a microSD card controller, whose purpose is to control
• RP has Bluetooth, Wi-Fi, and Ethernet things
connection • No Bluetooth, Wi-Fi (some models have),
• RP has basically all the features an ordinary and Ethernet (but can be provided as so-
computer has but in a much smaller package called Shields)
• Uptill 8 Gb RAM • Very little RAM (a few Kb)
• RP runs Linux applications • Inexpensive
Both have Digital Pins
Both have SPI and I2C
Arduino (UNO) has also Analog Input Pins
Raspberry Pi GPIO

A powerful feature of the Raspberry Pi is the GPIO (general-purpose input/output) pins.


The Raspberry Pi has a 40-pin GPIO header as seen in the image
Raspberry Pi OS
• In order make your Raspberry Pi up and running you need
to install an Operating System (OS)
• The OS for Raspberry Pi is called “Raspberry Pi OS“
(previously known as Raspbian)
• Raspberry Pi runs a version of an operating system called
Linux (Windows and macOS are other operating systems).
• To install the necessary OS, you need a microSD card
• Then you use the “Raspberry Pi Imager“ in order to
download the OS to the microSD card.
https://www.raspberrypi.org/software/
Start using Raspberry Pi
Raspberry Pi OS

• Put the microSD card into the Raspberry


Pi
• Connect Monitor, Mouse and Keyboard
• Connect Power Supply
• Follow the Instructions on Screen to
https://www.raspberrypi.org/software/ setup Wi-Fi
https://www.halvorsen.blog

Raspberry Pi
and Python Programming
Hans-Petter Halvorsen Table of Contents
Raspberry Pi and Python
The Raspberry Pi OS comes with a
basic Python Editor called Thonny
Raspberry Pi + Python are a
powerful combination!

But you can install and use other


Python Editors if you prefer

https://www.raspberrypi.org/documentation/usage/python/
Python Packages with Thonny
Tools -> Manage packages…
LED Example: Setup and Wiring
LED Example: Python Code
https://www.halvorsen.blog

DAQ and IoT Sensors

Hans-Petter Halvorsen Table of Contents


DAQ and IoT Sensors
DAQ and IoT Sensors
• DAQ (Data Acquisition) and Sensors are
needed and used in all IoT applications.
• DAQ is the process of getting data from
the sensors into your software.
• Here will some popular IoT sensors be
presented.
IoT Sensors
• IoT sensors comes in many flavors.
• Below, some IoT sensors are presented
they can be programmed with Python.
• IoT Sensor Examples: TMP36,
Thermistor 10K, TC74, BME280, and
DHT11/22.
GPIO Python Libraries
• GPIO Zero
– https://pypi.org/project/gpiozero/
• RPi.GPIO
– https://pypi.org/project/RPi.GPIO/
• smbus (used for I2C communication)
• CircuitPython - Typically, you would use the
Python GPIO Zero Library, but it does not work so
well with SPI/I2C Sensors
https://www.halvorsen.blog

Digital Sensor Interfaces

Hans-Petter Halvorsen Table of Contents


Digital Interfaces
• Raspberry Pi has only Digital pins
• In order to connect and use Sensors we
typically need to use one or more of
these digital interfaces:
– SPI Interface
– I2C Interface
– 1-Wire Interface
Enable Access to Interfaces
• SPI Interface
• I2C Interface
• 1-Wire Interface
CircuitPython and Adafruit-Blinka
• CircuitPython adds the Circuit part to the Python part.
• Letting you program in Python and talk to Circuitry like
sensors, motors, and LEDs!
• Typically, you would use the Python GPIO Zero Library,
but it does not work with SPI/I2C Sensors
• On Raspberry Pi we need to install Adafruit-Blinka. This is
a CircuitPython API that can be used on Linux devices
such as the Raspberry Pi
• Adafruit-Blinka: https://pypi.org/project/Adafruit-Blinka/
https://learn.adafruit.com/circuitpython-on-raspberrypi-linux/
https://www.halvorsen.blog

SPI

Hans-Petter Halvorsen Table of Contents


SPI
• Serial Peripheral Interface (SPI)
• SPI is an interface to communicate with
different types of electronic components
like Sensors, Analog to Digital Converts
(ADC), etc. that supports the SPI
interface
• Thousands of different Components and
Sensors supports the SPI interface
https://www.raspberrypi.org/documentation/hardware/raspberrypi/spi/
SPI Wiring on Raspberry Pi
GPIO 40 pins Connector
Analog Temperature Sensors
TMP36 Temperature Sensor 10k Thermistor Temperature Sensor
Note! Raspberry Pi has no +5V
Analog In Channels. You
need to use an external ADC
10𝑘 Thermistor

Analog In (AI)

𝑅 = 10𝑘Ω

GND
Example: Read Data from ADC
The MCP3002 is a 10-bit analog to digital converter with 2 channels (0-1).
For test purpose we start by wiring a 1.5V Battery to the CH0 (+) and CH1(-) pins on the ADC
Note! WE have set
differential=True (meaning from gpiozero import MCP3002
CH0 is “+“ and CH1 is “-“) from time import sleep

1.5V Battery adc = MCP3002(channel=0, differential=True)

ADC N = 20

for x in range(N):
adcdata = adc.value #Value between 0 and 1
#print(adcdata)
voltvalue = adcdata * 5 #Value 0-5V
print(voltvalue)
sleep(1)
Measure temperature with an ADC
from gpiozero import MCP3002
TMP36 Temperature Sensor from time import sleep

adc = MCP3002(channel=0, differential=False)

N = 10

for x in range(N):
adcdata = adc.value #Value between 0 and 1
#print(adcdata)

Wire a TMP36 temperature voltvalue = adcdata * 5 #Value between 0V and 5V


sensor to the first channel of an #print(voltvalue)
MCP3002 analog to digital tempC = 100*voltvalue-50 #Temperature in Celsius
converter and the other pins to tempc = round(tempC,1)
+5V and GND print(tempC)

sleep(1)
https://www.halvorsen.blog

I2C

Hans-Petter Halvorsen Table of Contents


I2C
• I2C is a multi-drop bus
• 2-Wire Protocol (SCL + SDA)
• Multiple devices can be connected to the I2C
pins on the Raspberry Pi
• Each device has its own unique I2C address
I2C Wiring on Raspberry Pi
GPIO 40 pins Connector

Note! The I2C pins include a fixed 1.8 kΩ pull-up resistor to 3.3v.
TC74 Temperature Sensor
SMBus/I2C Interface
TC74A0-5.0VAT • The TC74 acquires and converts
temperature information from its onboard
solid-state sensor with a resolution of
±1°C.
• It stores the data in an internal register
which is then read through the serial port.
• The system interface is a slave SMBus/I2C
port, through which temperature data can
be read at any time.

Datasheet: https://ww1.microchip.com/downloads/en/DeviceDoc/21462D.pdf
TC74 Python Code Example
import smbus
This code shows the basic
reading of the Sensor Data. channel = 1
address = 0x48
You can add a For Loop or a
While Loop for reading bus = smbus.SMBus(channel)
Sensor Data at specific
intervals. data = bus.read_byte_data(address, 0)
print(data)
You can plot the Data using
matplotlib, save data to a File Or just:
or send data to a cloud data = bus.read_byte(address)
service like ThingSpeak, etc. print(data)

This gives the Temperature Value in Degrees Celsius, e.g., 22


BME280
• BME280 is a Digital Humidity, Pressure and
Temperature Sensor from Bosch
• The sensor provides both SPI and I2C interfaces
• Adafruit, Grove Seeed, SparkFun, etc. have
breakout board bords for easy connection to
Arduino, Raspberry Pi, etc.
BME280 Python Example
import time
import board https://circuitpython.readthedocs.io/projects/bme280/en/latest/
import busio
import adafruit_bme280

# Create library object using our Bus I2C port


i2c = busio.I2C(board.SCL, board.SDA)
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c)

# OR create library object using our Bus SPI port


# spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
# bme_cs = digitalio.DigitalInOut(board.D10)
# bme280 = adafruit_bme280.Adafruit_BME280_SPI(spi, bme_cs)

# change this to match the location's pressure (hPa) at sea level


bme280.sea_level_pressure = 1013.25

while True:
print("\nTemperature: %0.1f C" % bme280.temperature)
print("Humidity: %0.1f %%" % bme280.relative_humidity)
print("Pressure: %0.1f hPa" % bme280.pressure)
print("Altitude = %0.2f meters" % bme280.altitude)
time.sleep(2)
https://www.halvorsen.blog

1-Wire

Hans-Petter Halvorsen Table of Contents


DHT11/DHT22
They are Breadboard friendly and easy to wire. They use a single-wire to send data.

DHT11 DHT22
• Good for 20-80% DHT22 is more precise,
humidity readings with more accurate and works
5% accuracy in a bigger range of
• Good for 0-50°C temperature and
temperature readings humidity, but its larger
±2°C accuracy and more expensive
• 1 Hz sampling rate • 0-100% RH
(once every second) • -40-125°C
• Price: a few bucks
Typically you need a 4.7K or 10K resistor, which you will want to use as a
pullup from the data pin to VCC. This is included in the package
DHT11/DHT22
+5V (P
in 2)
DHT
GND (Pi
n 6)
Raspberry Pi GPIO

1 2 4 GND

VCC
3.3/5V 𝑅 = 10𝑘Ω

GND 16 (Pin 36) This is just an example, you can use any Power pins,
any of the GND pins and any of the GPIO pins
DHT11/DHT22 Python Example
import time
import board
import adafruit_dht

dhtDevice = adafruit_dht.DHT22(board.D18, use_pulseio=False)

while True:
try:
temperature_c = dhtDevice.temperature
Errors happen fairly often, DHT's
humidity = dhtDevice.humidity are hard to read because it needs
print(
"Temp: {:.1f} C Humidity: {}% ".format( precise timing. That’s why you
temperature_c, humidity
) should use try in your code
)

except RuntimeError as error:


# Errors happen fairly often, DHT's are hard to read, just keep going
print(error.args[0])
time.sleep(2.0)
continue https://learn.adafruit.com/dht-
except Exception as error:
dhtDevice.exit() humidity-sensing-on-raspberry-pi-with-
raise error gdocs-logging/python-setup
time.sleep(2.0)
https://www.halvorsen.blog

NoSQL and MongoDB

Hans-Petter Halvorsen Table of Contents


MongoDB
• MongoDB is a cross-platform document-oriented database program.
• MongoDB is a NoSQL database program
• MongoDB uses JSON-like documents
• Home Page: https://www.mongodb.com/
Software:
• MongoDB Community Server – Free version of the MongoDB Server
which can be installed locally on your computer or a server
• MongoDB Atlas – Premade MongoDB ready to use in the Cloud
• MongoDB Compass – GUI for connecting to and manipulating your
MongoDB database
• PyMongo – MongoDB Driver for Python
SQL vs MongoDB
Note the following:
• A collection in MongoDB is the same
as a table in SQL databases.
• A document in MongoDB is the same
as a record in SQL databases.
MongoDB Compass
PyMongo
• The PyMongo package contains tools for
interacting with MongoDB database
from Python
• The PyMongo package is a native
Python driver for MongoDB
• Install using PIP: pip install pymongo
• https://pypi.org/project/pymongo/
Python
Python script that creates a Database (“Library”), a Collection (“BookDB”) and a Document.

In a SQL database we use the INSERT statement to insert data in a table.

In MongoDB we use the insert_one() and insert_many() methods to insert data into a collection.

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")
database = client["Library"]
collection = database["Book"]

document = { "Title": "C# Programming", "Author": "Knut Hamsun" }

x = collection.insert_one(document)
import pymongo

Logging Data Example


import random
import time
from datetime import datetime

# Create Database
client = pymongo.MongoClient("mongodb://localhost:27017/")
database = client["MeasurementSystem"]
collection = database["MeasurementData"]

Ts = 10 # Sampling Time
N = 10
for k in range(N):
# Generate Random Data
LowLimit = 20
UpperLimit = 25
MeasurementValue = random.randint(LowLimit, UpperLimit)

#Find Date and Time


now = datetime.now()
datetimeformat = "%Y-%m-%d %H:%M:%S"
MeasurementDateTime = now.strftime(datetimeformat)

# Insert Data into Database


document = { "MeasurementValue": MeasurementValue, "MeasurementDateTime":
MeasurementDateTime }
x = collection.insert_one(document)

# Wait
time.sleep(Ts)
import pymongo
import matplotlib.pyplot as plt
from datetime import datetime

# Connect to Database
Plotting Data client = pymongo.MongoClient("mongodb://localhost:27017/")
database = client["MeasurementSystem"]
collection = database["MeasurementData"]

t = []
data = []

# Retrieving and Formatting Data


for document in collection.find():
MeasurementValue = document["MeasurementValue"]
MeasurementDateTime = document["MeasurementDateTime"]

timeformat = "%Y-%m-%d %H:%M:%S"


MeasurementDateTime = datetime.strptime(MeasurementDateTime, timeformat)

data.append(MeasurementValue)
t.append(MeasurementDateTime)

# Plotting
plt.plot(t, data, 'o-')
plt.title('Temperature')
plt.xlabel('t [s]')
plt.ylabel('Temp [degC]')
plt.grid()
plt.show()
Plotted Data
https://www.halvorsen.blog

ThingSpeak

Hans-Petter Halvorsen Table of Contents


ThingSpeak
• ThingSpeak is an IoT analytics platform service
that lets you collect and store sensor data in the
cloud and develop Internet of Things applications.
• ThingSpeak has a free Web Service (REST API) that
lets you collect and store sensor data in the cloud
and develop Internet of Things applications.
• It works with Arduino, Raspberry Pi, MATLAB and
LabVIEW, Python, etc.
https://thingspeak.com
import thingspeak

Write TMP36 Data


A Free ThingSpeak Channel can
import time
only be updated every 15 sec
from gpiozero import MCP3002

adc = MCP3002(channel=0, differential=False)

channel_id = xxxxxxx
write_key = ”xxxxxxxxxxxxxxxxxx”

channel = thingspeak.Channel(id=channel_id, api_key=write_key)

N = 10
for x in range(N):
#Get Sensor Data
adcdata = adc.value #Scaled Value between 0 and 1
voltvalue = adcdata * 5 # Value between 0V and 5V
tempC = 100*voltvalue-50 # Temperature in Celsius
tempC = round(tempC,1)
print(tempC)

#Write to ThingSpeak
response = channel.update({'field1': tempC})
time.sleep(15)
Write TMP36 Data
Here we see the Temperature Data in ThingSpeak:
https://www.halvorsen.blog

MQTT

Hans-Petter Halvorsen Table of Contents


MQTT MQTT is a popular IoT
Communication Protocol

• Message Queueing Telemetry Transport (MQTT) is


an IoT connectivity protocol
• MQTT is used in applications with thousands of
sensors
• MQTT is efficient in terms of bandwidth, battery,
and resources
• MQTT uses a publish/subscribe model

https://mqtt.org/
• MQTT can be implemented using standard HTTP
calls
• M2M (machine to machine) Communication
MQTT Scenario
MQTT Publishers MQTT Subscribers
(Clients) (Clients)

MQTT Broker
(Server)

The Broker is responsible for


Sensors sending messages between the
Publishers and the Subscribers
Publish/Subscribe Model
Typically, we have what we call Producers (Publishers), and we have Consumers,
which can be both Publishers and Subscribers.

(Client) (Server) (Client)


Publish (Topic, Data)
Producer Publish (Topic, Data) Broker Publish (Topic)
Consumer

(Publishers) (Publishers/Subscribers)

An MQTT Client Publishes Other Clients can Subscribe to


a Message to the Broker the Broker to receive Messages
https://www.halvorsen.blog

Raspberry Pi
with MATLAB
Hans-Petter Halvorsen Table of Contents
Raspberry Pi + MATLAB

Network
PC with MATLAB

With MATLAB support package for Raspberry Pi, the Raspberry Pi is connected to a
computer running MATLAB. Processing is done on the computer with MATLAB.

https://mathworks.com/hardware-support/raspberry-pi-matlab.html
MATLAB Support Package for Raspberry Pi

Getting Started with MATLAB Support Package for Raspberry Pi: https://youtu.be/32ByiUdOwsw
MATLAB Example

Observe that the built-in LED


on the Raspberry Pi is blinking
Hans-Petter Halvorsen
University of South-Eastern Norway
www.usn.no

E-mail: [email protected]
Web: https://www.halvorsen.blog

You might also like