Skip to content

Instantly share code, notes, and snippets.

@robertoloja
Last active December 23, 2017 18:36
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 robertoloja/ee8af09fad1b8824848b7c49f13bf13a to your computer and use it in GitHub Desktop.
Save robertoloja/ee8af09fad1b8824848b7c49f13bf13a to your computer and use it in GitHub Desktop.
Controls when temperature and weight are measured, and inputs measurements into local mongo instance.
#!/usr/bin/python
from pymongo import MongoClient
import Adafruit_MCP3008
import Adafruit_DHT
import time
'''
Weight
'''
CLK = 2
MISO = 3
MOSI = 4
CS = 17
mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)
def measureWeight():
'''
Measures weight.
@return the weight, in pounds.
'''
def weight(x):
'''
Converts ADC reading into pounds.
'''
x = int(x)
# The results of 3 polynomial regressions, on 3 data sets, averaged.
a = 1E-8 * x**4 - 1E-5 * x**3 + 0.0036 * x**2 - 0.1661 * x + 1.5569
b = 1E-8 * x**4 - 7E-6 * x**3 + 0.0007 * x**2 + 0.2831 * x - 6.8611
c = 2E-9 * x**4 - 2E-6 * x**3 + 0.0004 * x**2 + 0.2194 * x - 6.515
return (a + b + c) / 3
count = 0
average = 0
# Compensate for remaining signal flutter.
while count < 10:
values = mcp.read_adc(0)
count += 1
average += values
time.sleep(0.01)
average /= 10
value = int(weight(average))
return value if value >= 0 else 0
'''
Temperature
'''
sensor = Adafruit_DHT.DHT11
def measureTemperature():
'''
Measures temperature and humidity
@return A list of lists, where the latter are [temperature, humidity] for
each sensor.
'''
pins = [10, 25, 20, 21]
readings = [[None, None], [None, None], [None, None], [None, None]]
for i in range(0, len(readings)):
readings[i][0], readings[i][1] = Adafruit_DHT.read_retry(sensor,
pins[i])
return readings
db = MongoClient().sensorData # Establish db connection, fetch sensorData db.
data = db.data # Create or access a collection called data.
hiveInfo = db.hiveInfo
while True:
tempReading = measureTemperature()
temp = [x[0] for x in tempReading if x is not None]
hum = [x[1] for x in tempReading if x is not None]
position = [44, 44] # Start in the center (N.B.: edges are 10 and 80).
# Set hive cluster position, according to temperature readings.
if temp[0] is temp[1]:
position[0] = 44
elif temp[0] > temp[1]:
position[0] = 10
else:
position[0] = 80
if temp[2] is temp[3]:
position[1] = 44
elif temp[2] > temp[3]:
position[1] = 10
else:
position[1] = 80
# Update mongo.
reading = {
'weight': measureWeight(),
'temperature': sum(temp) / len(temp),
'population': hiveInfo.find_one()['population'],
'date': int(time.time()),
'humidity': sum(hum) / len(hum),
'position': position,
'uploaded': False # Is this datum present on Firebase?
}
data.insert_one(reading)
time.sleep(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment