ThingSpeak

由於現在Internet of Thing(物聯網)發展快速,希望設備資訊狀態能透過通訊能隨時監測的狀況下,也越來越多的雲端IOT資料平台,例如現在要用的ThingSpeak,把Raspberry Pi上的溫濕度透過網路傳送到ThingSpeak網站上,然後就可以透過網站就可以即時知道目前Raspberry Pi的溫濕度狀況,接下來先申請ThingSpeak的帳號

申請ThingSpeak帳號

建立Channels

接下來就在瀏覽器中直接執行下面的網址做測試,注意一下網址,有修改field1及field2及其後方的值

  • 溫度(Field1)

  • https://api.thingspeak.com/update?api_key=Q8BGENDUC797GENI&field1=30
    https://api.thingspeak.com/update?api_key=Q8BGENDUC797GENI&field1=40
  • 濕度(Field2)

  • https://api.thingspeak.com/update?api_key=Q8BGENDUC797GENI&field2=55
    https://api.thingspeak.com/update?api_key=Q8BGENDUC797GENI&field2=70

透過Python上傳到ThingSpeak

測試手動執行網址可以上傳到channl後,那接下來使用python把所取得的溫濕度上傳到ThingSpeak所建立的channel,接著把下方的程式碼複製到Raspberry Pi中,並且儲存成dht22.py,並加入可執行的權限

cd ~
nano dht22.py
chmod +x dht22.py

程式原始碼:

#!/usr/bin/python
import sys
import Adafruit_DHT
import httplib, urllib
import time

thingSpeakApiKey = "Q8BGENDUC797GENI"

def main():
    [temp,humidity] = dht22()
    params = urllib.urlencode({'field1': '{0:0.1f}'.format(temp), 'field2': '{0:0.1f}'.format(humidity), 'key': thingSpeakApiKey})
    post_to_thingspeak(params)


# Get Temperature,Humidity
def dht22():
    humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302,4)
    #humidity, temperature = Adafruit_DHT.read_retry(sensor,pin)

    if humidity is not None and temperature is not None:
        print('Temp={0:0.1f}* Humidity={1:0.1f}%'.format(temperature,humidity))
        return(temperature,humidity)
    else:
        print('Failed to get reading. Try again!')
        return(0,0)


# Set ThingSpeak Connection
def post_to_thingspeak(payload):
    headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
    not_connected = 1
    while (not_connected):
        try:
            conn = httplib.HTTPConnection("api.thingspeak.com:80")
            conn.connect()
            not_connected = 0
        except (httplib.HTTPException, socket.error) as ex:
            print "Error: %s" % ex

    #time.sleep(10) # sleep 10 seconds
    conn.request("POST", "/update", payload, headers)
    response = conn.getresponse()
    #print( response.status, response.reason, payload, time.strftime("%c"))
    data = response.read()
    conn.close()

# end main
if __name__ == "__main__":
    sys.exit(main())

執行測試程式,執行指令./dht22.py 或 python dht22.py 就會出現如下的畫面

pi@raspberrypi:~ $ ./dht22.py
Temp=26.8* Humidity=90.9%

定時執行

dht22.py程式只會執行一次後就結束程序,所以這邊透過設定crontab去定時執行dht22.py程式把資料傳送到ThingSpeak上,設定的方式很簡單執行以下的指令

sudo crontab -e

然後加入下面這一行指令後儲存,下面的設定是每10分鐘執行一次,如果要測試可以自已修改該數值

*/10 * * * *     /home/pi/dht22.py >/dev/null 2>&1

儲存後,再回到ThingSpeak上看channel內的溫濕度是否有新增資料

Last updated