def get_sensors(precision): """ get temp, pressure, humidity from the Sense HAT :param precision: Decimal point round precision, e.g. with 3 the results will be 24.054. Default 2 :return: returns a data dictionary """ sense = SenseHat() data = {} data['temperature'] = round(sense.get_temperature(), precision) data['pressure'] = round(sense.get_pressure(), precision) data['humidity'] = round(sense.get_humidity(), precision) data['temperature_h'] = round(sense.get_temperature_from_humidity(), precision) data['temperature_p'] = round(sense.get_temperature_from_pressure(), precision) magnetometer_raw = sense.get_compass_raw() data['magnetometer_x'] = magnetometer_raw['x'] data['magnetometer_y'] = magnetometer_raw['y'] data['magnetometer_z'] = magnetometer_raw['z'] gyroscope_raw = sense.get_gyroscope_raw() data['gyroscope_x'] = gyroscope_raw['x'] data['gyroscope_y'] = gyroscope_raw['y'] data['gyroscope_z'] = gyroscope_raw['z'] accelerometer_raw = sense.get_accelerometer_raw() data['accelerometer_x'] = accelerometer_raw['x'] data['accelerometer_y'] = accelerometer_raw['y'] data['accelerometer_z'] = accelerometer_raw['z'] return data
def get_readings(): sense = SenseHat() humidity = sense.get_humidity() temp_h = sense.get_temperature_from_humidity() temp_p = sense.get_temperature_from_pressure() pressure = sense.get_pressure() return [humidity, temp_h, pressure, temp_p]
def get_data(): conn = sqlite3.connect(dbname) curs = conn.cursor() while True: for row in curs.execute("SELECT * FROM Device"): device_address = None nearby_devices = bluetooth.discover_devices() for mac_address in nearby_devices: if row[1] == bluetooth.lookup_name(mac_address, timeout=5): device_address = mac_address break if device_address is not None: print("Hi {}! Your device ({}) has the MAC address: {}".format( row[0], row[1], device_address)) sense = SenseHat() get_cpu_temp = os.popen("vcgencmd measure_temp").readline() cpu_temp = float( get_cpu_temp.replace("temp=", "").replace("'C\n", "")) temp_h = sense.get_temperature_from_humidity() temp_p = sense.get_temperature_from_pressure() avgtemp = (temp_h + temp_p) / 2 curr_temp = avgtemp - ((cpu_temp - avgtemp) / 1.5) temp = round(curr_temp, 1) humid = sense.get_humidity() sense.show_message("Hi {}! Current Temp is {}*c".format( row[0], temp), scroll_speed=0.05) sense.show_message("Current Humidity is {}%".format( round(humid, 1), ), scroll_speed=0.05) else: print("Looking for device...") conn.close()
def sense_data(): sense = SenseHat() comx, comy, comz = sense.get_compass_raw().values() accx, accy, accz = sense.get_accelerometer_raw().values() gyrox, gyroy, gyroz = sense.get_accelerometer_raw().values() temperature = sense.get_temperature_from_humidity() humidity = sense.get_humidity() pressure = sense.get_pressure() timestamp = datetime.now().isoformat() if accy > 0.1 : drop_flg = 1 else: drop_flg = 0 message = { "deviceid": deviceid, \ "timestamp" : timestamp, \ "temperature" : temperature, \ "humidity" : humidity, \ "pressure" : pressure, \ "comx" : comx, \ "comy" : comy, \ "comz" : comz, \ "gyrox" : gyrox, \ "gyroy" : gyroy, \ "gyroz" : gyroz, \ "accx" : accx, \ "accy" : accy, \ "accz" : accz, \ "drop" : drop_flg } print accx, accy, accz, drop_flg return message
def tempCalibration(): # Get CPU temperature. def get_cpu_temp(): res = os.popen("vcgencmd measure_temp").readline() return float(res.replace("temp=", "").replace("'C\n", "")) # Use moving average to smooth readings. def get_smooth(x): if not hasattr(get_smooth, "t"): get_smooth.t = [x, x, x] get_smooth.t[2] = get_smooth.t[1] get_smooth.t[1] = get_smooth.t[0] get_smooth.t[0] = x return (get_smooth.t[0] + get_smooth.t[1] + get_smooth.t[2]) / 3 sense = SenseHat() t1 = sense.get_temperature_from_humidity() t2 = sense.get_temperature_from_pressure() t_cpu = get_cpu_temp() h = sense.get_humidity() p = sense.get_pressure() # Calculates the real temperature compesating CPU heating. t = (t1 + t2) / 2 t_corr = t - ((t_cpu - t) / 1.5) t_corr = get_smooth(t_corr) return t_corr
def readSensor(self): from sense_hat import SenseHat senseHat = SenseHat() self.humidity = senseHat.get_humidity() self.tempH = senseHat.get_temperature_from_humidity() self.pressure = senseHat.get_pressure() + PRESSURE_OFFSET self.tempP = senseHat.get_temperature_from_pressure() self.mesureTime = time.time()
class Sensor : def __init__(self) : self.sensor_id = "sensor hat" self.fileplace = 'tempplace.conf' self.total_count = 0 self.device_file = "/dev/null" self.sense = SenseHat() self.place = self.readplacename() def reinit(self) : self.__init__() def sensorid(self) : return self.sensor_id def total_count(self) : return self.total_count def placename(self): return self.place def setplacename(self, name): self.place = setplace_db(name) def readplacename(self): self.place = getplace_db() return self.place def read_temp(self): temp = "null" tt = self.sense.get_temperature() th = self.sense.get_temperature_from_humidity() tf = self.sense.get_temperature_from_pressure() tf = float(tt) tf = tf - 10.0 # Fattore di correzione tt = round(tt, 2) tc = round(tf, 2) th = round(th, 2) tf = round(tf, 2) self.total_count += 1 return str(tc) def read_pressure(self): p = self.sense.get_pressure() p = round(p, 2) self.total_count += 1 return str(p) def read_humidity(self): h = self.sense.get_humidity() h = round(h, 2) self.total_count += 1 return str(h) def sensordebug(self): return 'Sense Hat'
class SenseLogger: def __init__(self): self.sense = SenseHat() self.filename = "./logs/Senselogg-" + str(datetime.now()) + ".csv" self.file_setup(self.filename) def write_line(self, line): with open(self.filename, "a") as f: f.write(line + "\n") def log_data(self): sense_data = self.get_sense_data() line = ",".join(str(value) for value in sense_data) self.write_line(line) def file_setup(self, filename): header = [ "datetime", "temp_h", "temp_p", "humidity", "pressure", "pitch", "roll", "yaw", "mag_x", "mag_y", "mag_z", "accel_x", "accel_y", "accel_z", "gyro_x", "gyro_y", "gyro_z" ] with open(filename, "w") as f: f.write(",".join(str(value) for value in header) + "\n") def get_sense_data(self): sense_data = [] sense_data.append(datetime.now()) sense_data.append(self.sense.get_temperature_from_humidity()) sense_data.append(self.sense.get_temperature_from_pressure()) sense_data.append(self.sense.get_humidity()) sense_data.append(self.sense.get_pressure()) o = self.sense.get_orientation() yaw = o["yaw"] pitch = o["pitch"] roll = o["roll"] sense_data.extend([pitch, roll, yaw]) mag = self.sense.get_compass_raw() x = mag["x"] y = mag["y"] z = mag["z"] sense_data.extend([x, y, z]) acc = self.sense.get_accelerometer_raw() x = acc["x"] y = acc["y"] z = acc["z"] sense_data.extend([x, y, z]) gyro = self.sense.get_gyroscope_raw() x = gyro["x"] y = gyro["y"] z = gyro["z"] sense_data.extend([x, y, z]) return sense_data
class SenseLogger: def __init__(self): self.sense = SenseHat() self.filename = "./logs/Senselogg-"+str(datetime.now())+".csv" self.file_setup(self.filename) def write_line(self, line): with open(self.filename, "a") as f: f.write(line + "\n") def log_data(self): sense_data = self.get_sense_data() line = ",".join(str(value) for value in sense_data) self.write_line(line) def file_setup(self, filename): header = ["datetime", "temp_h", "temp_p", "humidity", "pressure", "pitch", "roll", "yaw", "mag_x", "mag_y", "mag_z", "accel_x", "accel_y", "accel_z", "gyro_x", "gyro_y", "gyro_z"] with open(filename, "w") as f: f.write(",".join(str(value) for value in header)+ "\n") def get_sense_data(self): sense_data = [] sense_data.append(datetime.now()) sense_data.append(self.sense.get_temperature_from_humidity()) sense_data.append(self.sense.get_temperature_from_pressure()) sense_data.append(self.sense.get_humidity()) sense_data.append(self.sense.get_pressure()) o = self.sense.get_orientation() yaw = o["yaw"] pitch = o["pitch"] roll = o["roll"] sense_data.extend([pitch, roll, yaw]) mag = self.sense.get_compass_raw() x = mag["x"] y = mag["y"] z = mag["z"] sense_data.extend([x, y, z]) acc = self.sense.get_accelerometer_raw() x = acc["x"] y = acc["y"] z = acc["z"] sense_data.extend([x, y, z]) gyro = self.sense.get_gyroscope_raw() x = gyro["x"] y = gyro["y"] z = gyro["z"] sense_data.extend([x, y, z]) return sense_data
def __calibrateTemperature(self): sense = SenseHat() t1 = sense.get_temperature_from_humidity() t2 = sense.get_temperature_from_pressure() t_cpu = self.__getCPUTemperature() t = (t1 + t2) / 2 t_corr = t - ((t_cpu - t) / 1.5) t_corr = round(t_corr,1) return t_corr
class Sense(): ''' This class has methods to connect and get sensor values from SenseHat ''' def __init__(self): self.clearFlag = False self.sens = SenseHat() print("Sense Hat object successfully created") def clear(self): self.sens.clearFlag = True def get_humidity(self): return self.sens.get_humidity() def get_temperature(self): return self.sens.get_temperature_from_humidity() def get_temperature_from_humidity(self): return self.sens.get_temperature_from_humidity() def get_temperature_from_pressure(self): return self.sens.get_temperature_from_pressure() def get_pressure(self): return self.sens.get_pressure() def show_letter(self, val): self.sens.show_letter(val) def get_light_intensity(self): lit = 0 tim = random.randint(0, 24) if (tim > 10 and tim < 16): lit = random.randint(1075, 107527) else: lit = random.randint(0, 1075) return lit def show_message(self, msg): self.sens.show_message(str(msg))
class Hat(object): ''' `sensed` sensor module for the Raspberry Pi Sense HAT. This module returns a dictionary of all built in sensors. ''' def __init__(self, config: DotMap) -> None: if config.sensed.test is not True: from sense_hat import SenseHat self.sense = SenseHat() def get_data(self) -> dict: # Environmental sensors humid = self.sense.humidity temp = self.sense.temperature temp_h = self.sense.get_temperature_from_humidity() temp_p = self.sense.get_temperature_from_pressure() press = self.sense.pressure # IMU (inertial measurement unit) sensors orient_r = self.sense.orientation_radians orient_d = self.sense.orientation compass = self.sense.compass compass_r = self.sense.compass_raw gyro = self.sense.gyroscope gyro_r = self.sense.gyroscope_raw accel = self.sense.accelerometer accel_r = self.sense.accelerometer_raw return {'environment': {'humidity': humid, 'temperature': temp, 'temperature_h': temp_h, 'temperature_p': temp_p, 'pressure': press}, 'imu': {'orientation_rad': orient_r, 'orientation_deg': orient_d, 'compass': compass, 'compass_r': compass_r, 'gyroscope': gyro, 'gyroscope_r': gyro_r, 'accelerometer': accel, 'accelerometer_raw': accel_r}} def test(self) -> dict: return {'environment': {'humidity': 1, 'temperature': 2, 'temperature_h': 3, 'temperature_p': 4, 'pressure': 5}, 'imu': {'orientation_rad': 6, 'orientation_deg': 7, 'compass': 8, 'compass_r': 9, 'gyroscope': 10, 'gyroscope_r': 11, 'accelerometer': 12, 'accelerometer_raw': 13}}
def getInfoConfig(): sense = SenseHat() info = { "date": time.ctime(), "temp": sense.temp, "humidity": sense.humidity, "temperature_from_humidity": sense.get_temperature_from_humidity(), "temperature_from_pressure": sense.get_temperature_from_pressure(), "pressure": sense.pressure } return json.dumps(info)
class _SenseHat: def __init__(self, board_object, colour=""): self.board = board_object self.colour = colour self.sense = SenseHat() def magnetometer_on(self): self.sense.set_imu_config(True, False, False) # gyroscope only @property def temp_c(self): return (self.sense.get_temperature_from_humidity() + self.sense.get_temperature_from_pressure())/2 @property def pressure(self): return self.sense.pressure @property def humidity(self): return self.sense.humidity def led_all(self, colour): lcd = [] for i in range(0, 64): lcd.append(colour) self.sense.set_pixels(lcd) def led_1(self, colour): self.sense.set_pixel(0, 0, colour) self.sense.set_pixel(0, 1, colour) self.sense.set_pixel(1, 0, colour) self.sense.set_pixel(1, 1, colour) def led_2(self, colour): self.sense.set_pixel(2, 2, colour) self.sense.set_pixel(2, 3, colour) self.sense.set_pixel(3, 2, colour) self.sense.set_pixel(3, 3, colour) def led_3(self, colour): self.sense.set_pixel(4, 4, colour) self.sense.set_pixel(4, 5, colour) self.sense.set_pixel(5, 4, colour) self.sense.set_pixel(5, 5, colour) def led_4(self, colour): self.sense.set_pixel(6, 6, colour) self.sense.set_pixel(6, 7, colour) self.sense.set_pixel(7, 6, colour) self.sense.set_pixel(7, 7, colour) def clear(self): self.sense.clear()
class SenseHatSensor: def __init__(self): self.__sense = SenseHat() def __tempFromHumiditySensor(self): return self.__sense.get_temperature_from_humidity() def __tempFromPressureSensor(self): return self.__sense.get_temperature_from_pressure() def getTemperature(self): return ((self.__tempFromPressureSensor() + self.__tempFromHumiditySensor()) / 2)
def main(): sense = SenseHat() tem_pressure = sense.get_temperature_from_pressure() tem_humidity = sense.get_temperature_from_humidity() tem = (tem_humidity + tem_pressure) / 2 hum = sense.get_humidity() air = sense.get_pressure() print json.dumps({ 'temperature': tem, 'humidity': hum, 'air_pressure': air })
def get_temp(): """Reads current temperature from sensor""" # Initialize SenseHat sense = SenseHat() temp = 0.0 # Check if last measurement exists, used to detect possible measurement error when call the sensor last_temp = -100.0 if os.path.isfile(FILE_PATH): last_temp_f = open(FILE_PATH, "r") last_temp = float(last_temp_f.readline()) last_temp_f.close() tries = 0 # If detected measurement error, tries counter to accept the measurement as valid # Algorithm to adjust impact of the CPU temp on the temperature sensor readings while abs(last_temp - temp) > ERROR_TRESHOLD and tries < TRIES: # We need two continuous measures because first measurement uses to fail p = sense.get_temperature_from_pressure() h = sense.get_temperature_from_humidity() p = sense.get_temperature_from_pressure() h = sense.get_temperature_from_humidity() # Calculates temperature with CPUTemp() as cpu_temp: c = cpu_temp.get_temperature() temp = round(((p + h) / 2) - (c / 7), 1) # Check if possible measurement error and wait 5 seconds to try again if abs(last_temp - temp) > ERROR_TRESHOLD: sleep(WAIT_SECONDS) tries += 1 # If we did a wrong measurement, use the last measurement as current measurement # (if last_temp == -100, first measure from reboot) if (math.isnan(temp) or temp == 0.0 or abs(last_temp - temp) > ERROR_TRESHOLD) and last_temp != -100: update_state(last_temp) # Save measurement and call API to update return last_temp update_state(temp) # Save measurement and call API to update return temp
def read_data(): sense = SenseHat() t1 = sense.get_temperature_from_humidity() t2 = sense.get_temperature_from_pressure() t_cpu = get_cpu_temp() p = sense.get_pressure() h = sense.get_humidity() p = round(p, 1) h = round(h, 1) t = (t1 + t2) / 2 t_corr = t - ((t_cpu - t) / 1.5) t_corr = round(t_corr, 1) return t_corr, p, h
def __init__(self): sense = SenseHat() sense.clear() res = os.popen("vcgencmd measure_temp").readline() temp_cpu = float(res.replace("temp=", "").replace("'C\n", "")) t1 = sense.get_temperature_from_humidity() t2 = sense.get_temperature_from_pressure() temp = (t1 + t2) / 2 correctedTemp = temp - ((temp_cpu - temp) / 1.5) self.__temperature = round(correctedTemp) self.__humidity = round(sense.get_humidity())
def update(self): """Get the latest data from Sense HAT.""" from sense_hat import SenseHat sense = SenseHat() temp_from_h = sense.get_temperature_from_humidity() temp_from_p = sense.get_temperature_from_pressure() t_cpu = get_cpu_temp() t_total = (temp_from_h + temp_from_p) / 2 t_correct = t_total - ((t_cpu - t_total) / 1.5) t_correct = get_average(t_correct) self.temperature = t_correct self.humidity = sense.get_humidity() self.pressure = sense.get_pressure()
def update(self): """Get the latest data from Sense HAT.""" from sense_hat import SenseHat sense = SenseHat() temp_from_h = sense.get_temperature_from_humidity() temp_from_p = sense.get_temperature_from_pressure() t_cpu = get_cpu_temp() t_total = (temp_from_h + temp_from_p) / 2 t_correct = t_total - ((t_cpu - t_total) / 1.5) t_correct = get_average(t_correct) self.temperature = t_correct self.humidity = sense.get_humidity() self.pressure = sense.get_pressure()
class SenseHatCollector(): """ This sets up a custom collector for the SenseHat """ def __init__(self, orientation=False): self.sense = SenseHat() self.orientation = orientation @REQUEST_TIME.time() def collect(self): """ Collect our metrics from the SenseHat """ log.info('collecting metrics') temperature = self.sense.get_temperature() humidity = self.sense.get_humidity() pressure = self.sense.get_pressure() temperature_from_humidity = self.sense.get_temperature_from_humidity() temperature_from_pressure = self.sense.get_temperature_from_pressure() metric = Metric('rpi_sensehat', 'sensehat metric values', 'gauge') metric.add_sample('rpi_sensehat_temperature', value=temperature, labels={'name': 'SenseHat Temperature'}) metric.add_sample( 'rpi_sensehat_temperature_from_humidity', value=temperature_from_humidity, labels={'name': 'SenseHat Temperature from humidity sensor'}) metric.add_sample( 'rpi_sensehat_temperature_from_pressure', value=temperature_from_pressure, labels={'name': 'SenseHat Temperature from pressure sensor'}) metric.add_sample('rpi_sensehat_humidity', value=humidity, labels={'name': 'SenseHat Humidity'}) metric.add_sample('rpi_sensehat_pressure', value=pressure, labels={'name': 'SenseHat Pressure'}) if self.orientation: roll = self.sense.orientation['roll'] yaw = self.sense.orientation['yaw'] pitch = self.sense.orientation['pitch'] metric.add_sample('rpi_sensehat_roll', value=roll, labels={'name': 'SenseHat Roll'}) metric.add_sample('rpi_sensehat_yaw', value=yaw, labels={'name': 'SenseHat Yaw'}) metric.add_sample('rpi_sensehat_pitch', value=pitch, labels={'name': 'SenseHat Pitch'}) yield metric
class SenseClient(object): def __init__(self): self.sense = SenseHat() self.sense.clear() self.sense.set_imu_config(True, True, True) def getSensePoints(self, imperial_or_metric, bucket): dt = datetime.now(tz=pytz.timezone('US/Pacific')).isoformat() point = Point(measurement_name="sense") point.time(time=dt) # % relative point.field("humidity", self.sense.get_humidity()) if imperial_or_metric == "imperial": point.field( "temperature_from_humidity", convertCToF(self.sense.get_temperature_from_humidity())) point.field( "temperature_from_pressure", convertCToF(self.sense.get_temperature_from_pressure())) point.field("pressure", convertmbToPSI(self.sense.get_pressure())) else: point.field("temperature_from_humidity", self.sense.get_temperature_from_humidity()) point.field("temperature_from_pressure", self.sense.get_temperature_from_pressure()) point.field("pressure", self.sense.get_pressure()) point.field("orientation_radians", self.sense.get_orientation_radians()) point.field("orientation_degress", self.sense.get_orientation_degrees()) # magnetic intensity in microteslas point.field("compass_raw", self.sense.get_compass_raw()) # rotational intensity in radians per second point.field("gyroscope_raw", self.sense.get_gyroscope_raw()) # acceleration intensity in Gs point.field("accelerometer_raw", self.sense.get_accelerometer_raw()) return [{"bucket": bucket, "point": point}]
def main(): sense = SenseHat() conditions = get_conditions() if ('current_observation' not in conditions): print "Error! Wunderground API call failed, check your STATE and CITY and make sure your Wunderground API key is valid!" if 'error' in conditions['response']: print "Error Type: " + conditions['response']['error']['type'] print "Error Description: " + conditions['response']['error']['description'] exit() else: print('Connected to Wunderground') while True: # -------------- Sense Hat -------------- #temp_c = sense.get_temperature() #humidity = sense.get_humidity() #pressure_mb = sense.get_pressure() t1 = sense.get_temperature_from_humidity() t2 = sense.get_temperature_from_pressure() t_cpu = get_cpu_temp() humidity = round(sense.get_humidity(),1) p = round(sense.get_pressure(),1) t = (t1+t2)/2 t_corr = t - ((t_cpu-t)/1.5) t_corr = get_smooth(t_corr) temp_f = round(1.8 * round(t_corr, 1) + 32) # -------------- Wunderground -------------- conditions = get_conditions() if ('current_observation' not in conditions): print "Error! Wunderground API call failed. Skipping a reading then continuing ..." else: humidity_pct = conditions['current_observation']['relative_humidity'] o_humidity = float(humidity_pct.replace("%","")) o_temp = float(conditions['current_observation']['temp_f']) wind_mph = float(conditions['current_observation']['wind_mph']) ts = calendar.timegm(time.gmtime()) print("temp=%.1f Outside Temp=%.1f Humidity%1f Outside Humidity=%.1f time=%.1f" % (temp_f, o_temp, humidity, o_humidity, ts)) sense.show_message("Temperature F: " + str(temp_f) + " Humidity: " + str( humidity)) delay_s = 14400 sensor_sn = '0000001' topic = 'myrpi/' + sensor_sn # write to AWS msg1 = '"device_id": "{:s}", "timestamp":"{}", "inside temp": "{}", "outside temp": "{}"'.format(sensor_sn, ts, temp_f, o_temp) msg2 = '"inside humidity":"{}", "outside humidity":"{}","wind":"{}"'.format(humidity, o_humidity, wind_mph) msg = '{'+msg1+','+msg2+'}' myMQTTClient.publish(topic, msg, 1) topic = 'myrpi/' + sensor_sn time.sleep(delay_s)
def set_temp(): sense = SenseHat() time = datetime.now().strftime("%H:%M") humidity = sense.get_humidity() temp = sense.get_temperature_from_humidity() temp_cpu = get_cpu_temp() #calculate the correct temperature temp_correct = temp - ((temp_cpu - temp) / 1.5) logData(temp_correct, humidity) # if temp lower then 20, it will send message via pushbullet to the user if temp_correct < 20: ip_address = os.popen('hostname -I').read() send_notification_via_pushbullet(ip_address, "Please bring your sweater")
def update(self): """Get the latest data from Sense HAT.""" from sense_hat import SenseHat sense = SenseHat() temp_from_h = sense.get_temperature_from_humidity() temp_from_p = sense.get_temperature_from_pressure() t_cpu = get_cpu_temp() t_total = (temp_from_h + temp_from_p) / 2 t_correct = t_total - ((t_cpu - t_total) / 1.5) t_correct = get_average(t_correct) self.temperature = t_correct self.humidity = sense.get_humidity() self.pressure = sense.get_pressure() _LOGGER.debug('Throttle(MIN_TIME_BETWEEN_UPDATES)={}'.format( MIN_TIME_BETWEEN_UPDATES))
def dump_sense_hat_data(): log('getting sense hat data') sense = SenseHat() sense.clear() return { 'timestamp': datetime.utcnow().isoformat() + 'Z', 'provider': 'Sense Hat', 'humidity': sense.get_humidity(), # percent 'pressure': sense.get_pressure(), # millibars 'temperature': c_to_f(sense.get_temperature()), 'temperature_from_humidity': c_to_f(sense.get_temperature_from_humidity()), 'temperature_from_pressure': c_to_f(sense.get_temperature_from_pressure()), }
def getSenseHatData(): sense = SenseHat() t1 = sense.get_temperature_from_humidity() t2 = sense.get_temperature_from_pressure() temp_cpu = get_cpu_temp() humidity = sense.get_humidity() # calculates the real temperature compesating CPU heating t = (t1+t2)/2 temp_corr = t - ((temp_cpu-t)/1.5) temp_corr = get_smooth(temp_corr) if temp_corr is not None: temp_corr = round(temp_corr, 1) if humidity is not None: humidity = round(humidity, 1) logData (temp_corr, humidity)
def runTests(self,resourceName): sense_hat = SenseHat() while True: #generated a random temperture data and created a sensordata object #temperature = random.uniform(0.0,30.0) #humidity = random.uniform(30.0,40.0) #get sensor data from senseHat sensor temperature = sense_hat.get_temperature_from_humidity() humidity = sense_hat.get_humidity() sensorData = str(temperature) +','+ str(humidity) logging.info(sensorData) #post the sensorData to the server response = self.client.post(resourceName, sensorData) sleep(60)
def measure_temp_hum(): # initialize the sense hat object sense = SenseHat() # get the temperature t = sense.get_temperature_from_humidity() # get the cpu temerature t_cpu = get_cpu_temp() # get humidity h = sense.get_humidity() # calculates the real temperature compesating CPU heating t_corr = t - ((t_cpu-t)/1.5) # print("t=%.1f t_cpu=%.1f t_corr=%.1f h=%d p=%d" % (t, t_cpu, t_corr, round(h))) # return both termpreature after correction and humidity return round(t_corr), round(h)
def _read_data(self): sense = SenseHat() sense.show_message('Hello world!') # Float, the percentage of relative humidity humid = round(sense.get_humidity()) # Float, the current temperature in degrees Celsius temp = round(sense.get_temperature_from_humidity()) # Other way to get the temperature from the Sense HAT # temp = round(sense.get_temperature_from_pressure()) # Float, the current pressure in Millibars press = round(sense.get_pressure()) return f'{"temp": {temp}, "humid": {humid}, "press": {press}}'
def get_temp_hum(): # Initialize the sensehat object sense = SenseHat() # Get the temperature t1 = sense.get_temperature_from_humidity() t2 = sense.get_temperature_from_pressure() # Get the CPU temperature t_cpu = environment.get_cpu_temp() # Get humidity h = sense.get_humidity() #p = sense.get_pressure() # Calculates the real temperature compesating CPU heating. t = (t1 + t2) / 2 t_corr = t - ((t_cpu - t) / 1.5) if environment.check_valid_data(t,h)==False: return environment.get_temp_hum return round(t_corr), round(h)
def sensor_active(self): sense = SenseHat() sense.clear() pressure = round(sense.get_pressure(), 2) humidity = round(sense.get_humidity(), 2) temp_humi = round(sense.get_temperature_from_humidity(), 2) temp_press = round(sense.get_temperature_from_pressure(), 2) orien = sense.get_orientation() pitch = round(orien['pitch'], 3) roll = round(orien['roll'], 3) yaw = round(orien['yaw'], 3) self.temp_lcd.display(temp_press) self.humi_lcd.display(humidity) self.pitch_lcd.display(pitch) self.roll_lcd.display(roll) self.yaw_lcd.display(yaw)
def update(self): """Get the latest data from Sense HAT.""" sense = SenseHat() temp_from_h = sense.get_temperature_from_humidity() temp_from_p = sense.get_temperature_from_pressure() t_total = (temp_from_h + temp_from_p) / 2 if self.is_hat_attached: t_cpu = get_cpu_temp() t_correct = t_total - ((t_cpu - t_total) / 1.5) t_correct = get_average(t_correct) else: t_correct = get_average(t_total) self.temperature = t_correct self.humidity = sense.get_humidity() self.pressure = sense.get_pressure()
def notify(): while True: sense = SenseHat() get_cpu_temp = os.popen("vcgencmd measure_temp").readline() cpu_temp = float(get_cpu_temp.replace("temp=","").replace("'C\n","")) temp_h = sense.get_temperature_from_humidity() temp_p = sense.get_temperature_from_pressure() avgtemp = (temp_h+temp_p)/2 curr_temp = avgtemp - ((cpu_temp-avgtemp)/1.5) curr_temp = round(curr_temp, 1) if curr_temp < 20: send_notification_via_pushbullet("Notification", "The current temperature is " + str(curr_temp) + "*C, remember to bring a sweater!") elif 20<= curr_temp <= 30: send_notification_via_pushbullet("Notification", "The current temperature is " + str(curr_temp) + "*C, what a nice weather!") else: send_notification_via_pushbullet("Notification", "The current temperature is " + str(curr_temp) + "*C, wow it's hot today!") time.sleep(60*60*4)
def sensehat(sensor): from sense_hat import SenseHat sense = SenseHat() if (sensor == "mv_sensors"): while True: if (magnetometer == True): sense.set_imu_config(True, False, False) north = sense.get_compass() print("direction {0:.1f}".format(north)) if (gyroscope == True): sense.set_imu_config(False, True, False) gyro_only = sense.get_gyroscope() print("pitch: {pitch}".format(**sense.gyro)) print("yaw: {yaw}".format(**sense.gyro)) print("roll: {roll}".format(**sense.gyro)) if (accelerometer == True): sense.set_imu_config(False, False, True) raw = sense.get_accelerometer_raw() print("ac_x: {x}".format(**raw)) print("ac_y: {y}".format(**raw)) print("ac_z: {z}".format(**raw)) elif (sensor == "temperature"): for x in range(0, 3): t1 = sense.get_temperature_from_humidity() t2 = sense.get_temperature_from_pressure() t = (t1 + t2) / 2 t_cpu = get_cpu_temp() # calculates the real temperature compesating CPU heating t_corr = t - ((t_cpu - t) / 1.6) t_corr = get_smooth(t_corr) mesurement = t_corr elif (sensor == "humidity"): #Approximating from Buck's formula Ha = Hm*(2.5-0.029*Tm) temp = sense.get_temperature() humidity = sense.get_humidity() calchum = humidity * (2.5 - 0.029 * temp) mesurement = calchum elif (sensor == "pressure"): mesurement = sense.get_pressure() return mesurement
#! /usr/bin/env python from sense_hat import SenseHat sense = SenseHat() temp = sense.get_temperature_from_humidity() print("Temperature from humidity sensor: %s C" % temp) temp = sense.get_temperature_from_pressure() print("Temperature from pressure sensor: %s C" % temp)
class PiSenseHat(object): """Raspberry Pi 'IoT Sense Hat API Driver Class'.""" # Constructor def __init__(self): self.sense = SenseHat() # enable all IMU functions self.sense.set_imu_config(True, True, True) # pixel display def set_pixel(self,x,y,color): # red = (255, 0, 0) # green = (0, 255, 0) # blue = (0, 0, 255) self.sense.set_pixel(x, y, color) # clear pixel display def clear_display(self): self.sense.clear() # Pressure def getPressure(self): return self.sense.get_pressure() # Temperature def getTemperature(self): return self.sense.get_temperature() # Humidity def getHumidity(self): return self.sense.get_humidity() def getHumidityTemperature(self): return self.sense.get_temperature_from_humidity() def getPressureTemperature(self): return self.sense.get_temperature_from_pressure() def getOrientationRadians(self): return self.sense.get_orientation_radians() def getOrientationDegrees(self): return self.sense.get_orientation_degrees() # degrees from North def getCompass(self): return self.sense.get_compass() def getAccelerometer(self): return self.sense.get_accelerometer_raw() def getEnvironmental(self): sensors = {'name' : 'sense-hat', 'environmental':{}} return sensors def getJoystick(self): sensors = {'name' : 'sense-hat', 'joystick':{}} return sensors def getInertial(self): sensors = {'name' : 'sense-hat', 'inertial':{}} def getAllSensors(self): sensors = {'name' : 'sense-hat', 'environmental':{}, 'inertial':{}, 'joystick':{}} sensors['environmental']['pressure'] = { 'value':self.sense.get_pressure(), 'unit':'mbar'} sensors['environmental']['temperature'] = { 'value':self.sense.get_temperature(), 'unit':'C'} sensors['environmental']['humidity'] = { 'value':self.sense.get_humidity(), 'unit': '%RH'} accel = self.sense.get_accelerometer_raw() sensors['inertial']['accelerometer'] = { 'x':accel['x'], 'y':accel['y'], 'z': accel['z'], 'unit':'g'} orientation = self.sense.get_orientation_degrees() sensors['inertial']['orientation'] = { 'compass':self.sense.get_compass(), 'pitch':orientation['pitch'], 'roll':orientation['roll'], 'yaw': orientation['yaw'], 'unit':'degrees'} return sensors
class Reading: def __init__(self): # initialize sense hat self.sense = SenseHat() self.sense.clear() def getReading(self): # get temperature from humidity t1 = self.sense.get_temperature_from_humidity() # get temperature from pressure t2 = self.sense.get_temperature_from_pressure() # get cpu temperature t_cpu = self.get_cpu_temp() # average temperature from humidity and pressure t = (t1+t2)/2 # normalize temperature with cpu temperature t_corr = t - ((t_cpu-t)/1.5) # smooth the normalization by averaging t_corr = self.get_smooth(t_corr) # get humidity humidity = self.sense.get_humidity() # get pressure pressure = self.sense.get_pressure() # return data for pushing into iot return { "deviceid": self.getserial(), "humidity": humidity, "pressure": pressure, "temperature": t_corr, "timestamp": int(round(time.time() * 1000)), } # code supplied from http://yaab-arduino.blogspot.com/2016/08/accurate-temperature-reading-sensehat.html # get CPU temperature def get_cpu_temp(self): res = os.popen("vcgencmd measure_temp").readline() t = float(res.replace("temp=","").replace("'C\n","")) return(t) # code supplied from http://yaab-arduino.blogspot.com/2016/08/accurate-temperature-reading-sensehat.html # use moving average to smooth readings def get_smooth(self, x): smoothing = [x,x,x] smoothing[2] =smoothing[1] smoothing[1] = smoothing[0] smoothing[0] = x # average smoothing xs = (smoothing[0]+smoothing[1]+smoothing[2])/3 return(xs) # code supplied from https://www.raspberrypi-spy.co.uk/2012/09/getting-your-raspberry-pi-serial-number-using-python/ def getserial(self): # Extract serial from cpuinfo file cpuserial = "0000000000000000" try: f = open('/proc/cpuinfo','r') for line in f: if line[0:6]=='Serial': cpuserial = line[10:26] f.close() except: cpuserial = "ERROR000000000" return cpuserial
class TemperatureEventEmitter(EventEmitter): def __init__(self, servers, topic, identifier): EventEmitter.__init__(self, servers, topic) self.contents = dict() self.contents["id"] = identifier self.event["@timestamp"] = datetime.utcnow() self.event["data"] = self.contents self.sense = SenseHat() def update_event(self): self.event["@timestamp"] = datetime.utcnow() self.event["data"]["temperature"] = round( (self.sense.get_temperature_from_pressure()+self.sense.get_temperature_from_humidity())/2,1) self.event["data"]["pressure"] = round(self.sense.get_pressure(),1) self.event["data"]["humidity"] = round(self.sense.get_humidity(),1) self.send()
def main(): sense = SenseHat() temp = sense.get_temperature() print "temp_from_temperat:%s" % temp print "temp_from_humidity:%s" % sense.get_temperature_from_humidity() print "temp_from_pressure:%s" % sense.get_temperature_from_pressure()
def execute(self): sense = SenseHat() temp = sense.get_temperature()-ADJUSTMENT temp_hum = sense.get_temperature_from_humidity()-ADJUSTMENT temp_pre = sense.get_temperature_from_pressure()-ADJUSTMENT return dict(temp=temp, temp_hum=temp_hum, temp_pre=temp_pre)
question_mark = [ O, O, O, O, O, O, O, O, O, X, X, O, O, X, X, O, O, X, X, O, O, X, X, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, X, O, O, O, O, X, O, O, O, X, X, X, X, O, O, O, O, O, X, X, O, O, O ] while (1 == 1) : print("%s Temperature" % sense.temp) print("%s Temp - humidity sensor" % sense.get_temperature_from_humidity()) print("%s Temp - pressure sensor" % sense.get_temperature_from_pressure()) print("%s Pressure: in Millibars" % sense.get_pressure()) print("%s Humidity" % sense.get_humidity()) north = sense.get_compass() print("%s Degrees to north" % north) raw = sense.get_accelerometer_raw() print("Acc intensity in Gs x: {x}, y: {y}, z: {z}".format(**raw)) m = '%.1f' % sense.temp sense.show_message(m, text_colour=[255, 0, 0]) print("*********") sense.set_pixels(question_mark) time.sleep(1)
#* set the sampling parameters #* #********************************************* rate = 60 #sample frecuency in seconds samples = 900 #number of samples stabilization = True #Allow for termometer to stabilize report = True #send email at the end of the process? smtpUser = "******" #email account smtpPass = "******" #email password fromAdd = smtpUser toAdd = "recipient" #completion email recipient #initialization read from the sensor. This is neccesary since sometimes the sensors return #a 0 value for pressure on the first read t = round(sense.get_temperature_from_humidity(),1) p = round(sense.get_pressure(),1) h = round(sense.get_humidity(),1) sense.show_letter("W") time.sleep(5) sense.clear() #stabilize temperature readings by waiting 7 min if stabilization: sense.show_letter("W") time.sleep(420) sense.clear() #open the sampling file sensefile = open("sensefile.dat", "w")
while True: sense_data = get_sense_data() if DELAY == 0: log_data() if len(batch_data) >= WRITE_FREQUENCY: print("Writing to file..") with open(filename,"a") as f: for line in batch_data: f.write(line + "\n") batch_data = [] # also write to plotly now = datetime.now() temp = round(sense.get_temperature_from_pressure(), 5) temp2 = round(sense.get_temperature_from_humidity(), 5) point1 = { 'x' : str(now), 'y' : temp } plotly_stream1.write(point1) point2 = { 'x' : str(now), 'y' : temp2 } plotly_stream2.write(point2) plotly_stream.close()
mqttc.tls_set(caPath, certfile=certPath, keyfile=keyPath, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None) mqttc.connect(awshost, awsport, keepalive=60) mqttc.loop_start() while True: message = {} device = {} device['cpuTemperature'] = os.popen('vcgencmd measure_temp').readline().replace("temp=","").replace("'C\n","") environment = {} temp = {} temp['basedOnHumidity'] = sense.get_temperature_from_humidity() temp['basedOnPressure'] = sense.get_temperature_from_pressure() environment['humidity'] = sense.get_humidity() environment['pressure'] = sense.get_pressure() environment['temperature'] = temp message['device'] = device message['environment'] = environment jsonData = json.dumps(message) if connflag == True: mqttc.publish("environmentData", jsonData, qos=1) print jsonData sleep(10)
#HUMIDITY 4 d=humidity = my_weather[0]['humidity'] #RAINFALL 5 e=rainfall = my_weather[0]['rainfall'] #AIRPRESSURE 6 a=air_pressure = my_weather[0]['air_pressure'] #GROUNDTEMP 1 c=ground_temp = my_weather[0]['ground_temp'] #AMBIENTTEMP 2 b=ambient_temp = my_weather[0]['ambient_temp'] f=((sense.get_temperature_from_humidity()+sense.get_temperature_from_pressure())/2) i=0 def move_left (event): if event.action=='pressed': global i i = i-1 print(i) print(event) def move_right (event): if event.action=='pressed': global i i = i+1 print(i)
def getTempValue(self): sense = SenseHat() temp = sense.get_temperature_from_humidity() return str(temp)