2017年2月26日 星期日

MicroPython + ESP8266 + MQTT ThingSpeak


參考
https://pengshp.github.io/post/IoT-ESP8266-OLED-OpenHab-MQTT-Micropython/

https://github.com/MikeTeachman/micropython-thingspeak-mqtt-esp8266/blob/master/mqtt-to-thingspeak.py

ESP8266控制DHT11的温湿度采集



ds=DHT11(machine.Pin(4))
i2c = I2C(sda = Pin(2), scl = Pin(14), freq=100000)








#===================================================
from machine import Pin,I2C
from time import sleep_ms
from ubinascii import hexlify
from umqtt.simple import MQTTClient
from dht import DHT11
from ssd1306 import SSD1306_I2C
import machine
import network
import time
import gc

#---DHT11---
ds=DHT11(machine.Pin(4))

def medirTemHum():
    try:
        ds.measure()
        tem=ds.temperature()
        hum=ds.humidity()
        return (tem,hum)
    except Exception as e:
        return (-1,-1)
#---End DHT11---

#---OLED IIC 128x64---
i2c = I2C(sda = Pin(2), scl = Pin(14), freq=100000)
display = SSD1306_I2C(128, 64, i2c)
led_blue = machine.Pin(2, Pin.OUT)  # ?置 GPIO2 ??出
led_blue.high()
def displaytem(tem,hum):
    display.fill(0)
    temperatura = 'Tem: ' + str(tem)[:5] + 'C'
    humedad = 'Hum: ' + str(hum)[:5] + '%'
    display.text(temperatura,2,2,1)
    display.text(humedad,2,18,1)
    display.show()
#---End OLED---

#---Main Program---
sleep_ms(10000)

# connect the ESP8266 to local wifi network
#
yourWifiSSID = "74170287" # <--- replace with your WIFI network name
yourWifiPassword = "24063173" # <--- replace with your WIFI network password
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(yourWifiSSID, yourWifiPassword)
while not sta_if.isconnected():
  pass

# connect ESP8266 to Thingspeak using MQTT
#
myMqttClient = "my-mqtt-client"  # can be anything unique
thingspeakIoUrl = "mqtt.thingspeak.com"
c = MQTTClient(myMqttClient, thingspeakIoUrl, 1883)  # uses unsecure TCP connection
c.connect()

#
# publish temperature and free heap to Thingspeak using MQTT
#

thingspeakChannelId = "232393"   # <--- replace with your Thingspeak Channel ID
thingspeakChannelWriteapi = "DQMZJSDYCHJ2WKUO" # <--- replace with your Thingspeak Write API Key
publishPeriodInSec = 30


while True:
    (tem,hum) = medirTemHum()
    displaytem(tem,hum)
    # note:  string concatenations below follow best practices as described in micropython reference doc
    credentials = "channels/{:s}/publish/{:s}".format(thingspeakChannelId, thingspeakChannelWriteapi)
    payload = "field1={:.1f}&field2={:.1f}&field3={:d}\n".format(tem,hum, gc.mem_free())
    c.publish(credentials, payload)

    time.sleep(publishPeriodInSec)

c.disconnect()
#---END Main Program---



沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

 2024_09 作業3  (以Node-Red 為主  Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker  2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...