class VibrateSensor(object): """Vibration Sensor""" def __init__(self): from sense_hat import SenseHat self.movement_threshold = 0.05 self.sensor = SenseHat() self.current_reading = self.sensor.get_accelerometer_raw() self.last_reading = self.current_reading def read_sensor(self): """Set last_reading to prevous sensor reading, and read again""" self.last_reading = self.current_reading self.current_reading = self.sensor.get_accelerometer_raw() def motion_detected(self): """Returns True if there has been movement since the last read""" self.read_sensor() x_movement = abs(self.last_reading['x'] - self.current_reading['x']) y_movement = abs(self.last_reading['y'] - self.current_reading['y']) z_movement = abs(self.last_reading['z'] - self.current_reading['z']) if (x_movement > self.movement_threshold) \ or (y_movement > self.movement_threshold) \ or (z_movement > self.movement_threshold): return True else: return False
def updateDisplayRotation(SenseHat, default=0): last_rotation = default while True: x = round(SenseHat.get_accelerometer_raw()['x'], 0) y = round(SenseHat.get_accelerometer_raw()['y'], 0) if x == -1: if last_rotation != 90: last_rotation = 90 SenseHat.set_rotation(90) elif x == 1: if last_rotation != 270: last_rotation = 270 SenseHat.set_rotation(270) elif y == -1: if last_rotation != 180: last_rotation = 180 SenseHat.set_rotation(180) elif y == 1: if last_rotation != 0: last_rotation = 0 SenseHat.set_rotation(0) else: if last_rotation != default: last_rotation = default SenseHat.set_rotation(default) sleep(0.5)
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 run(self): while True: if self.flag == True: sense = SenseHat() acceleration = sense.get_accelerometer_raw() tempData = sense.get_temperature() humidData = sense.get_humidity() pressureData = sense.get_pressure() x = acceleration['x'] y = acceleration['y'] z = acceleration['z'] x = abs(x) y = abs(y) z = abs(z) print("Temperature - ", tempData, "Pressure - ", pressureData, "Humidity - ", humidData) if x > 1 or y > 1 or z > 1: sense.show_letter("!", blue) print("Sending notification...") sen.publishMessage("Alert", humidData) print("Message sent.!") else: sense.clear() print('Please wait for ') sleep(self.rateInSec)
def main(): file_opened = False sense = SenseHat() try: filename = input("Enter the filename\n") sense_file = open(filename, "a") file_opened = True print("Move the pi around") while True: acceleration = sense.get_accelerometer_raw() x = acceleration['x'] y = acceleration['y'] z = acceleration['z'] t1 = ctime(time()) print("{0},{1},{2},{3}".format(x, y, z, t1)) print("{0},{1},{2},{3}".format(x, y, z, t1), file=sense_file) sleep(0.5) except KeyboardInterrupt: print("Exiting...") except PermissionError: #do not have write permissions print("Permission Error") except IsADirectoryError: print("Directory is specified and not a file") except FileNotFoundError: print("File not found") finally: if file_opened: sense_file.close()
def getSensors(): global accel_x, accel_y, accel_z sense = SenseHat() sense.clear() temp_x = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] temp_y = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] temp_z = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] counter = 0 last_time = 0 print("getSensors起動") while True: current_time = round(time.time() * 1000) if current_time - last_time >= 50: last_time = current_time acceleration = sense.get_accelerometer_raw() temp_x[counter] = acceleration['x'] * STANDARD_GRAVITY temp_y[counter] = acceleration['y'] * STANDARD_GRAVITY temp_z[counter] = acceleration['z'] * STANDARD_GRAVITY # temp_x[counter] = round(acceleration['x']*STANDARD_GRAVITY*100000000) # temp_y[counter] = round(acceleration['y']*STANDARD_GRAVITY*100000000) # temp_z[counter] = round(acceleration['z']*STANDARD_GRAVITY*100000000) counter += 1 if (counter >= 10): accel_x = temp_x accel_y = temp_y accel_z = temp_z counter = 0
def main(): sense = SenseHat() sense.set_imu_config(True, True, True) gyro = sense.get_gyroscope_raw() acc = sense.get_accelerometer_raw() comp = sense.get_compass_raw() temp = sense.temp humidity = sense.humidity pressure = sense.pressure data = [{ "id": "gyro", "values": [gyro['x'], gyro['y'], gyro['z']] }, { "id": "acc", "values": [acc['x'], acc['y'], acc['z']] }, { "id": "comp", "values": [comp['x'], comp['y'], comp['z']] }, { "id": "temp", "values": [temp] }, { "id": "humidity", "values": [humidity] }, { "id": "pressure", "values": [pressure] }] print(json.dumps(data))
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
class AccelerationSensor(threading.Thread): def __init__(self, message_queue): threading.Thread.__init__(self) self.sense = SenseHat() self.sense.clear() self.sending = True self.message_queue = message_queue def run(self): while self.sending: acceleration = self.sense.get_accelerometer_raw() x = str(round(acceleration['x'], 2)) y = str(round(acceleration['y'], 2)) z = str(round(acceleration['z'], 2)) dt = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') message = {"timestamp" : dt, "x" : x, "y" : y, "z" : z} json_object = json.dumps(message) topic = "acceleration" queue_object =[ topic, json_object, message] self.message_queue.put(queue_object) time.sleep(cfg.acceleration_freq)
def SenseHatData(conf, dataobj): sense = SenseHat() sense.clear() zero_pressure = sense.get_pressure() while not conf.shutdown: # Adjust ground pressure in case of anomaly if conf.state == "HALT": zero_pressure = zero_pressure * .9 + sense.get_pressure() * .1 # Altimeter data = dataobj.current_data current_pressure = sense.get_pressure() data["sensors"]["alt"] = get_altitude( zero_pressure, sense.get_pressure(), sense.get_temperature()) # meters data["sensors"]["hum"] = sense.get_humidity() # % data["sensors"]["temp"] = (sense.get_temperature() * 9 / 5) + 32 # F data["sensors"]["pres"] = current_pressure conf.data.add_dp(current_pressure - conf.data.last_pressure) conf.data.last_pressure = current_pressure # IMU data["sensors"]["acc"] = sense.get_accelerometer_raw() # Gs data["sensors"]["pitch"] = sense.get_accelerometer()[ "pitch"] # degrees data["sensors"]["yaw"] = sense.get_accelerometer()["yaw"] # degrees data["sensors"]["roll"] = sense.get_accelerometer()["roll"] # degrees data["sensors"]["compass"] = sense.get_compass() # rad/sec data["sensors"]["gyro"] = sense.get_gyroscope_raw() # rad/sec data["sensors"]["mag"] = sense.get_compass_raw() # microteslas
class SenseHAT(Block, EnrichSignals): imu = ObjectProperty(IMUsensor, title='IMU Sensor') version = VersionProperty('0.1.0') def __init__(self): super().__init__() self.hat = None def configure(self, context): super().configure(context) self.hat = SenseHat() self.hat.set_imu_config( self.imu().accel(), self.imu().compass(), self.imu().gyro()) def process_signals(self, signals): data = {} if self.imu().accel(): data['accelerometer'] = self.hat.get_accelerometer_raw() if self.imu().compass(): data['compass'] = self.hat.get_compass_raw() if self.imu().gyro(): data['gyroscope'] = self.hat.get_gyroscope_raw() outgoing_signals = [] for signal in signals: outgoing_signals.append(self.get_output_signal(data, signal)) self.notify_signals(outgoing_signals)
def runDie(self): sense = SenseHat() faces = self.dieFaces.copy() exit = False while exit == False: for event in sense.stick.get_events(): # Check for when the jostick is pressed if event.action == "pressed": if event.direction == "right": exit = True sense.show_message("Back to menu") return acceleration = sense.get_accelerometer_raw() x = acceleration['x'] y = acceleration['y'] z = acceleration['z'] x = abs(x) y = abs(y) z = abs(z) if x > 3 or y > 3 or z > 3: opt = randint(1, 6) sense.set_pixels(faces[opt - 1]) time.sleep(3) sense.clear() else: sense.clear()
class MotionDetector: MAX_DEGREE = 1 MIN_DEGREE = -1 def __init__(self): self.sense = SenseHat() self.x = 0 self.y = 0 self.z = 0 self.orientation = 0 self.acceleration = 0 def update_parameters(self): acc = self.sense.get_accelerometer_raw() self.x = acc['x'] self.y = acc['y'] self.z = acc['z'] x, y, z = self.x, self.y, self.z if z >= 0 and z <= 1 and x <= 1 and x >= -1 and y <= 1 and y >= -1: self.orientation = x self.acceleration = -y def get_parameters(self): return self.x, self.y, self.z, self.orientation, self.acceleration
def gyro(): sense = SenseHat() globals.pitch, globals.roll, globals.yaw = sense.get_accelerometer( ).values() globals.x, globals.y, globals.z = sense.get_accelerometer_raw().values() globals.pitch = round(globals.pitch, 0) globals.roll = round(globals.roll, 0) globals.yaw = round(globals.yaw, 0)
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 menu(): global sense, time1, time2, r, t, m, w, k, a, b, elapsed sense = SenseHat() sense.set_rotation(180) sense.clear() sense.set_pixels(imagemenu) sense.stick.get_events() while True: print (" new game1",a," ",b) y1 = sense.get_accelerometer_raw()['y'] y1 = round(y1, 0) if y1 == -1: sense.show_message("Highscore '%s'"% (h)) sense.set_pixels(imagemenu) for event in sense.stick.get_events(): if event.action == "pressed" and event.direction == "middle": elapsed = timedelta(seconds=0) sense.set_rotation(180) sense.stick.direction_up = move_up sense.stick.direction_down = move_down sense.stick.direction_right = move_right sense.stick.direction_left = move_left x=0 y=0 time1 = datetime.now() print(elapsed, " elapsed and e ", e) while elapsed < e: sense.clear() draw_player() test = draw_enemy(x, y) print("menu nivel1 ",test) if test == 1: new_game() break sleep(0.25) y = y+1 if y > 7: r = randint(0,7) t = randint(0,7) m = randint(0,7) y = 0 x = x+1 if x > 7: w = randint(0,7) k = randint(0,7) x = 0 if elapsed > e: sense.show_message("Next level", scroll_speed=0.05) sense.set_pixels(imagesmile) sleep(1) level_2(x,y) new_game() break if event.action == "pressed" and (event.direction == "up" or event.direction == "down" or event.direction == "left" or event.direction == "right"): return
class SensePublisher: def __init__(self): self.sense = SenseHat() self.sense.clear() self.pub_humidity = rospy.Publisher('sensehat/humidity', Float64, queue_size=10) self.pub_temperature = rospy.Publisher('sensehat/temperature', Float64, queue_size=10) self.pub_pressure = rospy.Publisher('sensehat/pressure', Float64, queue_size=10) self.pub_accelerometer = rospy.Publisher('sensehat/accelerometer', Vector3, queue_size=10) self.pub_gyroscope = rospy.Publisher('sensehat/gyroscope', Vector3, queue_size=10) self.pub_magnetometer = rospy.Publisher('sensehat/magnetometer', Vector3, queue_size=10) self.pub_compass = rospy.Publisher('sensehat/compass', Float64, queue_size=10) self.pub_stick = rospy.Publisher('sensehat/stick', SenseInputEvent, queue_size=10) def publish(self): self.pub_humidity.publish(self.sense.get_humidity()) self.pub_temperature.publish(self.sense.get_temperature()) self.pub_pressure.publish(self.sense.get_pressure()) acceleration = self.sense.get_accelerometer_raw() self.pub_accelerometer.publish( Vector3(acceleration['x'], acceleration['y'], acceleration['z'])) gyroscope = self.sense.get_gyroscope_raw() self.pub_gyroscope.publish( Vector3(gyroscope['x'], gyroscope['y'], gyroscope['z'])) compass = self.sense.get_compass_raw() self.pub_magnetometer.publish( Vector3(compass['x'], compass['y'], compass['z'])) self.pub_compass.publish(self.sense.get_compass()) stickEvents = self.sense.stick.get_events() if len(stickEvents) > 0: event = SenseInputEvent(stickEvents[-1].direction, stickEvents[-1].action) self.pub_stick.publish(event) def turn_off(self): self.sense.clear() def run(self): rospy.init_node('sense_hat', anonymous=True) rate = rospy.Rate(10) # 10hz while not rospy.is_shutdown(): self.publish() rate.sleep()
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 main(): topic = "{}{}".format(TOPIC, DEVICE_LABEL) mqtt_client = mqttClient.Client() while True: ''' Create sense hat object''' sense = SenseHat() acceleration = sense.get_accelerometer_raw() tempData = sense.get_temperature() humidData = sense.get_humidity() pressureData = sense.get_pressure() ''' Obtain acceleration information''' x1 = acceleration['x'] y1 = acceleration['y'] z1 = acceleration['z'] ''' Obtain absolute value to indicate motion''' x = abs(x1) y = abs(y1) z = abs(z1) ''' Send data to sensor object in order to send to email''' sensor.addValue(tempData, pressureData, humidData) print("Sending sensor data...") sen.publishMessage("Updated sensor information", sensor) print("Temperature - ", tempData, "Pressure - ", pressureData, "Humidity - ", humidData) ''' Condition to send intrusion detection information''' if x > 1 or y > 1 or z > 1: sense.show_letter("!", red) print("Sending notification...") sen.publishMessage("Alert", "Intruder Detected") print("Message sent.!") ''' Turn the speaker ON and start playing music''' # pygame.mixer.music.play() # time.sleep(10) # pygame.mixer.music.pause() ''' Create payload by dumping sensor data information in json object and publish''' payload = json.dumps({"Temperature": tempData, "Pressure":pressureData, "Humidity":humidData, "acc_x":x, "acc_y":y, "acc_z":z}) if not connect(mqtt_client, MQTT_USERNAME, MQTT_PASSWORD, BROKER_ENDPOINT, TLS_PORT): return False publish(mqtt_client, topic, payload) time.sleep(5) ''' Clear the information from sense hat''' sense.clear() return True
def AccelTake(): sense = SenseHat() sense.clear acceleration = sense.get_accelerometer_raw() x = acceleration['x'] y = acceleration['y'] z = acceleration['z'] return x, y, z
class ElectronicDie(): def __init__ (self): self.sense = SenseHat() def shake(self): global n acceleration = self.sense.get_accelerometer_raw() x = acceleration['x'] y = acceleration['y'] z = acceleration['z'] vx = abs(x) vy = abs(y) vz = abs(z) time.sleep(0.1) x,y,z = self.sense.get_accelerometer_raw().values() x1 = abs(abs(vx)-abs(x)) y1 = abs(abs(vy)-abs(y)) z1 = abs(abs(vz)-abs(z)) if x1 > 0.5 or y1 > 0.5 or z1 > 0.5: n = random.randint(1,6) if n == 1: self.sense.set_pixels(c.one) if n == 2: self.sense.set_pixels(c.two) if n == 3: self.sense.set_pixels(c.three) if n == 4: self.sense.set_pixels(c.four) if n == 5: self.sense.set_pixels(c.five) if n == 6: self.sense.set_pixels(c.six) else: n = 0 return n def execute(self): while True: self.shake()
def root(): sense = SenseHat() temp1 = sense.get_temperature() temp2 = sense.get_temperature_from_pressure() pressure = sense.get_pressure() north = sense.get_compass() accel_only = sense.get_accelerometer() acc_raw = sense.get_accelerometer_raw() temp = "Temp {:10.4f}".format(temp1) + " {:10.4f}".format(temp2) other = "Pres {:10.4f}".format(pressure) + " Compas {:10.4f}".format(north) acc1 = "p: {pitch}, r: {roll}, y: {yaw}".format(**accel_only) acc2 = "x: {x}, y: {x}, z: {z}".format(**acc_raw) print temp + "\n" + other + "\n" + acc1 + "\n" + acc2 + "\n"
def Start(): sense=SenseHat() rospy.init_node('sense_hat', anonymous=True) #TODO #temp_pub = rospy.Publisher("/sensehat/temperature", Temperature, queue_size= 10) #humidity_pub = rospy.Publisher("/sensehat/humidity", RelativeHumidity, queue_size= 10) pose_pub = rospy.Publisher("/sensehat/pose", Imu, queue_size= 10) compass_pub = rospy.Publisher("/sensehat/compass", MagneticField, queue_size=10) r = rospy.Rate(10) # 10hz while not rospy.is_shutdown(): gyro = Imu() gyro.angular_velocity.x = sense.get_gyroscope()['pitch'] gyro.angular_velocity.y = sense.get_gyroscope()['roll'] gyro.angular_velocity.z = sense.get_gyroscope()['yaw'] gyro.orientation.x = sense.get_orientation_degrees()['pitch'] gyro.orientation.y = sense.get_orientation_degrees()['roll'] gyro.orientation.z = sense.get_orientation_degrees()['yaw'] gyro.linear_acceleration.x = sense.get_accelerometer_raw()['x'] gyro.linear_acceleration.y = sense.get_accelerometer_raw()['y'] gyro.linear_acceleration.z = sense.get_accelerometer_raw()['z'] #rospy.loginfo("Sending IMU data:%s", gyro) r.sleep()
def acceleration(): sense = SenseHat() acceleration = sense.get_accelerometer_raw() date = date_str_with_current_timezone() data = {} data["sensor_id"] = ACCELERATION_ID data["values"] = { "x": acceleration["x"], "y": acceleration["y"], "z": acceleration["z"], } data["values"] = json.dumps(data["values"]) data["date"] = date return data
def getData(onTarget): if (onTarget == False): t = random.randrange(20, 30) h = random.randrange(30, 40) p = random.randrange(1000, 1020) data = createJsonObject(t, h, p) #print(data) return data #ret = db.child(localID).push(data, user['idToken']) #print(ret) elif (onTarget == True): from sense_hat import SenseHat sense = SenseHat() sense.clear() while True: # Take readings from all three sensors t = sense.get_temperature() p = sense.get_pressure() h = sense.get_humidity() # Round the values to one decimal place t = round(t, 1) p = round(p, 1) h = round(h, 1) # Create the message # str() converts the value to a string so it can be concatenated message = "Temperature: " + str(t) + " Pressure: " + str( p) + " Humidity: " + str(h) # Display the scrolling message #sense.show_message(message, scroll_speed=0.05) #print(message) acceleration = sense.get_accelerometer_raw() x = acceleration['x'] y = acceleration['y'] z = acceleration['z'] x = round(x, 0) y = round(y, 0) z = round(z, 0) #print("x={0}, y={1}, z={2}".format(x, y, z)) data = createJsonObject(t, h, p) return data
def main(): sense = SenseHat() color = (255, 0, 0) prev_x = -1 prev_y = -1 while True: acc = sense.get_accelerometer_raw() x = round(limit(-10 * acc['x'] + 3)) y = round(limit(-10 * acc['y'] + 3)) if x != prev_x or y != prev_y: sense.clear() sense.set_pixel(x, y, *color) prev_x = x prev_y = y time.sleep(0.08)
def index(): sense = SenseHat() sense.clear() celcius = round(sense.get_temperature(), 1) fahrenheit = round(1.8 * celcius + 32, 1) humidity = round(sense.get_humidity(), 1) pressure = round(sense.get_pressure(), 1) acceleration = sense.get_accelerometer_raw() x = round(acceleration['x'], 2) y = round(acceleration['y'], 2) z = round(acceleration['z'], 2) return render_template('weather.html', celcius=celcius, fahrenheit=fahrenheit, humidity=humidity, pressure=pressure, x=x, y=y, z=z)
def index(): sense = SenseHat() sense.clear() acceleration = sense.get_accelerometer_raw() celsius = round(sense.get_temperature(), 1) kwargs = dict( celsius=celsius, fahrenheit=round(1.8 * celsius + 32, 1), humidity=round(sense.get_humidity(), 1), pressure=round(sense.get_pressure(), 1), x=round(acceleration['x'], 2), y=round(acceleration['y'], 2), z=round(acceleration['z'], 2), ) return render_template('weather.html', **kwargs)
def set_random_gyroscope_color(): sense = SenseHat() acceleration = sense.get_accelerometer_raw() x = acceleration['x'] y = acceleration['y'] z = acceleration['z'] x = abs(x) y = abs(y) z = abs(z) if x > 1 or y > 1 or z > 1: x = random.choice(c.color_presets) c.color = x return x
def getSensors(): global sensorData sense = SenseHat() sense.clear() while True: sensorData["temprature"] = sense.get_temperature() # sensorData["pressure"] = sense.get_pressure() sensorData["humidity"] = sense.get_humidity() acceleration = sense.get_accelerometer_raw() sensorData["acceleration_x"] = acceleration['x'] sensorData["acceleration_y"] = acceleration['y'] sensorData["acceleration_z"] = acceleration['z'] time.sleep(0.2)
class SenseController: def __init__(self): self.sense = SenseHat() def __enter__(self): self.clear() return self def __exit__(self, type, value, traceback): self.clear() def clear(self): self.sense.clear() def get_data(self): orientation_time = time.time() orientation = self.sense.get_orientation_degrees() compass_time = time.time() compass = self.sense.get_compass_raw() acceleration_time = time.time() acceleration = self.sense.get_accelerometer_raw() return [ # Environmental sensors (time.time(), "humidity", self.sense.get_humidity()), (time.time(), "pressure", self.sense.get_pressure()), (time.time(), "temperature_from_humidity", self.sense.get_temperature()), (time.time(), "temperature_from_pressure", self.sense.get_temperature_from_pressure()), # IMU sensors (orientation_time, "orientation.pitch", orientation['pitch']), (orientation_time, "orientation.roll", orientation['roll']), (orientation_time, "orientation.yaw", orientation['yaw']), (compass_time, "compass.x", compass['x']), (compass_time, "compass.y", compass['y']), (compass_time, "compass.z", compass['z']), (acceleration_time, "accelerometer.x", acceleration['x']), (acceleration_time, "accelerometer.y", acceleration['y']), (acceleration_time, "accelerometer.z", acceleration['z']) ] def show_message(self, message): self.sense.show_message(message, text_colour=[0, 64, 0])
class Acceleration: def __init__(self): self.sense = SenseHat() self.madgwick = MadgwickAHRS(.055, None, 1) def get_acceleration(self): acceleration = self.sense.get_accelerometer_raw() orientation = self.sense.get_orientation_degrees() # print("p: {pitch}, r: {roll}, y: {yaw}".format(**orientation)) ori_pitch = orientation['pitch'] acc_x = acceleration['x'] print("acceleration before compensation: {:.4f}".format(acc_x)) def get_quaternion(self): ninedofxyz = read_sensors() # Get data from sensors madgwick.update(ninedofxyz[0], ninedofxyz[1], ninedofxyz[2]) # Update self.ahrs = madgwick.quaternion.to_euler_angles()
def glitter(): glitterOn = True sense = SenseHat() sense.set_imu_config(False, False, True) sense.clear() colours = [ "yellow", "blue", "red", "pink", "green", "orange", "violet", "purple", "gold" ] my_colour = random.choice(colours) while glitterOn == True: image = [] for i in range(64): shade = randomShade(my_colour) image.append(shade) sense.set_pixels(image) time.sleep(0.1) ac = sense.get_accelerometer_raw() x = ac["x"] y = ac["y"] z = ac["z"] shake = x * x + y * y + z * z if shake > 5.0: my_colour = random.choice(colours) for event in sense.stick.get_events(): if event.action == "pressed": if event.direction == "middle": glitterOn = False sense.clear()
class Sensor: ''' Class responsible for getting raw sensor data from Sense HAT sense: SenseHat instance of Sense HAT ''' def __init__(self): self.sense = SenseHat() def getData(self): ''' returns the most recent data from Sense HAT ''' accel = self.sense.get_accelerometer_raw() gyro = self.sense.get_orientation() temp = self.sense.get_temperature() pressure = self.sense.get_pressure() return SensorData(datetime.now(), accel['x'], accel['y'], accel['z'], gyro['pitch'], gyro['roll'], gyro['yaw'], temp, pressure)
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
start = time.time() current = time.time() i = 0 video = 0 #SET MAX LOG DURATION IN SECONDS while (current-start) < 5: current = time.time() t = sense.get_temperature() p = sense.get_pressure() h = sense.get_humidity() pitch, roll, yaw = sense.get_orientation().values() xc, yc, zc = sense.get_compass_raw().values() xg, yg, zg = sense.get_gyroscope_raw().values() xa, ya, za = sense.get_accelerometer_raw().values() f = open('./hat-log/hat.csv', 'a', os.O_NONBLOCK) line = "%d, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f\n" % (1000*time.time(),t,p,h,pitch,roll,yaw,xc,yc,zc,xg,yg,zg,xa,ya,za) f.write(line) f.flush f.close() #set za threshold to the number of g you would expect at launch if video == 0 and (za > 1.1 or za < -1.1): video = 1 call(["./video", ""]) #print i i = i+1
#!/usr/bin/env python from sense_hat import SenseHat sense = SenseHat() sense.show_letter("J") while True: x = sense.get_accelerometer_raw()['x'] y = sense.get_accelerometer_raw()['y'] z = sense.get_accelerometer_raw()['z'] x = round(x, 0) y = round(y, 0) if x == -1: sense.set_rotation(180) elif y == 1: sense.set_rotation(90) elif y == -1: sense.set_rotation(270) else: sense.set_rotation(0)
class sensors(Thread): def __init__(self): Thread.__init__(self) self.daemon=True self.pitch = 0 self.roll = 0 self.yaw = 0 self.compass= 10 self.temp = 0 self.humidity = 0 self.pressure = 0 self.ax = 0 self.ay = 0 self.az = 0 self.altitude = 0 # Comment if not running on RPI self.sense = SenseHat() self.sense.clear() self.sense.set_imu_config(True, True, True) def joinDelimiter(self, arr): tmp=[None]*len(arr) for i in range(len(arr)): tmp[i]=str(arr[i]) return ",".join(tmp) def getRandomStrArr(self): pitch = r.randint(3, 5) roll = r.randint(3, 5) yaw = r.randint(0, 2) compass = r.randint(240, 241) temp = r.randint(19, 20) humidity = r.randint(43, 46) pressure = r.randint(983, 985) ax = 0.1 ay = 0.1 az = 0.1 altitude = 286 return self.joinDelimiter([pitch, roll, yaw, compass, temp, humidity, pressure, ax, ay, az, altitude]) def run(self): while True: self.temp = round(self.sense.get_temperature(), 1) self.humidity = round(self.sense.get_humidity(), 1) self.pressure = round(self.sense.get_pressure(), 2) self.sense.set_imu_config(True, True, True) pitch, yaw, roll = self.sense.get_orientation().values() ax, ay, az = self.sense.get_accelerometer_raw().values() self.compass = round(self.sense.get_compass(), 2) self.pitch = round(pitch, 2) self.roll = round(roll, 2) if (self.pitch > 180): self.pitch -= 360 if (self.roll > 180): self.roll -= 360 self.yaw = round(yaw, 2) self.ax = round(ax, 2) self.ay = round(ay, 2) self.az = round(az, 2) self.altitude = round((288.15 / -0.0065) * ((self.pressure * 100 / 101325) ** (-(8.31432 * -0.0065) / (9.80665 * 0.0289644)) - 1),2) """ self.pitch = r.randint(3, 5) self.roll = r.randint(3, 5) self.yaw = r.randint(0, 2) self.compass = r.randint(240, 241) self.temp = r.randint(19, 20) self.humidity = r.randint(43, 46) self.pressure = r.randint(983, 985) self.ax = 0.1 self.ay = 0.1 self.az = 0.1 self.altitude = 286 """ time.sleep(REFRESH_DELAY) def getStrArr(self): return self.joinDelimiter([self.pitch, self.roll, self.yaw, self.compass, self.temp, self.humidity, self.pressure, self.ax, self.ay, self.az, self.altitude]) def getTuple(self): return (self.getStrArr(),'')
e, e, e, r, r, e, e, e, e, e, r, r, r, r, e, e, e, r, e, r, r, e, r, e, r, e, e, r, r, e, e, r, e, e, e, r, r, e, e, e, e, e, e, r, r, e, e, e, e, e, e, r, r, e, e, e, e, e, e, r, r, e, e, e ] # Print it once sh.set_pixels(arrow) while True: # Below works with Rasbian's Python 3.4.2 AND 2.7.9 raw = sh.get_accelerometer_raw() x=round(raw['x'], 0) y=round(raw['y'], 0) z=round(raw['z'], 0) # Not really needed, except for perhaps debugging # Below works with Rasbian's Python 3.4.2 AND 2.7.9 #print ("x=%s, y=%s, z=%s" % (raw['x'],raw['y'],raw['z'])) # Depending on which x or y axis is pointing up or down # Rotate the "arrow" (set_pixels, above) to point up # Assumes earth-gravity if x == -1: sh.set_pixels(arrow) sh.set_rotation(90)
def program (): sense = SenseHat() pygame.init() s = (pygame.mixer.music.load ("Alien_AlarmDrum.wav")) print(s) r = [255, 0, 0] o = [255, 127, 0] w = [255, 255, 0] g = [0, 255, 0] b = [0, 0, 255] i = [75, 0, 130] v = [159, 0, 255] e = [0, 0, 0] vermelho = [ e,e,e,r,r,e,e,e, e,e,e,r,r,e,e,e, e,e,e,r,r,e,e,e, e,e,e,r,r,e,e,e, r,e,e,r,r,e,e,r, e,r,e,r,r,e,r,e, e,e,r,r,r,r,e,e, e,e,e,r,r,e,e,e, ] vermelho_diagonal = [ r,e,e,e,e,e,e,e, e,r,e,e,e,e,e,e, e,e,r,e,e,e,e,e, e,e,e,r,e,e,e,r, e,e,e,e,r,e,e,r, e,e,e,e,e,r,e,r, e,e,e,e,e,e,r,r, e,e,e,r,r,r,r,r, ] laranja_diagonal = [ o,e,e,e,e,e,e,e, e,o,e,e,e,e,e,e, e,e,o,e,e,e,e,e, e,e,e,o,e,e,e,o, e,e,e,e,o,e,e,o, e,e,e,e,e,o,e,o, e,e,e,e,e,e,o,o, e,e,e,o,o,o,o,o, ] laranja = [ e,e,e,o,o,e,e,e, e,e,e,o,o,e,e,e, e,e,e,o,o,e,e,e, e,e,e,o,o,e,e,e, o,e,e,o,o,e,e,o, e,o,e,o,o,e,o,e, e,e,o,o,o,o,e,e, e,e,e,o,o,e,e,e, ] green = [ g,g,g,g,g,g,g,g, g,g,g,g,g,g,g,g, g,g,g,g,g,g,g,g, g,g,g,g,g,g,g,g, g,g,g,g,g,g,g,g, g,g,g,g,g,g,g,g, g,g,g,g,g,g,g,g, g,g,g,g,g,g,g,g, ] def musica(): pygame.mixer.music.load("Alien_AlarmDrum.wav") pygame.mixer.music.play(0) while True: x = sense.get_accelerometer_raw()['x'] y = sense.get_accelerometer_raw()['y'] z = sense.get_accelerometer_raw()['z'] x = round(x, 1) y = round(y, 1) z = round(z, 1) print("pitch={0}, roll={1}, yaw={2}".format(x,y,z)) if x == 0 and y <= -0.5 and z <= 0.5 and z != 1: sense.set_rotation(180) sense.set_pixels(vermelho) musica() elif x == 0 and y >= -0.5 and z >= 0.5 and z != 1 and y < 0: sense.set_rotation(180) sense.set_pixels(laranja) #(seta para baixo) elif x <= -0.5 and y == 0 and z <= 0.5 : sense.set_rotation(90) sense.set_pixels(vermelho) musica() elif x >= -0.5 and y == 0 and z >=0.5 and x < 0 and z != 1: sense.set_rotation(90) sense.set_pixels(laranja) #(seta para direita) elif x >= 0.5 and y == 0 and z <= 0.5: sense.set_rotation(270) sense.set_pixels(vermelho) musica() elif x <= 0.5 and y == 0 and z >= 0.5 and x > 0 and z != 1: sense.set_rotation(270) sense.set_pixels(laranja) #(seta para esquerda) elif x == 0 and y >= 0.5 and z <= 0.5: sense.set_rotation(0) sense.set_pixels(vermelho) musica() elif x == 0 and y <= 0.5 and z >= 0.5 and y > 0 and z != 1: sense.set_rotation(0) sense.set_pixels(laranja) #(seta para cima) elif x <= -0.5 and y <= -0.5 and z <= 0.5: sense.set_rotation(180) sense.set_pixels(vermelho_diagonal) musica() elif x >= -0.3 and y <= -0.8 and z >= -0.1 and z <= 0.1 and x < 0: sense.set_rotation(180) sense.set_pixels(laranja_diagonal) elif x <= -0.8 and y >= -0.3 and z >= -0.1 and z <= 0.1 and y < 0: sense.set_rotation(180) sense.set_pixels(laranja_diagonal) elif x >= -0.5 and y >= -0.5 and z >= 0.5 and x < 0 and y < 0 and z != 1: sense.set_rotation(180) sense.set_pixels(laranja_diagonal) #(seta canto inferior direito) elif x <= -0.5 and y >= 0.5 and z <= 0.5: sense.set_rotation(90) sense.set_pixels(vermelho_diagonal) musica() elif x <= -0.8 and y <= 0.3 and z >= -0.1 and z <= 0.1 and y > 0: sense.set_rotation(90) sense.set_pixels(laranja_diagonal) elif x >= -0.5 and y <= 0.5 and z >= 0.5 and x < 0 and y > 0 and z != 1: sense.set_rotation(90) sense.set_pixels(laranja_diagonal) elif x >= -0.3 and y >= 0.8 and z >= -0.1 and z <= 0.1 and x < 0: sense.set_rotation(90) sense.set_pixels(laranja_diagonal) #(seta canto superior direito) elif x >= 0.5 and y >= 0.5 and z <= 0.5: sense.set_rotation(0) sense.set_pixels(vermelho_diagonal) musica() elif x <= 0.5 and y <= 0.5 and z >= 0.5 and x > 0 and y > 0 and z != 1: sense.set_rotation(0) sense.set_pixels(laranja_diagonal) elif x <= 0.3 and y >= 0.8 and z >= -0.1 and z <= 0.1 and x > 0: sense.set_rotation(0) sense.set_pixels(laranja_diagonal) elif x >= 0.8 and y <= 0.3 and z >= -0.1 and z <= 0.1 and y > 0: sense.set_rotation(0) sense.set_pixels(laranja_diagonal) #(seta canto superior esquerdo) elif x >= 0.5 and y <= -0.5 and z <= 0.5: sense.set_rotation(270) sense.set_pixels(vermelho_diagonal) musica() elif x <= 0.5 and y >= -0.5 and z >= 0.5 and x > 0 and y < 0 and z != 1: sense.set_rotation(270) sense.set_pixels(laranja_diagonal) elif x >= 0.8 and y >= -0.3 and z >= -0.1 and z <= 0.1 and y < 0: sense.set_rotation(270) sense.set_pixels(laranja_diagonal) elif x <= 0.3 and y <= -0.8 and z >= -0.1 and z <= 0.1 and x > 0: sense.set_rotation(270) sense.set_pixels(laranja_diagonal) #(seta canto inferior esquerdo) elif x == 0 and y == 0 and z == 1: sense.set_rotation(180) sense.set_pixels(green)
from sense_hat import SenseHat sh = SenseHat() while True: print([sh.get_accelerometer_raw()[key] for key in ['x', 'y', 'z']])
class Accelerometer(Thread): def __init__(self, quantum, bin_logger): Thread.__init__(self) self.daemon = True self.Sense = SenseHat() self.Sense.set_imu_config(False, False, True) self.cnt = 0 self.quantum = quantum self.period = 0.01 self.iters = int(self.quantum / self.period) self.que = Queue(1024) self.dorun = True self.acc_offset = 0 self.bin_logger = bin_logger def run(self): print("Calibrating...") self.adjust() print("Calibration done!") while (self.dorun): i = self.iters max = -1000000000.0 min = 1000000000.0 sum = 0.0 acc_first = self.read_acc() while (i > 0): rd = self.read_acc() av = self.get_adj_len() sum = sum + av if (max < av): max = av acc_max = rd acc_max_i = (self.iters - i) if (min > av): min = av acc_min = rd acc_min_i = (self.iters - i) i = i - 1 time.sleep acc_last = self.read_acc() ruck_avg = sqrt(pow(acc_first['x']-acc_last['x'], 2)+pow(acc_first['y']-acc_last['y'], 2)+pow(acc_first['z']-acc_last['z'], 2))/self.quantum ruck_max = sqrt(pow(acc_max['x']-acc_min['x'], 2)+pow(acc_max['y']-acc_min['y'], 2)+pow(acc_max['z']-acc_min['z'], 2))/(abs(acc_min_i-acc_max_i)*self.period) acc_dic = {'avg': (sum/float(self.iters)), 'min': min, 'max': max} ruck_dic = {'avg': ruck_avg, 'max': ruck_max} self.que.put([dt.datetime.now().strftime('%Y%m%d %H:%M.%S.%f'), acc_dic, ruck_dic, acc_first, acc_last]) time.sleep(self.period) def writeBinLog(self, entry): if (self.bin_logger == None): return else: self.bin_logger.putNext([dt.datetime.now().strftime('%Y%m%d %H:%M.%S.%f'), entry]) def adjust(self): ac = 0.0 for i in range(0,100): rd = self.read_acc() av = self.get_len() ac += av self.acc_offset = ac/100.0 self.acc_offset *= 1.02 def read_acc(self): a1 = self.Sense.get_accelerometer_raw() self.writeBinLog(a1) self.acc = a1 return a1 def get(self): return [self.get_x(), self.get_y(), self.get_z()] def get_x(self): return self.acc['x'] def get_y(self): return self.acc['y'] def get_z(self): return self.acc['z'] def get_len(self): self.Length = sqrt(pow(self.get_x(),2) + pow(self.get_y(),2) + pow(self.get_z(),2)) return self.Length def get_adj_len(self): return self.get_len()-self.acc_offset def report(self): print(self.get_x()) print(self.get_y()) print(self.get_z()) print(self.get()) print(self.get_len()) def stopit(self): self.dorun = False def getNext(self): try: return self.que.get(True, timeout=5) except: print("Exception") def read_queue(self): yield self.que.get(True, None)
w, w, w, b, b, w, w, w, w, w, w, b, b, w, w, w, b, l, b, l, b, l, b, b, b, l, b, l, b, l, b, b, b, l, b, l, b, l, b, b, b, l, b, l, b, l, b, b, w, l, l, l, l, l, b, w, w, w, w, b, b, w, w, w, ] # create a list of the letters to choose from letters = [nun, gimmel, hey, shin] # our main code loop to run forever while True: x, y, z = sense.get_accelerometer_raw().values() # capture the data from the accelerometer in x, y, and z coordinates x = abs(x) # make the coordinates positive numbers y = abs(y) # with absolute value, the distance z = abs(z) # between a number and zero if x > 2 or y > 2 or z > 2: # check to see if the Raspberry Pi was shaken for a in range(10): # scroll through the letters 10 times sense.set_pixels(nun) sleep(.07) sense.set_pixels(gimmel) sleep(.07) sense.set_pixels(hey) sleep(.07) sense.set_pixels(shin) sleep(.07) result = choice(letters) # choose a random letter sense.set_pixels(result) # display the random letter
# init_pitch, init_roll, init_yaw = sense.get_orientation().values() # while True: # pitch, roll, yaw = sense.get_orientation().values() # print("pitch=%s, roll=%s, yaw=%s" % (pitch-init_pitch,yaw-init_yaw,roll-init_roll)) ##### Displacement detection from sense_hat import SenseHat sense = SenseHat() import time current_milli_time = lambda: int(round(time.time() * 1000)) f_x, f_y, f_z = sense.get_accelerometer_raw().values() lasttime = current_milli_time() f_x=round(f_x, 3) f_y=round(f_y, 3) f_z=round(f_z, 3) init_x = f_x init_y = f_y init_z = f_z alpha = 0.1 vx = 0 vy = 0 vz = 0
from sense_hat import SenseHat camera = PiCamera() sense = SenseHat() i = 0 def busted(): sense.show_message("BUSTED!!",scroll_speed=0.05, text_colour=[255, 0, 0], back_colour=[255, 255, 255]) def hiboss(): sense.clear() sense.show_message("HI BOSS ;)",scroll_speed=0.08, text_colour=[0, 0, 255]) event = sense.stick.wait_for_event() while True: acceleration = sense.get_accelerometer_raw() a = acceleration['x'] b= acceleration['y'] c = acceleration['z'] a = abs(a) b = abs(b) c = abs(c) if a > 1 or b > 1 or c > 1: camera.capture('/home/pi/Desktop/imagens/image%s.gif' % i) busted() i = i + 1 login, password = '******', 'supersenha2017' recipients = [login]
running = False # No data being recorded (yet) try: print('Press the Joystick button to start recording.') print('Press it again to stop.') while True: # capture all the relevant events from joystick r,w,x=select([js.fd],[],[],0.01) for fd in r: for event in js.read(): # If the event is a key press... if event.type==ecodes.EV_KEY and event.value==1: # If we're not logging data, start now if event.code==ecodes.KEY_ENTER and not running: running = True # Start recording data sh.clear(0,255,0) # Light up LEDs green # If we were already logging data, stop now elif event.code==ecodes.KEY_ENTER and running: running = False gentle_close() # If we're logging data... if running: # Read from acceleromter acc_x,acc_y,acc_z = [sh.get_accelerometer_raw()[key] for key in ['x' ,'y','z']] # Format the results and log to file logging.info('{:12.10f}, {:12.10f}, {:12.10f}'.format(acc_x,acc_y,ac c_z)) print(acc_x,acc_y,acc_z) # Also write to screen except: # If something goes wrong, quit gentle_close()
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 Accelerometer(Thread): def __init__(self, quantum, bin_logger): Thread.__init__(self) self.daemon = True self.Sense = SenseHat() self.Sense.set_imu_config(False, False, True) self.cnt = 0 self.quantum = quantum self.period = 0.01 self.iters = int(self.quantum / self.period) self.que = Queue(1024) self.dorun = True self.acc_bias = [0.0, 0.0, 0.0] self.Rmtx = IDmtx self.bin_logger = bin_logger # # Lambdas # self.l_len = lambda x: self.calcLen2d(x) def run(self): print("Calibrating...") self.adjust() print("Calibration done! adjust={}".format(self.acc_bias)) print("quantum={} period={} iters={}".format(self.quantum, self.period, self.iters)) acc_first = self.read_acc() while (self.dorun): i = self.iters sum = 0.0 acc_list = [] while (i > 0): adj = self.adjAcc(acc_first) acc_list.append(adj) i = i - 1 time.sleep(self.period) acc_first = self.read_acc() acc_len_list = map(self.l_len, acc_list) max = reduce(l_max, acc_len_list) min = reduce(l_min, acc_len_list) sum = reduce(l_sum, acc_len_list) avg = sum/float(len(acc_list)) sdev = sqrt(reduce(lambda x,y: x+pow((y-avg), 2.0), acc_len_list, 0)/(len(acc_list)-1.0)) ruc_len_list = map(lambda x,y: (x-y)/self.period,acc_len_list[1:], acc_len_list[:-1]) ruck_max = reduce(l_max, ruc_len_list) ruck_min = reduce(l_min, ruc_len_list) ruck_sum = reduce(l_sum, ruc_len_list) ruck_avg = ruck_sum/float(len(ruc_len_list)) ruck_sdev = sdev = sqrt(reduce(lambda x,y: x+pow((y-ruck_avg), 2.0), ruc_len_list, 0)/(len(ruc_len_list)-1.0)) ruck_tot_avg = sqrt(pow(acc_list[0][0]-acc_list[-1][0], 2)+pow(acc_list[0][1]-acc_list[-1][1], 2)+pow(acc_list[0][2]-acc_list[-1][2], 2))/self.quantum acc_dic = {'avg': avg, 'min': min, 'max': max, 'sdev': sdev} ruck_dic = {'avg': ruck_avg, 'min': ruck_min, 'max': ruck_max, 'sdev': ruck_sdev, 'tot_avg': ruck_tot_avg} self.que.put([dt.datetime.now().strftime('%Y%m%d %H:%M.%S.%f'), acc_dic, ruck_dic, acc_list[0], acc_list[-1]]) def writeBinLog(self, entry): if (self.bin_logger == None): return else: self.bin_logger.putNext([dt.datetime.now().strftime('%Y%m%d %H:%M.%S.%f'), entry]) def adjust(self): ac = 0.0 x = 0.0 y = 0.0 z = 0.0 for i in range(0,100): rd = self.read_acc() x += rd[0] y += rd[1] z += rd[2] time.sleep(0.001) self.acc_bias = [x/100.0, y/100.0, z/100.0] def read_acc(self): a1 = self.Sense.get_accelerometer_raw() self.writeBinLog(a1) return [a1['x'], a1['y'], a1['z']] def get(self): return [self.get_x(), self.get_y(), self.get_z()] def calcLen(self, acc): return sqrt(pow(acc[0], 2) + pow(acc[1], 2) + pow(acc[2], 2)) def calcLen2d(self, acc): return sqrt(pow(acc[0], 2) + pow(acc[1], 2)) def adjAcc(self, acc): return [acc[0]-self.acc_bias[0], acc[1]-self.acc_bias[1], acc[0]+(Gdelta-self.acc_bias[0])] def stopit(self): self.dorun = False def getNext(self): try: return self.que.get(True, timeout=15) except: print("Exception") def read_queue(self): yield self.que.get(True, None)
#setup the sense HAT from sense_hat import SenseHat hat = SenseHat() while True: #get acceleration data in G's acceleration = hat.get_accelerometer_raw() #round values to 1.d.p. acceleration['x'] = round(acceleration['x'], 1) acceleration['y'] = round(acceleration['y'], 1) acceleration['z'] = round(acceleration['z'], 1) print(acceleration)
arrow = [ e,e,e,w,w,e,e,e, e,e,w,w,w,w,e,e, e,w,e,w,w,e,w,e, w,e,e,w,w,e,e,w, e,e,e,w,w,e,e,e, e,e,e,w,w,e,e,e, e,e,e,w,w,e,e,e, e,e,e,w,w,e,e,e ] # Print it once sh.set_pixels(arrow) while True: x_full, y_full, z_full = sh.get_accelerometer_raw().values() x=round(x_full, 0) y=round(y_full, 0) z=round(z_full, 0) print ("x=%s, y=%s, z=%s" % (x_full,y_full,z_full)) if x == -1: # works sh.set_pixels(arrow) sh.set_rotation(180) elif x == 1: # works sh.set_pixels(arrow) sh.set_rotation(0) elif y == 1:
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)
# Convert degrees to radians (needed for sin(), cos()) pitch_rad = math.radians(pitch) roll_rad = math.radians(roll) # Estimate a_gx, a_gy, a_gz from Pi's orientation a_gx = 1 * math.sin(roll_rad) a_gy = 1 * (-math.sin(pitch_rad)) a_gz = 1 * math.cos(pitch_rad) * math.cos(roll_rad) # Round measurements a_gx = round(a_gx,5) a_gy = round(a_gy,5) a_gz = round(a_gz,5) # Get Pi's acceleration from accelerometer a_x, a_y, a_z = sense.get_accelerometer_raw().values() # Round measurements a_x = round(a_x,5) a_y = round(a_y,5) a_z = round(a_z,5) # Compute user acceleration A_x = a_x-a_gx A_y = a_y-a_gy A_z = a_z-a_gz # Round measurements A_x = round(A_x,0) A_y = round(A_y,0) A_z = round(A_z,0)
from sense_hat import SenseHat from time import strftime import datetime sense=SenseHat() #sense.show_message("running sensors",scroll_speed=0.01) print('#Time,pitch(deg),roll(deg),yaw(deg),X-Acceleration(g),Y-Acceleration(g),Z-Acceleration(g),Pressure(Millibars),Temperature(deg C),Humidity(%)') t0=datetime.datetime.now() while(True): pitch,roll,yaw=(ii if ii <180.0 else ii-360.0 for ii in sense.get_orientation().values())#rotations #print(list(sense.get_orientation().values())) ax,ay,az=sense.get_accelerometer_raw().values() #accelerations p=sense.get_pressure() # pressure t=sense.get_temperature() #temperature h=sense.get_humidity() #humidity delta=datetime.datetime.now()-t0 #print(type(delta)) outputs=(delta.total_seconds(),pitch,roll,yaw,ax,ay,az,p,t,h) print(','.join('{:5.3f}'.format(ii) for ii in outputs))
#!/usr/bin/python from sense_hat import SenseHat sense = SenseHat() while True: x, y, z = sense.get_accelerometer_raw().values() x=round(x, 5) y=round(y, 5) z=round(z, 5) print("modulus(a_tot)==%s" % round(x**2+y**2+z**2,0))
class sensors(): def __init__(self): self.pitch = 0 self.roll = 0 self.yaw = 0 self.heading = 10 self.temp = 0 self.humidity = 0 self.pressure = 0 self.ax = 0 self.ay = 0 self.az = 0 self.altitude = 0 self.send_timer=0 def joinDelimiter(self, arr): tmp=[None]*len(arr) for i in range(len(arr)): tmp[i]=str(arr[i]) return ",".join(tmp) def getRandomStrArr(self): pitch = r.randint(3, 5) roll = r.randint(3, 5) yaw = r.randint(0, 2) compass = r.randint(240, 241) temp = r.randint(19, 20) humidity = r.randint(43, 46) pressure = r.randint(983, 985) ax = 0.1 ay = 0.1 az = 0.1 altitude = 286 return self.joinDelimiter([pitch, roll, yaw, compass, temp, humidity, pressure, ax, ay, az, altitude]) def run(self): # Comment if not running on RPI self.sense = SenseHat() self.sense.clear() self.sense.set_imu_config(True, True, True) while True: self.temp = round(self.sense.get_temperature(), 1) self.humidity = round(self.sense.get_humidity(), 1) self.pressure = round(self.sense.get_pressure(), 1) self.sense.set_imu_config(True, True, True) orientation = self.sense.get_orientation() pitch = orientation['pitch'] roll = orientation['roll'] yaw = orientation['yaw'] ax, ay, az = self.sense.get_accelerometer_raw().values() self.heading = round(self.sense.get_compass(), 1) if (pitch > 180): pitch -= 360 self.pitch = round(pitch, 1) self.roll = round(roll, 1) self.yaw = round(yaw, 1) self.ax = round(ax, 2) self.ay = round(ay, 2) self.az = round(az, 2) self.altitude = round((288.15 / -0.0065) * ((self.pressure * 100 / 101325) ** (-(8.31432 * -0.0065) / (9.80665 * 0.0289644)) - 1),1) """ self.pitch = r.randint(3, 5) self.roll = r.randint(3, 5) self.yaw = r.randint(0, 2) self.compass = r.randint(240, 241) self.temp = r.randint(19, 20) self.humidity = r.randint(43, 46) self.pressure = r.randint(983, 985) self.ax = 0.1 self.ay = 0.1 self.az = 0.1 self.altitude = 286 """ # sensors must initialize try: t=time.time() if(time.time()-self.send_timer>delays.BROWSER): sensors_publisher.send_string("%s %s" % (topic.SENSOR_TOPIC, self.getString())) self.send_timer=t #print(time.time()-t) except: print("sensors error") time.sleep(delays.SENSOR_REFRESH_DELAY) def getString(self): return self.joinDelimiter([self.pitch, self.roll, self.yaw, self.heading, self.temp, self.humidity, self.pressure, self.ax, self.ay, self.az, self.altitude]) # Update values if instance not doint reading with run() def setValues(self,string): self.pitch, self.roll, self.yaw, self.heading, self.temp, self.humidity, \ self.pressure, self.ax, self.ay, self.az, self.altitude = [float(x) for x in string.split(',')] if (self.roll > 180): self.roll=round(self.roll - 360,1)
SH_compass_raw_z = SH_compass_raw.get('z') # Gyro Data #sense.set_imu_config(False,True,False) time.sleep(0.01) # sleep for 10 ms after changing IMU configuration #SH_gyro = sense.get_gyroscope() # orientation of pitch, roll, yaw axes in degrees SH_gyro_raw = sense.get_gyroscope_raw() # rotational velocity of pitch, roll, yaw axes in radians per sec SH_gyro_raw_x = SH_gyro_raw.get('x') SH_gyro_raw_y = SH_gyro_raw.get('y') SH_gyro_raw_z = SH_gyro_raw.get('z') # Accelerometer data #sense.set_imu_config(False,False,True) time.sleep(0.01) # sleep for 10 ms after changing IMU configuration #SH_accel = sense.get_accelerometer() # orientation of pitch, roll, yaw axes in degrees SH_accel_raw = sense.get_accelerometer_raw() # acceleration intensity of pitch, roll, yaw axes in 'G's SH_accel_raw_x = SH_accel_raw.get('x') SH_accel_raw_y = SH_accel_raw.get('y') SH_accel_raw_z = SH_accel_raw.get('z') ## Readings from the BMP180 installed in the sealed box BMP_pressure = BMP_sensor.read_pressure() # value in Pascals BMP_temp = BMP_sensor.read_temperature() # value in degrees C # Altitude readings BMP_prev_alt = BMP_alt # keep the previous altitude reading for comparison later BMP_alt = BMP_sensor.read_altitude() # value in meters ## Readings from the ADC to monitor battery and bus voltages bus_bat = (adc.readADCSingleEnded(3, gain, sps) / 1000) * (3)