IOT Sensor

Motivation

Logging data can be quite simple, especially with a raspberry pi in your toolbox !

Code

Using Envirophat shield on a raspberry pi zero, is a convenient way to get a lot of sensors attached. It is then possible to retrieve values from these sensors and upload the data to a server. In my case I use Thingspeak.

The below code gives an example of data from 3 sensors on the envirophat board. The data is being uploaded to a thingspeak channel. Check out the newest uploaded pressure data here

import time
import httplib
import urllib
from envirophat import weather, light, motion

sleep = 120
key = 'INPUT YOUR THINGSPEAK WRITE API KEY HERE'

def get_pressure():
    val_01 = weather.pressure() / 100
    return(val_01)

def get_light():
    val_02 = light.light()
    return(val_02)

def get_heading():
    val_03 = motion.heading()
    return(val_03)

def updatets():
    while True:
        params = urllib.urlencode({'field1':pressure,'field2':lightvalue,'field3':heading,'key':key})
        headers = {"Content-type":"application/x-www-form-urlencoded","Accept":"text/plain"}
        conn = httplib.HTTPConnection("api.thingspeak.com:80")
        try:
            conn.request("POST","/update",params,headers)
            response = conn.getresponse()
            print response.status, response.reason
            data = resonse.read()
            conn.close()
        except:
            print("connection failed")
        break

if __name__ == "__main__":
    while True:
        pressure = int(get_pressure())
        lightvalue = int(get_light())
        heading = int(get_heading())
        updatets()
        time.sleep(sleep)