station-meteo/code/main.py

62 lines
2.1 KiB
Python
Raw Normal View History

"""Station météo connectée au service Adafruit IO
"""
import time
import machine
import network
import bme280_i2c
from mqtt import MQTTClient
import config
# connect to WLAN
wlan = network.WLAN(network.STA_IF)
nets = wlan.scan()
for net in nets:
net_ssid = net[0].decode()
if net_ssid == config.WIFI_SSID:
print('Network found!')
wlan.connect(net_ssid, config.WIFI_PSK)
while not wlan.isconnected():
machine.idle() # save power while waiting
print('WLAN connection succeeded!')
break
if not wlan.isconnected():
print("WLAN not found/not connected")
# Create a micropython I2C object with the appropriate device pins
i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4))
# Create a sensor object to represent the BME280
# Note that this will error if the device can't be reached over I2C.
bme = bme280_i2c.BME280_I2C(address=bme280_i2c.BME280_I2C_ADDR_SEC, i2c=i2c)
# Configure the sensor for the application in question.
bme.set_measurement_settings({
'filter': bme280_i2c.BME280_FILTER_COEFF_16,
'standby_time': bme280_i2c.BME280_STANDBY_TIME_500_US,
'osr_h': bme280_i2c.BME280_OVERSAMPLING_1X,
'osr_p': bme280_i2c.BME280_OVERSAMPLING_16X,
'osr_t': bme280_i2c.BME280_OVERSAMPLING_2X})
# Start the sensor automatically sensing
bme.set_power_mode(bme280_i2c.BME280_NORMAL_MODE)
client = MQTTClient(client_id="int_weather_station",
server="io.adafruit.com",
user=config.ADAFRUIT_IO_USERNAME,
password=config.ADAFRUIT_IO_KEY,
port=1883)
client.connect()
while 1:
bme_data = bme.get_measurement()
print(bme_data)
client.publish("{}/feeds/weather.interior-hum".format(config.ADAFRUIT_IO_USERNAME), "{:.0f}".format(bme_data["humidity"]))
time.sleep_ms(2000)
client.publish("{}/feeds/weather.interior-press".format(config.ADAFRUIT_IO_USERNAME), "{:.2f}".format(bme_data["pressure"]/100))
time.sleep_ms(2000)
client.publish("{}/feeds/weather.interior-temp2".format(config.ADAFRUIT_IO_USERNAME), "{:.1f}".format(bme_data["temperature"]))
time.sleep_ms(16000)