Archived
1
0
This repository has been archived on 2025-04-27. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
pico-dht22/main.py

168 lines
5.4 KiB
Python

import network
import rp2
import time
import machine
from machine import Pin
from umqtt.simple import MQTTClient
import dht
import urequests
import wifi_config
import mqtt_config
# Change this GPIO PIN where your DHT22 sensor is connected
DHT_22_GPIO_PIN = 3
def read_cpu_temp():
"""
If you print the value of the temperature value you are going to get an integer number between 0 and 65535.
So, we have to convert this value either to the Celsius degree scales.
The temperature sensor works by delivering a voltage to the ADC4 pin that is proportional to the temperature.
From the datasheet, a temperature of 27 degrees Celsius delivers a voltage of 0.706 V.
With each additional degree the voltage reduces by 1.721 mV or 0.001721 V.
The first step in converting the 16-bit temperature is to convert it back to volts, which is done based on the 3.3 V maximum voltage used by the Pico board.
ref: https://how2electronics.com/read-temperature-sensor-value-from-raspberry-pi-pico/
"""
cpu_temp_conversion_factor = 3.3 / 65535
cpu_temp_sensor = machine.ADC(4)
reading = cpu_temp_sensor.read_u16() * cpu_temp_conversion_factor
temperature_c = 27 - (reading - 0.706) / 0.001721
temperature_f = temperature_c * 9/5. + 32.0
return temperature_f
def read_dht_22(sensor):
"""
reads the temperature and humidity from dht.DHT22 sensor.
returns tuple(temperature, humidity) if no errors
returns None if there was an error
"""
try:
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
return temperature, humidity
except:
time.sleep(2)
return None
def wlan_up(wlan):
wlan.active(True)
wlan.connect(wifi_config.HOME_WIFI_SSID, wifi_config.HOME_WIFI_PWD)
# Wait for connect or fail
max_wait = 10
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print('Waiting for WiFi connection...')
time.sleep(1)
if max_wait == 0:
return None
ifconfig = wlan.ifconfig()
print(ifconfig)
return ifconfig
def led_error_code(led, error_code: int):
"""Blink LED for a given error code (int). error code == number of times to blink"""
print("LED Error Status code: {}".format(error_code))
# Run a quick 'start error code sequence'
# So we know when LED error sequence starts
start_sequence_counter = 0
while start_sequence_counter < 3:
led.value(True)
time.sleep(0.1)
led.value(False)
time.sleep(0.1)
start_sequence_counter += 1
# Run real error code sequence
blink_counter = 0
while blink_counter < error_code:
time.sleep(1)
led.value(True)
time.sleep(1)
led.value(False)
blink_counter += 1
# Make sure to turn off LED when this subroutine finished
led.value(False)
print("LED Error Status code finished for: {}".format(error_code))
def main():
print("Start up")
count = 0
# Set Wi-Fi Country
rp2.country('US')
wlan = network.WLAN(network.STA_IF)
mqtt_client = MQTTClient(mqtt_config.MQTT_CLIENT_ID, mqtt_config.MQTT_HOST_NAME)
sensor = dht.DHT22(Pin(DHT_22_GPIO_PIN))
led = machine.Pin('LED', machine.Pin.OUT)
led.value(False)
led_error_code(led, 1)
print("Enter main loop")
while True:
led.value(False)
count += 1
print(f'\nStarting loop #{count}... \nWiFI Status is {wlan.status()}.')
if wlan.status() != 3:
ifconfig = wlan_up(wlan)
if ifconfig is None:
print("Trouble to connecting WiFi: {}".format(e))
led_error_code(led, 3)
continue
else:
print("Connected to WiFi: {}".format(ifconfig))
else:
ifconfig = wlan.ifconfig()
print(f"Skipping WiFi Activation since WiFi Status is {wlan.status()} \n{ifconfig}.")
try:
mqtt_client.connect()
print(f'MQTT Connected.')
except Exception as e:
print("Trouble to connecting to MQTT: {}".format(e))
led_error_code(led, 2)
continue
dht22_reading = read_dht_22(sensor)
debug_str = "None"
if dht22_reading is not None:
temp,hum = dht22_reading
temp = temp * 9/5. + 32.0
mqtt_client.publish("m/v1/home/{}/0/temperature".format(mqtt_config.MQTT_ZONE_ID), "DHT22 Temp = {} degF".format(str(temp)), retain=True)
mqtt_client.publish("m/v1/home/{}/0/humidity".format(mqtt_config.MQTT_ZONE_ID), "DHT22 %Hum = {} %".format(str(hum)), retain=True)
debug_str = "{} ; {}".format(temp, hum)
cpu_temp = read_cpu_temp()
print("{} ; CPU: {}".format(debug_str, cpu_temp))
# HW Info
mqtt_client.publish("m/v1/hw/{}/cpu/temperature".format(mqtt_config.MQTT_HW_ID), "CPU Temp = {} degF".format(str(cpu_temp)), retain=True)
mqtt_client.publish("m/v1/hw/{}/wlan/info".format(mqtt_config.MQTT_HW_ID), str(ifconfig), retain=True)
mqtt_client.disconnect()
print(f'MQTT Disconnected.')
# Sleep for a bit.
print(f'Finished loop #{count}.')
time.sleep(5)
main()