2017年3月9日 星期四

MicroPython ESP8266-dht11 sensor


# Import libraries and settings
# from settings import *
# APIKEY = 'T2I3BOAY1M0CCUEL'
# CHANNELID = '258108'
# WifiSSID='PTS-2F'
# WifiPSWD=''

import machine
import time
import dht
import network
import gc
from umqtt.simple import MQTTClient

# Run the ESP8266 at max speed
machine.freq(160000000)

# Functions

def measure():
    d = dht.DHT11(machine.Pin(4))
    try:
    d.measure()
    temp = d.temperature()
    hum = d.humidity()
    #print('Temp: ', temp)  # eg. 23.6 (簞C)
    #print('Humidity: ', hum)  # eg. 41.3 (% RH)
    return temp, hum
    except Exception as e:
        return (-1,-1)

def go_sleep():
    # put the device to sleep for 60 seconds
    time.sleep(60)


def do_connect():
     # connect the ESP8266 to local wifi network
     #
     yourWifiSSID = "PTS-2F" # <--- replace with your WIFI network name
     yourWifiPassword = "" # <--- 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

def post_data(temp,hum):

      # 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 = "238108"   # <--- replace with your Thingspeak Channel ID
      thingspeakChannelWriteapi = "T2I4BOAY1M0CCUEL" # <--- replace with your Thingspeak Write API Key
    # 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(temp,hum, gc.mem_free())
  c.publish(credentials, payload)


# Start of actual program

while True:
    do_connect()
    (temp, hum) = measure()
    post_data(temp,hum)
    go_sleep()

c.disconnect()

沒有留言:

張貼留言

113 學年度第 1 學期 RFID應用課程 Arduino程式

113 學年度第 1 學期 RFID應用課程 Arduino程式 https://www.mediafire.com/file/zr0h0p3iosq12jw/MFRC522+(2).7z/file 內含修改過後的 MFRC522 程式庫 (原程式有錯誤) //定義MFRC522...