def get_sense_hat_data(): sense_hat_data = { 'pressure': 993, 'temperature': 21, 'temperatureFromPressure': 21, 'humidity': 30, 'pitch': 0, 'roll': 0, 'yaw': 0, 'cpuTemp': 46 } if not env.bool('IS_RASPBERRY_PI') or importlib.util.find_spec("sense_hat") is None: return sense_hat_data from sense_hat import SenseHat sense = SenseHat() sense_hat_data['pressure'] = sense.get_pressure() sense_hat_data['temperature'] = sense.get_temperature() sense_hat_data['temperatureFromPressure'] = sense.get_temperature_from_pressure() sense_hat_data['humidity'] = sense.get_humidity() sense_hat_data['pitch'] = sense.get_orientation()['pitch'] sense_hat_data['roll'] = sense.get_orientation()['roll'] sense_hat_data['yaw'] = sense.get_orientation()['yaw'] sense_hat_data['cpuTemp'] = get_cpu_temp() return sense_hat_data
def draw(self): image = Image.open(self.filename) angle = 0 print(self.process_next_frame) sense = SenseHat() #sense.set_rotation(180) sense.set_imu_config(True, True, False) sense.clear() while True: o = sense.get_orientation() pitch = o["pitch"] roll = o["roll"] yaw = o["yaw"] print("RAW - Pitch: {0}, Roll: {1}, Yaw: {2}".format( pitch, roll, yaw)) rollAngle = self.roundToStablize(roll) #rowAngle %= 360 #print("roll: {0}".format(rollAngle)) pitchAngle = self.roundToStablize(pitch) #pitchAngle %= 360 pitchAngle = pitchAngle + 20 # - 90 #center screen with 450 height 225 pitchOffset = (math.tan(math.radians(pitchAngle))) / 0.5 pitchOffsetPx = pitchOffset * 112 #112 px per inch #print("pitch: {0}, offset: {1}, roll: {2}".format(pitchAngle,pitchOffset,rollAngle)) tkimage = ImageTk.PhotoImage(image.rotate(rollAngle)) canvas_obj = self.canvas.create_image(300, 225 + pitchOffsetPx, image=tkimage) self.master.after_idle(self.process_next_frame) yield self.canvas.delete(canvas_obj) time.sleep(0.0009)
def on_press(key): try: print("\n alphanumeric pressed: ", key.char) # pitch, roll, yaw, using accelerometer, gyroscope and magnetometer (for best accuracy) sense = SenseHat() orientation = sense.get_orientation() # create a dictionary with with the following keys: pitch, roll, yaw, command angle_info = { "pitch": orientation["pitch"], "roll": orientation["roll"], "yaw": orientation["yaw"], "command": "stop" } # change the command depending on what keys are pressed on the keyboard if key.char == "f": angle_info["command"] = "forward" if key.char == "b": angle_info["command"] = "backward" if key.char == "l": angle_info["command"] = "left" if key.char == "r": angle_info["command"] = "right" # print to screen all the angle_info values print("\n pitch: ", angle_info["pitch"], "\n roll: ", angle_info["roll"], "\n yaw: ", angle_info["yaw"], "\n command: ", angle_info["command"]) # append angle_info to list angles_list.append(angle_info) except AttributeError: print("special key pressed: ", key)
class OrientationSensor(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: orientation = self.sense.get_orientation() pitch = str(round(orientation["pitch"], 2)) roll = str(round(orientation["roll"], 2)) yaw = str(round(orientation["yaw"], 2)) dt = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') message = {"timestamp" : dt, "pitch" : pitch, "roll" : roll, "yaw" : yaw} json_object = json.dumps(message) topic = "orientation" queue_object = [ topic, json_object, message ] self.message_queue.put(queue_object) time.sleep(cfg.orientation_freq)
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 OrientationTake(): sense = SenseHat() sense.clear() orient = sense.get_orientation() pitch = orient["pitch"] roll = orient["roll"] yaw = orient["yaw"] return pitch, roll, yaw
def smiley(): sense = SenseHat() while True: orientation = sense.get_orientation() roll = orientation['roll'] #print('{:.2f}'.format(roll)) if roll > 70 and roll < 110.0: sense.set_pixels(frown) else: sense.set_pixels(wink)
def senser(): sense = SenseHat() with Pyro4.Proxy("PYRONAME:ROVSyncer") as rov: while rov.run: orientation = sense.get_orientation() rov.sensor = { 'temp': sense.get_temperature(), 'pressure': sense.get_pressure() / 10, 'humidity': sense.get_humidity(), 'pitch': orientation['pitch'], 'roll': orientation['roll'] + 180, 'yaw': orientation['yaw'] }
def start(): sense = SenseHat() sense.clear() ball_color = (255, 255, 255) food_color = (220, 125, 0) b = (0, 0, 0) game_over = False ball_x_position = 7 ball_y_position = 7 hat_grid = [[b, b, b, b, b, b, b, b], [b, b, b, b, b, b, b, b], [b, b, b, b, b, b, b, b], [b, b, b, b, b, b, b, b], [b, b, b, b, b, b, b, b], [b, b, b, b, b, b, b, b], [b, b, b, b, b, b, b, b], [b, b, b, b, b, b, b, b]] num_of_food = 10 make_food(hat_grid, b, food_color, num_of_food) print("Created [" + str(num_of_food) + "] food") score = 0 sense.set_pixels(sum(hat_grid, [])) while not game_over: o = sense.get_orientation() pitch = o["pitch"] roll = o["roll"] yaw = o["yaw"] new_ball_x_position, new_ball_y_position = move_marble( pitch, roll, ball_x_position, ball_y_position) if hat_grid[new_ball_y_position][new_ball_x_position] == food_color: score = score + 1 hat_grid[ball_y_position][ball_x_position] = b hat_grid[new_ball_y_position][new_ball_x_position] = ball_color sense.set_pixels(sum(hat_grid, [])) time.sleep(0.05) ball_y_position = new_ball_y_position ball_x_position = new_ball_x_position if score == num_of_food: game_over = True sense.show_message("You WIN!!")
def orientation(): sense = SenseHat() orientation = sense.get_orientation() date = date_str_with_current_timezone() data = {} data["sensor_id"] = ORIENTATION_ID data["values"] = { "roll": orientation["roll"], "pitch": orientation["pitch"], "yaw": orientation["yaw"], } data["values"] = json.dumps(data["values"]) data["date"] = date return data
class SenseNode: def __init__(self): self.node_rate = 10 self.sense = SenseHat() self.pub = rospy.Publisher('magnetometer_topic', Float32, queue_size=10) # funzione che usa il metodo get_compass della classe SenseHat che restituisce i gradi rispetto al Nord magnetico def sensing(self): self.sense.set_imu_config(True, True, True) o = self.sense.get_orientation() north = o["yaw"] self.pub.publish(north) print("{SENSE_HAT} North: " + str(north))
def main(): sense = SenseHat() data = [[0] * 3, [0] * 3, [0] * 3] count = 0 or_name = ['pitch', 'roll', 'yaw'] while count < 3: orientation = sense.get_orientation() data[0][count] = orientation['pitch'] data[1][count] = orientation['roll'] data[2][count] = orientation['yaw'] sleep(1) count = count + 1 for i in range(0, 3): print(or_name[i]) for j in range(0, 3): print(str(data[i][j]))
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)
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)
class SkyScanner: def __init__(self, transformer: OrientationTransformer): self.sense = SenseHat() self.sense.set_rotation(90) self.transformer = transformer self.polaris = SkyCoord.from_name('polaris') def scan(self): time = Time.now() o = self.sense.get_orientation() pitch = o['pitch'] yaw = o['yaw'] observation = self.transformer.get_sky_coord(pitch, yaw, time) separation = observation.separation(self.polaris) print(separation) if separation.is_within_bounds(upper=Angle(9.9, unit='deg')): self.sense.show_letter(str(math.floor(separation.dms.d)), text_colour=[0, 0, 255]) else: self.sense.clear()
class SenseNode: def __init__(self): self.node_rate = 10 self.sense = SenseHat() self.pub = rospy.Publisher('magnetometer_topic', TwoFloat, queue_size=10) # funzione che usa il metodo get_compass della classe SenseHat che restituisce i gradi rispetto al Nord magnetico def sensing(self): self.sense.set_imu_config(True, True, True) o = self.sense.get_orientation() a = self.sense.get_accelerometer_raw() north = o["yaw"] x = a["x"] y = a["y"] z = a["z"]msg = TwoFloat() # north = self.sense.get_compass() msg.left_us = north if x < 1 and y <1 and z < 1: msg.right_us = 0.0 else: msg.right_us = 1.0 print("{SENSE_HAT} North: " + str(north))
class PiSenseHat: def __init__(self): self.sense = SenseHat() # define sensor object self.measurement = { "timestamp": 0, "temperature": 0, "pressure": 0, "humidity": 0, "acceleration": 0, "orientation": 0 } @staticmethod def round_value(value): return round(value, 3) def round_values(self): for key, value in self.measurement.items(): if key not in ["timestamp"]: if key in ["acceleration", "orientation"]: for sub_key, sub_value in value.items(): self.measurement[key][sub_key] = self.round_value( sub_value) else: self.measurement[key] = self.round_value(value) def get_measurement(self): self.measurement["timestamp"] = str( round(datetime.timestamp(datetime.now()) * 1000)) # rounded ms self.measurement["temperature"] = self.sense.get_temperature() self.measurement["pressure"] = self.sense.get_pressure() self.measurement["humidity"] = self.sense.get_humidity() self.measurement["orientation"] = self.sense.get_orientation() self.measurement["acceleration"] = self.sense.get_accelerometer_raw() self.round_values() def __repr__(self): return json.dumps(self.measurement, indent=4)
def getCurrentReading(): if (not readingSense.value): # flag the sensehat as busy readingSense.value = True # get the new reading sense = SenseHat() orientation = sense.get_orientation() # correct the pitch if (orientation['roll'] <= 90 or orientation['roll'] >= 270): orientation['pitch'] = 360 - orientation['pitch'] else: orientation['pitch'] = orientation['pitch'] - 180 # generate the reading newReading = { 'time' : datetime.now(), 'temperature': round(sense.get_temperature(),1), 'pressure': round(sense.get_pressure(),1), 'humidity': round(sense.get_humidity(),1), 'roll': round(orientation['roll'],1), 'pitch': round(orientation['pitch'], 1), 'yaw': round(orientation['yaw'],1) } # remove all other readings from the currentReading list while (len(currentReading) > 0): currentReading.pop() # save the current reading currentReading.append(newReading) # flag the sensehat as not busy readingSense.value = False if (len(currentReading) > 0): return currentReading[0]; else: return None
def runHat(self): """ Uses the Raspberry Pi Sense Hat """ senseHat = SenseHat() samples = 5 while not self.end: cumPitch = 0 cumRoll = 0 cumYaw = 0 for i in range(samples): orient = senseHat.get_orientation() cumPitch += orient['pitch'] cumRoll += orient['roll'] cumYaw += orient['yaw'] pitch = cumPitch/samples roll = cumRoll/samples yaw = cumYaw/samples while pitch > 180: pitch -= 360 while roll > 180: roll -= 360 while yaw > 180: yaw -= 360 self.pitch = self.lowPass(pitch, self.prevPitch, 50 , 10) self.roll = self.lowPass(roll, self.prevRoll, 50 , 10) self.yaw = self.lowPass(yaw, self.prevYaw, 50 ,10) time.sleep(0.01) self.prevPitch = self.pitch self.prevRoll = self.roll self.prevYaw = self.yaw
def get_sense_data(): sense = SenseHat() # Define list sense_data = [] # Append sensor data sense_data.append(sense.get_temperature_from_humidity()) sense_data.append(sense.get_temperature_from_pressure()) sense_data.append(sense.get_pressure()) sense_data.append(sense.get_humidity()) # Get orientation from sensor yaw,pitch,roll = sense.get_orientation().values() sense_data.extend([pitch,roll,yaw]) # Get magnetic field (compass) mag_x,mag_y,mag_z = sense.get_compass_raw().values() sense_data.extend([mag_x,mag_y,mag_z]) # Get accelerometer values x,y,z = sense.get_accelerometer_raw().values() sense_data.extend([x,y,z]) # Get Gyro values gyro_x,gyro_y,gyro_z = sense.get_gyroscope_raw().values() sense_data.extend([gyro_x,gyro_y,gyro_z]) # Add capture time sense_data.append(datetime.now()) # Add precise time sense_data.append(int(round(time.time()*1000))) return sense_data
key=bytes("alert", encoding='utf-8'), value=bytes(message, encoding='utf-8')) producer.send(device, key=bytes("alert", encoding='utf-8'), value=bytes(message, encoding='utf-8')) elif event.action == oldAction and event.action == 'held' and oldDirection != event.direction: oldDirection = event.direction producer.send('alerts', key=bytes("alert", encoding='utf-8'), value=bytes(message, encoding='utf-8')) oldAction = event.action sense.stick.direction_any = mid while True: readings = {} readings['orentation'] = sense.get_orientation() readings['compass'] = sense.get_compass_raw() readings['gyroscope'] = sense.gyro_raw readings['accelerometer'] = sense.accel_raw x = x + 1 message = json.dumps(readings) producer.send(device, key=bytes("message", encoding='utf-8'), value=bytes(message, encoding='utf-8')) time.sleep(parser.getfloat('device', 'sendSleep'))
return x,y def check_wall(x,y,new_x,new_y): if maze[new_y][new_x] != r: return new_x, new_y elif maze[new_y][x] != r: return x, new_y elif maze[y][new_x] != r: return new_x, y else: return x,y def check_win(x,y): global game_over if maze[y][x] == g: game_over = True sense.show_message('You Win') while not game_over: pitch = sense.get_orientation()['pitch'] roll = sense.get_orientation()['roll'] x,y = move_marble(pitch,roll,x,y) check_win(x,y) maze[y][x] = w sense.set_pixels(sum(maze,[])) sleep(0.01) maze[y][x] = b
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)
class SenseHat_Adapter (adapter.adapters.Adapter): """Interface to SenseHat-Adapter using SenseHat-Library """ mandatoryParameters = { 'poll.interval': '0.1' } def __init__(self): adapter.adapters.Adapter.__init__(self) self.pixel_Color = self.getRGBFromString('default') self.pixel_X = 0 self.pixel_Y = 0 def setActive (self, active): if active: self.sense = SenseHat() adapter.adapters.Adapter.setActive(self, active) else: adapter.adapters.Adapter.setActive(self, active) self.sense = None def run(self): if debug: print("thread started") _del = float(self.parameters['poll.interval']) last_temperature = None last_pressure = None last_humidity = None last_orientation_pitch = None last_orientation_yaw = None last_orientation_roll = None # # the float values are all different in each send cycle # to allow some reduction in value sending, the values are # converted to string and reduced to 2 digital points # formatString = "{:.1f}" while not self.stopped(): # # delay 5 sec, but break time in small junks to allow stopping fast # self.delay(_del) value = self.sense.get_temperature() sValue = formatString.format(value) if sValue != last_temperature: last_temperature = sValue self.temperature(sValue) value = self.sense.get_pressure() sValue = formatString.format(value) if sValue != last_pressure: last_pressure = sValue self.pressure(sValue) value = self.sense.get_humidity() sValue = formatString.format(value) if sValue != last_humidity: last_humidity = sValue self.humidity(sValue) orientation = self.sense.get_orientation() value = orientation['pitch'] sValue = formatString.format(value) if sValue != last_orientation_pitch: last_orientation_pitch = sValue self.orientation_pitch(sValue) value = orientation['yaw'] sValue = formatString.format(value) if sValue != last_orientation_yaw: last_orientation_yaw = sValue self.orientation_yaw(sValue) value = orientation['roll'] sValue = formatString.format(value) if sValue != last_orientation_roll: last_orientation_roll = sValue self.orientation_roll(sValue) # # values from adapter to scratch # def temperature(self, value): """output from adapter to scratch""" self.sendValue(value) def pressure(self, value): """output from adapter to scratch""" self.sendValue(value) def humidity(self, value): """output from adapter to scratch""" self.sendValue(value) def orientation_pitch(self, value): """output from adapter to scratch""" self.sendValue(value) def orientation_roll(self, value): """output from adapter to scratch""" self.sendValue(value) def orientation_yaw(self, value): """output from adapter to scratch""" self.sendValue(value) # # values from scratch to adapter # pixel_Color = None pixel_X = 0 pixel_Y = 0 def pixelColor(self, color): self.pixel_Color = self.getRGBFromString(color) def pixelX(self, value): if debug: print("pixelX", value) try: self.pixel_X = int(value) except Exception: pass def pixelY(self, value): if debug: print("pixelY", value) try: self.pixel_Y = int(value) except Exception: pass def color(self, color): if debug: print("color", color) self.pixel_Color = self.getRGBFromString(color) if debug: print(self.pixel_Color) def clear(self): if debug: print("clear") self.sense.clear() def setPixel_xy(self): if debug: print("setPixel_xy") try: self.sense.set_pixel( self.pixel_X, self.pixel_Y, self.pixel_Color['red'], self.pixel_Color['green'], self.pixel_Color['blue'] ) except Exception as e: # print(e) logger.error("{name:s}: {e:s}".format(name=self.name, e=str(e))) def clearPixel_xy(self): if debug: print("clearPixel_xy") try: self.sense.set_pixel( self.pixel_X, self.pixel_Y, 0, 0, 0 ) except Exception as e: logger.error("{name:s}: {e:s}".format(name=self.name, e=str(e)))
'left': -1, 'right': 1, }.get(event.direction, 0)) y = clamp(y + { 'up': -1, 'down': 1, }.get(event.direction, 0)) update_screen() while True: for event in hat.stick.get_events(): print(event.direction, event.action) move_dot(event) orientation = hat.get_orientation() pitch = orientation["pitch"] roll = orientation["roll"] yaw = orientation["yaw"] # pitch = round(pitch, 1) # roll = round(roll, 1) # yaw = round(yaw, 1) print("pitch {0} roll {1} yaw {2}".format(pitch, roll, yaw)) positionX = int(pitch) positionY = int(roll) positionZ = int(yaw) message = '0 ' + str(positionX) # make a string for use with Pdsend send2Pd(message) message = '1 ' + str(positionY) send2Pd(message)
##end # run the folling in the shell from sense_hat import SenseHat ## from sense_emu import SenseHat from time import sleep from pythonosc import osc_message_builder from pythonosc import udp_client sender = udp_client.SimpleUDPClient('127.0.0.1', 4559) sense = SenseHat() inst = "piano" while True: data = sense.get_orientation() pitch = data['pitch'] yaw = data['yaw'] roll = data['roll'] for event in sense.stick.get_events(): print(event.direction, event.action) if event.direction == "left": inst = "dark_ambience" elif event.direction == "up": inst = "beep" elif event.direction == "right": inst = "mod_dsaw" elif event.direction == "down": inst = "prophet" note = (pitch / 18) + 60
#!/usr/bin/env python # -*- coding: utf-8 -*- from sense_hat import SenseHat from time import sleep sh = SenseHat() try: while True: pitch, roll, yaw = sh.get_orientation().values() pitch = round( pitch, 1 ) roll = round( roll, 1 ) yaw = round( yaw, 1 ) print( "Pitch = %s° Roll = %s° Yaw = %s°" %(pitch, roll, yaw) ) except KeyboardInterrupt: print( "Exiting..." );
new_y += 1 elif 350 > roll > 170 and y != 0 : new_y -= 1 x,y = check_wall(x,y,new_x,new_y) return x,y def check_wall(x,y,new_x,new_y): if maze[new_y][new_x] != r: return new_x, new_y elif maze[new_y][x] != r: return x, new_y elif maze[y][new_x] != r: return new_x, y else: return x,y def check_win(x,y): global game_over if maze[y][x] == g: game_over = True sense.show_message('You Win') while not game_over: pitch = sense.get_orientation()['pitch'] roll = sense.get_orientation()['roll'] x,y = move_marble(pitch,roll,x,y) check_win(x,y) maze[y][x] = w sense.set_pixels(sum(maze,[])) sleep(0.01) maze[y][x] = b
#count is used to take photo on every other iteration of loop #this gives the camera a two second cool down instead of one count = 1 while (True): if count % 2 == 0: camera.capture('photos/image%s.jpg' % (count - 1)) #enviornmental sensors humidity = fedora.get_humidity() temp = fedora.get_temperature() temp_from_humidity = fedora.get_temperature_from_humidity() temp_from_pressure = fedora.get_temperature_from_pressure() pressure = fedora.get_pressure() #get orientation orientation = fedora.get_orientation() orientation_pitch = orientation.get('pitch') orientation_roll = orientation.get('roll') orientation_yaw = orientation.get('yaw') #get compass compass = fedora.get_compass() #get gyroscope gyro = fedora.get_gyroscope() gyro_pitch = gyro.get('pitch') gyro_roll = gyro.get('roll') gyro_yaw = gyro.get('yaw') #get accelerometer accelerometer = fedora.get_accelerometer()
class SensePi: def __init__(self, log_file_name=None, sensor_ids=None): nyu_purple = (87, 46, 140) self.sense = SenseHat() self.sense.show_message("MERCURY", text_colour=nyu_purple, scroll_speed=0.04) self.sense.clear() if log_file_name is None: self.logging = get_logger("SENSE_HAT_LOG_FILE") else: self.logging = get_logger(log_file_name, log_file_name) if sensor_ids is None: self.sensor_ids = {} self.sensor_ids[sensor_keys["TEMPERATURE"]] = 1 self.sensor_ids[sensor_keys["PRESSURE"]] = 2 self.sensor_ids[sensor_keys["HUMIDITY"]] = 3 self.sensor_ids[sensor_keys["ACCELERATION"]] = 4 self.sensor_ids[sensor_keys["ORIENTATION"]] = 5 else: self.sensor_ids = sensor_ids def factory(self, type): data = {} if type in sensor_keys: sensor_data = { sensor_keys["TEMPERATURE"]: self.sense.get_temperature(), sensor_keys["PRESSURE"]: self.sense.get_pressure(), sensor_keys["HUMIDITY"]: self.sense.get_humidity(), sensor_keys["ACCELERATION"]: self.sense.get_accelerometer_raw(), sensor_keys["ORIENTATION"]: self.sense.get_orientation(), } if type == "ALL": # ToDo: implement get all sensor data # This is just example data["values"] = sensor_data elif sensor_keys[type] in sensor_data: key = sensor_keys[type] id = self.sensor_ids[key] data["sensor_id"] = id data["values"] = {} data["values"][key] = sensor_data[key] data["date"] = date_str_with_current_timezone() return data def get_all(self): return self.factory("ALL") def get_temperature(self): return self.factory("TEMPERATURE") def get_pressure(self): return self.factory("PRESSURE") def get_humidity(self): return self.factory("HUMIDITY") def get_acceleration(self): return self.factory("ACCELERATION") def get_orientation(self): return self.factory("ORIENTATION")
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(),'')
# Main sensor polling loop while True: # This time is used for logging purposes in the CSV data file data_time = time.strftime("%H:%M:%S",time.gmtime()) ### Readings from the SenseHat ## Environment sensors SH_temp = sense.get_temperature() # value in degrees C SH_pressure = sense.get_pressure() * 100 # convert output from millibars to Pascals for consistency SH_humidity = sense.get_humidity() # % relative humidity # Orientation sense.set_imu_config(True,True,True) # Enable compass, gyro, and accelerometer SH_orientation = sense.get_orientation() # orientation of pitch, roll, yaw axes in degrees SH_orientation_x = SH_orientation.get('x') SH_orientation_y = SH_orientation.get('y') SH_orientation_z = SH_orientation.get('z') # Magnetometer data #sense.set_imu_config(True,False,False) time.sleep(0.01) # sleep for 10 ms after changing IMU configuration SH_compass_north = sense.get_compass() # direction of magnetometer from North, in degrees SH_compass_raw = sense.get_compass_raw() # magnetic intensity of x, y, z axes in microteslas SH_compass_raw_x = SH_compass_raw.get('x') SH_compass_raw_y = SH_compass_raw.get('y') SH_compass_raw_z = SH_compass_raw.get('z') # Gyro Data #sense.set_imu_config(False,True,False)
## Level 3 [[r, r, r, r, r, r, r, r], [r, k, k, k, k, k, k, r], [r, r, r, r, k, k, k, r], [r, r, k, r, r, k, r, r], [r, r, k, r, r, k, r, r], [r, r, r, r, r, g, r, r], [r, k, k, k, r, r, r, r], [r, r, r, r, r, r, r, r]] ] sh.show_message("L1") curr_level = 0 done = False while not done: level = levels[curr_level] orientation = sh.get_orientation() pitch = orientation['pitch'] roll = orientation['roll'] x, y = move(pitch, roll, x, y, level) if (level[y][x] == g): curr_level += 1 if (curr_level >= 3): done = True sh.show_message("W") sh.clear() else: sh.show_message("L%d" % int(curr_level + 1)) sh.clear() x = 1 y = 1
i = [] #Define list needed for the plot. s = [] v = [] w = [] x = [] y = [] z = [] angular = 0 #Initial value of the angular displacement. count = 0 snooze = 2 #Time in seconds for the time.sleep(). velocity = 0 while True: try: sense = SenseHat() orientation = sense.get_orientation() #Reads orientation from SenseHAT. xaxis = round(orientation["roll"], 2) yaxis = round(orientation["pitch"], 2) zaxis = round(orientation["yaw"], 2) count += 1 i.append(count) #Updates list for the plot. x.append(xaxis) y.append(yaxis) z.append(zaxis) if count >=2: #Calculates the angular displacement, at least two data points are needed. angular = round(((x[count-1]-x[count-2])**(2) + (y[count-1]-y[count-2])**(2) + (z[count-1]-z[count-2])**(2))**(0.5), 2) w.append(angular) velocity = round(angular/snooze, 2) #Calculates the angular velocity.
from sense_hat import SenseHat import time import datetime from time import sleep from guizero import App, Text, PushButton, Picture sense = SenseHat() sense.clear() orientation=sense.get_orientation() roll=orientation['roll'] e=(0,0,0) w=(255,255,255) r=(255,0,0) a=(0,0,255) y=(255,255,0) o=(255,150,0) c=(0,150,255) g=(0,255,0) dg=(0,125,0) z=(200,170,120) cb=(255,150,230) pp=(170,0,255) v=(150,100,50) cold=[ e,e,e,e,e,w,e,e, e,e,e,e,w,e,e,e, e,e,e,w,e,e,e,w, e,w,w,a,e,e,w,e,
#!/usr/bin/python from sense_hat import SenseHat import math sense = SenseHat() while True: # Get Pi's orientation pitch, yaw, roll = sense.get_orientation().values() pitch = round(pitch,1) yaw = round(yaw,1) roll = round(roll,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()
''' This program uses the gyro sensor of the SenseHat to show the live pitch, roll, and yaw ''' from sense_hat import SenseHat s = SenseHat() while True: o = s.get_orientation() pitch = o["pitch"] roll = o["roll"] yaw = o["yaw"] print("pitch {0} roll {1} yaw {2}".format(pitch, roll, yaw)) #Adding delay i = 0 while i < 100000: i += 1
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))
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) sense = SenseHat() sense.set_imu_config(True, True, True) red = (255, 0, 0) green = (0, 255, 0) counter=0 sense.clear() sense.show_message("WAIT", text_colour=[255, 0, 0]) for i in reversed(range(0,10)): sense.show_letter(str(i)) time.sleep(1) sense.show_message("GO", text_colour=[255, 0, 0]) o = sense.get_orientation() resting_yaw = round(o["yaw"],3) print("Resting yaw: {0}".format(resting_yaw)) while True: o = sense.get_orientation() yaw = round(o["yaw"],3) print("yaw: {0}".format(yaw)) if yaw>resting_yaw+30: print("-------------Door opened") sense.clear(red) counter += 1 else: print("-------------Door closed") if counter > 0: print("-------------BROADCAST!!!!")
class GyroClear(object): #Initialize class variables here b = (255, 255, 0) # background - gold f = (0, 0, 255) # foreground - blue c = (0, 0, 0) # clear e = (0, 255, 0) # eraser colour (green) a = [ b, b, b, f, f, b, b, b, b, b, b, f, f, b, b, b, b, b, f, b, b, f, b, b, b, b, f, b, b, f, b, b, b, f, f, f, f, f, f, b, b, f, b, b, b, b, f, b, f, b, b, b, b, b, b, f, f, b, b, b, b, b, b, f, ] s = [ b, b, f, f, f, f, b, b, b, f, b, b, b, b, f, b, b, f, b, b, b, b, b, b, b, b, f, f, f, b, b, b, b, b, b, f, f, f, b, b, b, b, b, b, b, b, f, b, b, f, b, b, b, b, f, b, b, b, f, f, f, f, b, b, ] p = [ b, f, f, f, f, f, b, b, b, f, b, b, b, b, f, b, b, f, b, b, b, b, f, b, b, f, b, b, b, b, f, b, b, f, f, f, f, f, b, b, b, f, b, b, b, b, b, b, b, f, b, b, b, b, b, b, b, f, b, b, b, b, b, b, ] def __init__(self): super(GyroClear, self).__init__() self.__sense = SenseHat() self.__eraser_row = 0 self.__eraser_col = 0 self.__letters = [GyroClear.a, GyroClear.s, GyroClear.p] self.__current_letter = 0 self.__current_state = self.__letters[self.__current_letter] def count_letter_blocks(self): """ Return number of letter blocks in the current letter It counts the number of elements that don't match the background colour. The current letter is stored in self.__current_state]. """ count = 0 for e in self.__current_state: if e != GyroClear.b: count += 1 print('Count is {0}'.format(count)) return count def show_letter(self, letter): self.__sense.show_letter(letter) time.sleep(2) def clear_display(self): self.__sense.clear() def display_letters(self): for letter in range(len(self.__letters)): self.__sense.set_pixels(self.__letters[letter]) time.sleep(2) def display_current_board(self): self.__sense.set_pixels(self.__current_state) def display_current_readings(self): temp = self.__sense.get_temperature() self.__sense.show_message("Th: ") self.__sense.show_message(str(int(temp))) temp = self.__sense.get_temperature_from_pressure() self.__sense.show_message("Tp: ") self.__sense.show_message(str(int(temp))) pressure = self.__sense.get_pressure() self.__sense.show_message("P: ") self.__sense.show_message(str(int(pressure))) humidity = self.__sense.get_humidity() self.__sense.show_message("H: ") self.__sense.show_message(str(int(humidity))) def next_letter(self): """ Move the game to the next level Returns False when there are no move letters. """ next_level = True if self.__current_letter >= (len(self.__letters) - 1): next_level = False else: self.__current_letter += 1 self.__current_state = self.__letters[self.__current_letter] return next_level def getArrayIndex(self, x, y): """ Return index in list relative to logical 8x8 matrix """ index = y * 8 + x print('Index: {0}'.format(index)) return index def move_eraser(self): """ Move the eraser based on pitch and roll from the Gyro This is the brains of the game. It using values from the Gyro to move the eraser around the board. If it finds a block that is not the background colour, then appropriate updates are made. Return True of a block was erased. """ block_erased = False old_x = self.__eraser_row old_y = self.__eraser_col pitch = self.__sense.get_orientation()['pitch'] roll = self.__sense.get_orientation()['roll'] if 1 < pitch < 179 and self.__eraser_row != 0: self.__eraser_row -= 1 elif 359 > pitch > 179 and self.__eraser_row != 7: self.__eraser_row += 1 if 1 < roll < 179 and self.__eraser_col != 7: self.__eraser_col += 1 elif 359 > roll > 179 and self.__eraser_col != 0: self.__eraser_col -= 1 old_index = self.getArrayIndex(old_x, old_y) print('old_index is {0} from {1},{2}'.format(old_index, old_x, old_y)) new_index = self.getArrayIndex(self.__eraser_row, self.__eraser_col) print('new_index is {0} from {1},{2}'.format(new_index, self.__eraser_row, self.__eraser_col)) # If new index is not background colour, then we have found a new block # to erase. if self.__current_state[new_index] != GyroClear.b: block_erased = True # Update current state to make this index background colour. self.__current_state[new_index] = GyroClear.b # Update the pixels on the sense hat display self.__sense.set_pixel(old_x, old_y, GyroClear.b) self.__sense.set_pixel(self.__eraser_row, self.__eraser_col, GyroClear.e) return block_erased def play_game(self): have_level = True while have_level: self.display_current_board() count = game.count_letter_blocks() while count > 0: erased = self.move_eraser() if erased: count -= 1 time.sleep(0.25) print('count is {0}'.format(count)) have_level = self.next_letter() self.__sense.show_message('Enter secret message here', text_colour=GyroClear.f, back_colour=GyroClear.b)
from sense_hat import SenseHat sh = SenseHat() from time import sleep while True: p,r,y = sh.get_orientation().values() print("pitch=%s, roll=%s, yaw=%s" % (p,r,y)) sleep(0.5)
return str(round(float(reform), 4)) '''Test function: lat = '4142.86751' longi = '08803.24426' loca_format(lat) + "," + loca_format(longi) ''' # Publish to the same topic in a loop forever while True: gpsList = [] # save ALL sensor and gps data (10 rows) if args.mode == 'both' or args.mode == 'publish': pitch, roll, yaw = sense.get_orientation().values() ax, ay, az = sense.get_accelerometer_raw().values() mx, my, mz = sense.get_compass_raw().values() message = {} message['camera_id'] = 'raspberry1' # sensor message['gx'] = pitch message['gy'] = roll message['gz'] = yaw message['ax'] = ax message['ay'] = ay