Created
May 21, 2023 18:08
-
-
Save creeper6530/6c6371cb4595e7b3d66fe0e5a3f8561c to your computer and use it in GitHub Desktop.
Python script to measure temperature and humidity using the Seeed Grove DHT20 sensor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
import smbus | |
import time | |
import argparse | |
try: | |
bus = smbus.SMBus(1) | |
except PermissionError: | |
print("Could not open I2C bus: Permission denied.") | |
print("Try re-running the script as root.") | |
exit(1) | |
my_data = [0x33, 0x00] | |
def read_dht20(): | |
bus.write_i2c_block_data(0x38, 0xAC, my_data) | |
time.sleep(0.08) | |
data = bus.read_i2c_block_data(0x38, 1, 7) | |
temp = 0 | |
temp = (temp | data[3]) << 8 | |
temp = (temp | data[4]) << 8 | |
temp = temp | data[5] | |
temp = temp & 0xfffff | |
temp = (temp * 200 * 10 / 1024 / 1024 - 500)/10 | |
humidity = 0 | |
humidity = (humidity | data[1]) << 8 | |
humidity = (humidity | data[2]) << 8 | |
humidity = humidity | data[3] | |
humidity = humidity >> 4 | |
humidity = (humidity * 100 * 10 / 1024 / 1024)/10 | |
return (temp, humidity) | |
parser = argparse.ArgumentParser() | |
parser.add_argument("metric") | |
args = parser.parse_args() | |
data = read_dht20() | |
if args.metric == "temp": | |
print(data[0]) | |
exit(0) | |
elif args.metric == "humid": | |
print(data[1]) | |
exit(0) | |
else: | |
print("Unsupported metric.") | |
exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment