Created
September 14, 2012 22:11
-
-
Save sammyd/3725256 to your computer and use it in GitHub Desktop.
Calculating the temperature from an Arduino and saving it to tempoDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import serial | |
import math | |
import datetime | |
from tempodb import Client, DataPoint | |
# Electronic component constants | |
POTENTIAL_DIVIDER_RESISTOR = 10000 | |
THERMISTOR_B_VALUE = 3977 | |
THERMISTOR_REF_TEMP = 298.15 | |
THERMISTOR_REF_RESISTANCE = 10000 | |
# Configure the tempoDB client | |
client = Client('your-api-key', 'your-api-secret') | |
# Calculates the temperature from the ADC output of the arduino | |
def calculate_temp(value): | |
# Assumes a 5V arduino supply | |
voltage = float(value) / 1024 * 5 | |
# Assumes the thermistor is on the ground side of the potential divider | |
resistance = POTENTIAL_DIVIDER_RESISTOR / (5 / voltage - 1) | |
temp = 1 / (1/THERMISTOR_REF_TEMP + math.log(resistance / THERMISTOR_REF_RESISTANCE) / THERMISTOR_B_VALUE) | |
print "Temperature is: %f K, (%f degC)" % (temp, temp-273.15) | |
return temp-273.15 | |
ser = serial.Serial('/dev/tty.usbserial-A800etDk', 9600) | |
# We want to average the readings over a minute | |
temperature_array = [] | |
while 1: | |
r = ser.readline() | |
# Fits the current arduino output line | |
split = r.split(": ") | |
if split[0] == "sensorValue": | |
value = split[1].strip() | |
temp = calculate_temp(value) | |
temperature_array.append(temp) | |
if(len(temperature_array) >= 20): | |
mean = sum(temperature_array) / float(len(temperature_array)) | |
print "Saving off this minute's mean: %f" % mean | |
# Only save the value when we have an average of 20 points | |
client.write_key('temperature', [DataPoint(datetime.datetime.now(), mean)]) | |
# Reset the array | |
temperature_array = [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment