Skip to content

Instantly share code, notes, and snippets.

@jonathanfann
Last active May 15, 2025 14:28
Show Gist options
  • Save jonathanfann/95d319e00b08718dc8d119ad70e0eec4 to your computer and use it in GitHub Desktop.
Save jonathanfann/95d319e00b08718dc8d119ad70e0eec4 to your computer and use it in GitHub Desktop.
Connect Pico to wifi and AHT20 Temperature & Humidity Sensor via i2C and Serve as JSON
import os
from microdot import Microdot
import network
from time import sleep
from machine import Pin, I2C
import json
from picozero import pico_led
import ahtx0
logfile = open('log.txt', 'a')
os.dupterm(logfile) # logs to log.txt file
ssid = 'MY_WIFI_NAME'
password = 'MY_WIFI_PW'
i2c = I2C(0, scl=Pin(17), sda=Pin(16), freq=400000)
sensor = ahtx0.AHT10(i2c)
def connect():
#Connect to WLAN
pico_led.off()
sleep(0.2)
pico_led.on()
sleep(0.2)
pico_led.off()
sleep(0.2)
pico_led.on()
sleep(0.2)
pico_led.off()
sleep(4)
wlan = network.WLAN(network.STA_IF)
wlan.active(False)
sleep(0.2)
wlan.active(True)
sleep(0.2)
attempt_i = 1
wlan.connect(ssid, password)
print('connecting to wifi', ssid)
while wlan.isconnected() == False:
pico_led.on()
sleep(0.5)
pico_led.off()
sleep(0.5)
print('Waiting for connection...', 'Attempt:', attempt_i)
sleep(5)
wlan.connect(ssid, password)
attempt_i += 1
pico_led.on()
sleep(1)
ip = wlan.ifconfig()[0]
print(f'Connected on {ip}')
sleep(0.2)
if wlan.isconnected() == True:
app = Microdot()
@app.route('/')
def index(request):
if sensor.temperature:
temp_farenheit = (sensor.temperature * 9/5) + 32
print("\nTemperature: %0.1f F" % temp_farenheit)
if sensor.relative_humidity:
humidity = sensor.relative_humidity
print("Humidity: %0.1f %%" % sensor.relative_humidity)
response = {"humidity": str(humidity), "temp_farenheit": str(temp_farenheit)}
return json.dumps(response), 200, {'Content-Type': 'text/javascript'}
app.run(port=5000)
connect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment