After writing the previous article, I read some related blog posts and wondered Why my sensor was not being recognized.
Then I suddenly realized!! I had misunderstood the Raspberry Pi's pin numbering!!
The yellow numbers show what I thought last time, and the blue numbers show the correct arrangement.

When I ran the command again to double-check...
sudo i2cdetect -y 1
The sensor was successfully detected!!

Let's get back on track and move on to the settings for actually reading the temperature with the sensor.
1. Read temperature and humidity using the sensor
-1. Create the working directory
mkdir -p ~/growtent
cd ~/growtent
python3 -m venv .venv
source .venv/bin/activate
-2. Install the required libraries
pip install adafruit-blinka adafruit-circuitpython-sht31d
-3. Create the test script
nano test_sht31.py
"test_sht31.py"
import time
import board
import busio
import adafruit_sht31d
i2c = busio.I2C(board.SCL, board.SDA)
sensor = adafruit_sht31d.SHT31D(i2c, address=0x44)
while True:
print(f"Temperature: {sensor.temperature:.2f} C")
print(f"Humidity: {sensor.relative_humidity:.2f} %")
print("-" * 20) time.sleep(5)
This code reads humidity and temperature from the sensor every 5 seconds.
-4. Run the test script
source ~/growtent/.venv/bin/activate
python ~/growtent/test_sht31.py
If the temperature and humidity are displayed every 5 seconds, the sensor is working as expected.

(I might need to turn on the dehumidifier in my room.)
1. Store the data in a CSV file
Next, I will store the temperature and humidity date in a CSV file.
-1. Create the logging script
Create a logging script.
nano log_sht31.py
"log_sht31.py"
import csv
import time
from datetime import datetime
from pathlib import Path
import board
import busio
import adafruit_sht31d
log_path = Path.home() / "growtent" / "temp_humidity_log.csv"
i2c = busio.I2C(board.SCL, board.SDA)
sensor = adafruit_sht31d.SHT31D(i2c, address=0x44)
file_exists = log_path.exists()
with open(log_path, "a", newline="") as f:
writer = csv.writer(f)
if not file_exists:
writer.writerow(["timestamp", "temperature_c", "humidity_percent"])
while True:
now = datetime.now().isoformat(timespec="seconds")
temp = round(sensor.temperature, 2)
hum = round(sensor.relative_humidity, 2)
writer.writerow([now, temp, hum])
f.flush()
print(now, temp, hum)
time.sleep(60)
-2. Run the logging script
python log_sht31.py
The temperature and humidity are displayed and saved every minute.
-3. Check the CSV file
Make sure that the data is correctly stored in the CSV file.
cat ~/growtent/temp_humidity_log.csv
Next time, I will install the sensor in the grow tent and upload the CSV data to AWS!


Top comments (0)