Skip to content

Instantly share code, notes, and snippets.

@pingswept
Last active July 1, 2018 00:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pingswept/6238c24461965ef0ccd98426e975309b to your computer and use it in GitHub Desktop.
Save pingswept/6238c24461965ef0ccd98426e975309b to your computer and use it in GitHub Desktop.
Python script to turn a fan on and off based on SHT31 temperature and temperature from the internet
from Adafruit_IO import *
import json
import requests
import RPi.GPIO as GPIO
import smbus
import time
aio = Client('XXXXXXXXXXXXXXXXX_ADAFRUIT_API_KEY_GOES_HERE_XXXXXXXXXXXXXXXXX')
GPIO.setmode(GPIO.BCM) # choose BCM or BOARD
GPIO.setup(26, GPIO.OUT, initial=0) # set a port/pin as an output
WEATHER_URL = 'http://api.openweathermap.org/data/2.5/weather?zip=02144&appid=fa50fc1b8864b5ca05d05995712c8728'
last_time = time.time() - 100 # pretend we checked outside temp 100 seconds ago
# Equations below from
# https://www.vaisala.com/sites/default/files/documents/Humidity_Conversion_Formulas_B210973EN-F.pdf
def saturation_pressure(temp_in_c):
A = 6.116441
m = 7.591386
Tn = 240.7263 # triple point temp in C
Pws = 100 * A * 10 ** ((m * temp_in_c) / (temp_in_c + Tn))
return Pws # in Pa (should range ~611-7377 Pa across 0-40 C, according to National Weather Service)
def vapor_pressure(temp_in_c, rh):
Pw = saturation_pressure(temp_in_c) * (rh/100.0)
return Pw
def absolute_humidity(temp_in_c, rh):
C = 2.16679 # [gK/J]
Pw = vapor_pressure(temp_in_c, rh)
T = temp_in_c + 273.15
A = C * (Pw / T)
return A # absolute_humidity(20,80) should return 13.82 [g/m3]
while(True):
if time.time() - last_time > 10:
r = requests.get(WEATHER_URL)
print("Got new weather data")
last_time = time.time()
weather_data = json.loads(r.text)
out_temp = 32 + 1.8 * (weather_data['main']['temp'] - 273.15) # converting from K to F
out_rh = weather_data['main']['humidity']
bus = smbus.SMBus(1)
# SHT31 address, 0x44(68)
bus.write_i2c_block_data(0x44, 0x2C, [0x06])
time.sleep(0.5)
# SHT31 address, 0x44(68)
# Read data back from 0x00(00), 6 bytes
# Temp MSB, Temp LSB, Temp CRC, Humididty MSB, Humidity LSB, Humidity CRC
data = bus.read_i2c_block_data(0x44, 0x00, 6)
# Convert the data
temp = data[0] * 256 + data[1]
in_temp = -49 + (315 * temp / 65535.0)
in_rh = 100 * (data[3] * 256 + data[4]) / 65535.0
# Send data to Adafruit IO
aio.send('woodbine-temp', in_temp)
aio.send('somerville-temp', out_temp)
# Output data to screen
print("Inside temp: %.2f F" % in_temp)
print("Inside RH: %.2f %%" % in_rh)
print("Outside temp: %.2f F" % out_temp)
print("Outside RH: %.2f %%" % out_rh)
print("\n")
if in_temp > out_temp:
GPIO.output(26, 1) # turn on the fan
aio.send('fan-status', 75)
else:
GPIO.output(26, 0) # turn off the fan
aio.send('fan-status', 25)
time.sleep(10) # wait a few seconds before we loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment