Friday, 30 August 2013

Making a raspberry pi temperature sensor (step 6- coding the sensor)

Here is the sensor code. All you have to do is enter the API key and the feed ID. You will have to type this all out though it will not run if copied into python

import httplib
import json as simplejson
from random import randint
import time
import os
import glob

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

run_number = 0

SENSE_API_KEY =  "your API key here" #note quotation marks
FEED_ID1 =  your feed ID here #note no quotation marks

def read_temp_raw():
     f = open(device_file, 'r')
     lines = f.readlines()
     f.close()
      return lines

def read_temp(): 
         lines = read_temp_raw()
        while lines[0].strip()[-3:]!= 'YES':
        time.sleep(1)
        lines = read_temp_raw()
         equals_pos = lines[1].find('t=')
        if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        tempC = float(temp_string)/1000.0
        return tempC

def send_to_opensense(data):
    try:
          datalist = [{"feed_id" :FEED_ID1, "value" :data['C']},]
          headers = {"sense_key": SENSE_API_KEY,"content-type":"appliaction/json"}
          conn = httplib.HTTPConnection("api.sen.se")
          conn.request("POST", "/events/", simplejson.dumps(datalist),headers)
          response = conn.getresponse()
         conn.close()
    except:
        pass


while(True):
      try:
           run_number = run_number + 1
           tempC = read_temp()
           print "RasPI(2) Ambient Run:",run_number," tempC:",tempC
           data = {'C' : tempC}
          send_to_opensense(data)
          time.sleep(10)
     except:
          pass

{code mostly from whiskeytangohotel}

No comments:

Post a Comment