Collect data from sensors using Raspberry Pi 4 model B.

Inputs and outputs of a Raspberry Pi model 4.
GPIO Header pin numbers.
Raspberry, extension cable and a wedge.
DHT11 sensor
HC-SR04 sensor
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
# 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()

--

--

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