Collect data from sensors using Raspberry Pi 4 model B.

First power up the machine and install the Linux software.

  1. The Raspberry Pi
  2. A power supply
  3. A microSD card
  4. A keyboard, a mouse and an HDMI cable
  5. A computer screen
  1. A case
  2. An ethernet cable

Second connect the 40 pins GPIO cable and the Wedge.

Inputs and outputs of a Raspberry Pi model 4.
GPIO Header pin numbers.
Raspberry, extension cable and a wedge.

Third use some very popular sensors to collect data.

DHT11 sensor
  • Operating Voltage: 3.5V to 5.5V
  • Operating current: 0.3mA (measuring) 60uA (standby)
  • Output: Serial data
  • Temperature Range: 0°C to 50°C
  • Humidity Range: 20% to 90%
  • Resolution: Temperature and Humidity both are 16-bit
  • Accuracy: ±1°C and ±1%
HC-SR04 sensor
  • Operating voltage: +5V
  • Theoretical Measuring Distance: 2cm to 450cm
  • Practical Measuring Distance: 2cm to 80cm
  • Accuracy: 3mm
  • Measuring angle covered: <15°
  • Operating Current: <15mA
  • Operating Frequency: 40Hz

Fourth connect the sensors to the breadboard and the Raspberry.

https://github.com/adafruit/Adafruit_Python_DHT.git
https://github.com/adafruit/Adafruit_CircuitPython_DHT.git
pip3 install adafruit-circuitpython-dht
sudo apt-get install libgpiod2
import time
import datetime
import board
import adafruit_dht
import RPi.GPIO as gpio

# Initial the dht device, with data pin connected to:
dhtDevice = adafruit_dht.DHT11(board.D4, use_pulseio=False)

filename = "temp_log.csv"

# Create header row in new CSV file
csv = open(filename, 'w')
csv.write("Timestamp,Temperature\n")
csv.close

for i in range(4):
try:
# Print the values to the serial port
temperature_c = dhtDevice.temperature
temperature_f = temperature_c * (9 / 5) + 32
humidity = dhtDevice.humidity
print(
"Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format(
temperature_f, temperature_c, humidity
)
)

temp_c = str(temperature_c)
entry = str(datetime.datetime.now())
entry = entry + "," + temp_c + "\n"

# Log (append) entry into file
csv = open(filename, 'a')
try:
csv.write(entry)
finally:
csv.close()

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
except Exception as error:
dhtDevice.exit()
raise error

time.sleep(2.0)

#print csv
csv = open(filename, 'r')
print(csv.read())
csv.close()

#cleanup gpio
gpio.cleanup()
Temp: 60.8 F / 16.0 C    Humidity: 68%
Temp: 60.8 F / 16.0 C Humidity: 67%
Temp: 60.8 F / 16.0 C Humidity: 67%
Temp: 60.8 F / 16.0 C Humidity: 67%
Timestamp,Temperature
2022-02-22 09:20:58.192588,16
2022-02-22 09:21:00.567850,16
2022-02-22 09:21:02.939780,16
2022-02-22 09:21:05.311523,16
  • VCC to Pin 2 (VCC)
  • GND to Pin 6 (GND)
  • TRIG to Pin 12 (GPIO18)
  • connect the 330Ω resistor to ECHO. On its end you connect it to Pin 18 (GPIO24) and through a 470Ω resistor you connect it also to Pin6 (GND).
# import libraries
import RPi.GPIO as GPIO
import time

#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)

#set GPIO Pins
GPIO_TRIGGER = 18
GPIO_ECHO = 24

#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)

def distance():
# set Trigger to HIGH
GPIO.output(GPIO_TRIGGER, True)

# set Trigger after 0.01ms to LOW
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)

StartTime = time.time()
StopTime = time.time()

# save StartTime
while GPIO.input(GPIO_ECHO) == 0:
StartTime = time.time()

# save time of arrival
while GPIO.input(GPIO_ECHO) == 1:
StopTime = time.time()

