ESP32 複合センサBME680で測定したデータをMariaDBにとばす
先日仕入れたBME680を用いて温度、湿度、気圧、ガス濃度を測定してMariaDBに飛ばして記録したいと思います。今回のプログラムです。先にWi-Fiにつないでからrunさせます。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import ujson import urequests from machine import Pin,I2C from time import sleep from bme680 import * p21 = Pin(21, Pin.IN, Pin.PULL_UP) p23 = Pin(23, Pin.IN, Pin.PULL_UP) i2c = I2C(scl=Pin(21), sda=Pin(23)) while True: try: bme = BME680_I2C(i2c=i2c) temp = str(round(bme.temperature, 2)) hum = str(round(bme.humidity, 2)) pres = str(round(bme.pressure, 2)) gas = str(round(bme.gas/1000, 2)) print('Temperature:', temp) print('Humidity:', hum) print('Pressure:', pres) print('Gas:', gas) dict = { "temp_value":temp, "hum_value":hum, "pres_value":pres, "gas_value":gas } response = urequests.post( 'https://***url***/postrcv.php', data=ujson.dumps(dict).encode("utf-8"), headers={'Content-Type': 'application/json'} ) print (response.text) except OSError as e: print('Failed to read sensor.') sleep(10) |
実行結果です。
C:\Users\>ampy -p com3 run c:\micropython\posttest8.py
Warning: I2C(-1, ...) is deprecated, use SoftI2C(...) instead
Temperature: 17.36
Humidity: 54.01
Pressure: 1019.21
Gas: 56.24
"temp=17.36 , hum=54.01 , pres=1019.21, gas=56.24"New record created successfully
Temperature: 17.35
Humidity: 54.14
Pressure: 1019.22
Gas: 54.43
"temp=17.35 , hum=54.14 , pres=1019.22, gas=54.43"New record created successfully
Temperature: 17.41
Humidity: 54.15
Pressure: 1019.24
Gas: 53.23
"temp=17.41 , hum=54.15 , pres=1019.24, gas=53.23"New record created successfully
Temperature: 17.48
Humidity: 54.03
Pressure: 1019.2
Gas: 52.34
"temp=17.48 , hum=54.03 , pres=1019.2, gas=52.34"New record created successfully
Aborted!
しっかりと10秒おきにDBに記録されています。
次回はプログラムを見直し、単独で自動運転できるようにします。
