Internet of Things and Raspberry Pi
Internet of Things and Raspberry Pi
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
Home
Soon everything will be connected to the Internet – even your Coffee Maker
Internet of Things (IoT)
Relevant Topics:
Sensor Technology
Machine Learning
Database Systems Internet of Things (IoT)
Raspberry Pi
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
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!
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
SPI
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
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
N = 10
for x in range(N):
adcdata = adc.value #Value between 0 and 1
#print(adcdata)
sleep(1)
https://www.halvorsen.blog
I2C
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)
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
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
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
)
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"]
x = collection.insert_one(document)
import pymongo
# 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)
# 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 = []
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
channel_id = xxxxxxx
write_key = ”xxxxxxxxxxxxxxxxxx”
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
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)
(Publishers) (Publishers/Subscribers)
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
E-mail: [email protected]
Web: https://www.halvorsen.blog