# time difference between start and arrival
TimeElapsed = StopTime - StartTime
# multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance = (TimeElapsed * 34300) / 2

return distance

if __name__ == '__main__':
try:
while True:
dist = distance()
print ("Measured Distance = %.1f cm" % dist)
time.sleep(1)

# Reset by pressing CTRL + C
except KeyboardInterrupt:
print("Measurement stopped by User")
GPIO.cleanup()
Measured Distance = 18.1 cm
Measured Distance = 19.5 cm
Measured Distance = 18.1 cm
Measured Distance = 18.1 cm
Measured Distance = 19.0 cm
Measured Distance = 18.2 cm
...
Combining the 2 sensors on the breadboard.
# Combine 2 sensors
# first get temperature and humidity
# second get distance
import time
import datetime
import board
import adafruit_dht
import RPi.GPIO as GPIO

#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)

#set GPIO Pins
GPIO_TRIGGER = 18
GPIO_ECHO = 24

#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)

# Initial the dht device, with data pin connected to:
dhtDevice = adafruit_dht.DHT11(board.D4, use_pulseio=False)

# give a name to csv file
filename = "temp_log.csv"

# Create header row in new CSV file
csv = open(filename, 'w')
csv.write("Timestamp,Temperature,Humidity,Distance\n")
csv.close

def get_values_from_two_sensors():
# Get the value from DHT11 sensor.
temperature_c = dhtDevice.temperature
temperature_f = temperature_c * (9 / 5) + 32
humidity = dhtDevice.humidity

# Get distance from HC-SR04
# set Trigger to HIGH
GPIO.output(GPIO_TRIGGER, True)

# set Trigger after 0.01ms to LOW
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)

StartTime = time.time()
StopTime = time.time()

# save StartTime
while GPIO.input(GPIO_ECHO) == 0:
StartTime = time.time()

# save time of arrival
while GPIO.input(GPIO_ECHO) == 1:
StopTime = time.time()

# time difference between start and arrival
TimeElapsed = StopTime - StartTime
# multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance = (TimeElapsed * 34300) / 2

temp_c = str(temperature_c)
humid = str(humidity)
entry = str(datetime.datetime.now())
dist = str(distance)
entry = entry + "," + temp_c + "," + humid + "," + dist + "\n"

# Log (append) entry into file
csv = open(filename, 'a')
try:
csv.write(entry)
finally:
csv.close()

return entry



if __name__ == '__main__':
try:
while True:
values = get_values_from_two_sensors()
print (values)
time.sleep(2.0)

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)

except Exception as error:
dhtDevice.exit()
raise error
#continue

except KeyboardInterrupt:
# Reset by pressing CTRL + C
print("Measurement stopped by User")
# read the csv
csv = open(filename, 'r')
print(csv.read())
csv.close()
# clean up
GPIO.cleanup()

--

--

--

I am a pharmacist turned android developer and machine learning engineer. Right now I’m a senior android developer at Invisalign and a ML GDE.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Is Migrate for Anthos a real game changer?

Switching to the Gnome Desktop

Deploy Laravel application in an Aws Ec2 Instance Step-by-step guide

Lightning This Week | 602,888

Testing your Android app on Doze Mode

Squids Launched Free Enterprise-level DBaaS Platform for Multi-Cloud

flaws.cloud — A fun interactive way to learn the basics of AWS Security

Validating a SaaS Solution

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
George Soloupis

George Soloupis

I am a pharmacist turned android developer and machine learning engineer. Right now I’m a senior android developer at Invisalign and a ML GDE.

More from Medium

Easy climate monitoring using a Raspberry Pi

Raspberry Pi Zero WH with an AHT20 Sensor attached and hooked up

Add Sounds to Your Raspberry Pi Device

Installing OpenCV on Raspberry Pi

Are You Running Ubuntu on Raspberry Pi 4? Here’s How to Boost Performance