def main(): _logger_config() sense = sense_hat.SenseHat() while True: event = sense.stick.wait_for_event(emptybuffer=True) if event.action == stick.ACTION_PRESSED: if event.direction == stick.DIRECTION_MIDDLE: sense.show_message(_get_local_time(), text_colour=[255, 0, 255]) elif event.direction == stick.DIRECTION_UP: sense.show_message("{0:.1f} %%rH".format(humidity), text_colour=[255, 0, 255]) elif event.direction == stick.DIRECTION_DOWN: sense.show_message( "{0:.1f} °F".format(curr_temp), text_colour=_determine_temp_led_color(curr_temp)) elif event.direction == stick.DIRECTION_LEFT: sense.show_message("{0:.3f} mbar".format(curr_pressure), text_colour=[255, 0, 255]) while event is not None: north = sense.get_compass() print("{0:.1f}°N".format(north)) humidity = sense.get_humidity() print("{0:.1f} %%rH".format(humidity)) curr_temp = _convert_to_farenheit( sense.get_temperature_from_humidity()) print("{0:.1f}°F".format(curr_temp)) curr_pressure = sense.get_pressure() print("{0:.4f} Millibars".format(curr_pressure)) time.sleep(2)
class TempSensorAdaptorTask(object): ''' The TempSensorAdaptorTask reads the temperature from the SenseHAT, creates a SensorData object using that value and returns it ''' #Initialize sense_hat sense = sense_hat.SenseHat() #Initialize SensorData sensorData = SensorData() #Set the name of the Sensor sensorData.setName("Temperature Sensor") #Empty constructor as we do not want to initialize anything during instantiation def __init__(self): ''' Constructor ''' """ Method to return the SensorData reference after getting the temperature from SenseHAT API """ def getTemperature(self): #Get the temperature and add it to SensorData self.sensorData.addValue(self.sense.get_temperature()) #Return the SensorData reference return self.sensorData
def main(): hat = sense_hat.SenseHat() hat.set_imu_config(False, True, True) imu = hat._imu print("IMU Name: " + imu.IMUName()) imu.setSlerpPower(0.02) poll_interval = imu.IMUGetPollInterval() / 1000.0 print("Recommended poll interval", poll_interval) samples = 0 next_measured_rate = time.monotonic() + 1.0 cstr = "" pos = np.empty(3, dtype=np.double) while True: now = time.monotonic() if now >= next_measured_rate: print(quat_string) print("Poll interval: ", samples, now - (next_measured_rate - 1.0), (now - (next_measured_rate - 1.0)) / samples) samples = 0 next_measured_rate = now + 1.0 rereads = 0 while not imu.IMURead(): rereads += 1 if rereads > 5: print("rereads:", rereads) samples += 1 # The RTIMU library here uses [w,x,y,z] imu_data = imu.getIMUData() q = imu_data['fusionQPose'] accel = np.array(imu_data['accel']) p = np.sin(time.time() * 2 * math.pi / np.array([5.0, 4.0, 6.0])) # imu.json needs to be in [x,y,z,w] #quat_string = "[%f,%f,%f,%f]" % (q[1], q[2], q[3], q[0]) # For the purposes of drawing the cube in my desired location, # I reorder the axes too. On screen, we have X=right, Y=down, # Z=out. In the IMU, Pin 1 is towards the side with the GPIO # connector and away from the side with the USB ports, but the # datasheet seems to be wrong (based on accelerometer # readings). Hence, in a SmartPi case sitting upright, we # have X=right, Y=up, Z=in. This component construction does # the right reorientation. accel *= 3 out_data = { "o": (q[1], q[3], q[2], -q[0]), "p": p.tolist(), "v": (accel[0], accel[2], accel[1]), "c": cstr } quat_string = json.dumps(out_data) with open("/run/user/1000/imu.json.new", "w") as fd: print(quat_string, file=fd) os.rename("/run/user/1000/imu.json.new", "/run/user/1000/imu.json")
def setUp(self): #instantiate the classes required self.sensorDataManager = SensorDataManager() self.hI2CSensorAdaptorTask = HI2CSensorAdaptorTask() self.humiditySensorAdaptorTask = HumiditySensorAdaptorTask() self.multiActuatorAdaptor = MultiActuatorAdaptor() self.multiSensorAdaptor = MultiSensorAdaptor() self.sense = sense_hat.SenseHat()
class SenseHat(pattern.Singleton, pattern.EventEmitter): def __init__(selfm *args, **kwargs): super(SenseHat, self).__init__(*args, **kwargs) self._sense = sense_hat.SenseHat() self._sense.set_imu_config( compass_enabled=True, gyro_enabled=True, accel_enabled=True) self._sense.stick.direction_middle = self._on_joystick_pushed
def __init__(self, max_temp, min_temp, max_updateTime, min_updateTime, configDir): Thread.__init__(self) self.max_value = max_temp self.min_value = min_temp self.maxUpdateTime = max_updateTime self.minUpdatetime = min_updateTime # get the data of device like: enableEmulator,nominalTemp... self.deviceConfigReader = ConfigUtil.ConfigUtil(configDir, "device") self.enableTempEmulator = self.deviceConfigReader.getProperty("enableEmulator") self.nominalTemp = self.deviceConfigReader.getProperty("nominalTemp") # if we chose sensehat, we should connect to sensehat part, dont add temperature by uniform function self.sh = sense_hat.SenseHat()
def __init__(self): # Get sense hat access self.__sense = sense_hat.SenseHat() # Load JSON config variables with open("config.json", "r") as jsonFile: config = json.load(jsonFile) self.__minTemp = float(config["min_temperature"]) self.__maxTemp = float(config["max_temperature"]) self.__minHumid = float(config["min_humidity"]) self.__maxHumid = float(config["max_humidity"]) # Load Pushbullet API access self.__pushbulletAPI = PushbulletAPI()
def __init__(self, enableEmulator, lowVal, highVal, curTemp, isPrevTempSet): super(SensorAdaptor, self).__init__() self.enableEmulator = enableEmulator self.curTemp = curTemp self.lowVal = lowVal self.highVal = highVal self.isPrevTempSet = isPrevTempSet self.sh = sense_hat.SenseHat() self.config = ConfigUtil.ConfigUtil('') self.config.loadConfig()
def __init__(self, databaseName): # Get sense hat access self.__sense = sense_hat.SenseHat() # Load JSON config variables with open("config.json", "r") as jsonFile: config = json.load(jsonFile) self.__minTemp = float(config["min_temperature"]) self.__maxTemp = float(config["max_temperature"]) self.__minHumid = float(config["min_humidity"]) self.__maxHumid = float(config["max_humidity"]) # Load Pushbullet API access self.__pushbulletAPI = PushbulletAPI() # Connect to database for logging climate data self.__connectToDatabase(databaseName)
async def run(self): self.hat = sense_hat.SenseHat() self.data = [] while True: #self.data.append(get_stats(self.hat)) for x in range(10): self.data.append(get_stats(self.hat)) await curio.sleep(0.1) print(len(self.data)) self.update_plots()
def __init__(self, configDir): Thread.__init__(self) self.deviceConfigReader = ConfigReader(configDir, "Device") self.sh = sense_hat.SenseHat() self.currentSensorData = SensorData("Temperature") #SensorEmulator simulates temperature range from 25 degree to 15 degree #temperature is changed after a random period of time in range 10 sec to 1 sec self.tempSensorEmulator = SensorEmulator(30, 15, 10, 1) self.tempSensorEmulator.daemon = True self.tempSensorEmulator.start() if self.deviceConfigReader.getProperty("enableEmulator") == "True": self.enableTempEmulator = True self.tempSensorEmulator.enableTempEmulator = True
def __init__(self, host, token, port=8088, disable_ssl_verify=False, index='ar-weather-demo', upload_interval=0.5): super(WeatherListener, self).__init__() self._url = '{host}:{port}/services/collector'.format(host=host, port=port) self._index = index self._upload_interval = upload_interval self._sense_hat = sense_hat.SenseHat() self._session = requests.Session() self._session.verify = not disable_ssl_verify self._session.max_redirects = 1 self._session.headers.update({'Authorization': 'Splunk ' + token}) # For debugging self.name = 'weather-polling-thread-' + str(id(self))
def main(): args = parseCmdline() pressureHistorySettings = {} if args.initiallow: pressureHistorySettings['initialpressurelow'] = args.initiallow if args.initialhigh: pressureHistorySettings['initialpressurehigh'] = args.initialhigh if args.logFilename: csvfile = open(args.logFilename, 'w') pressureHistorySettings['logger'] = CSVLogger(csvfile=csvfile) pressureHistory = PressureHistory(**pressureHistorySettings) barometer = Barometer(sense_hat.SenseHat(), pressureHistory, updaterate=args.updaterate) barometer.run()
def record_sensors(): import sense_hat s = sense_hat.SenseHat() temp_h = s.get_temperature_from_humidity() - 4 # correction factor. temp_p = s.get_temperature_from_pressure() - 4 # correction factor. humidity = s.get_humidity() pressure = s.get_pressure() Session = sessionmaker(bind=engine) session = Session() # append to db new_record = Record(temperature_h=temp_h, humidity=humidity, temperature_p=temp_p, pressure=pressure) session.add(new_record) session.commit()
class HumiditySensorAdaptorTask(): ''' classdocs ''' #initialize the sense hat class from the library sense = sense_hat.SenseHat() #initialize the fetcher enableFetcher = True #instantiate the SensorData class sensorData = SensorData() #set the sensorData name to humidity via sense_hat api sensorData.setName("sense_hat API humidity") #instantiate the SensorDataManager sensorDataManager = SensorDataManager() #this method is used to set the readings and the frequency of readings if provided, else defaults to 10 and 5 respectively def __init__(self): ''' Constructor ''' #get the humidity data using the sense hat library def getHumidityData(self): #get the humidity from the sense hat humidity = self.sense.get_humidity() #add it to the sensorData self.sensorData.addValue(humidity) #store the updated values from sensorData object time = ' Time: ' + self.sensorData.timeStamp current = ' Current: ' + str( self.sensorData.getCurrentValue()) average = ' Average: ' + str( self.sensorData.getAverageValue()) samples = ' Samples: ' + str(self.sensorData.getCount()) min_temp = ' Min: ' + str(self.sensorData.getMinValue()) max_temp = ' Max: ' + str(self.sensorData.getMaxValue()) data = 'Humidity readings from SenseHAT API' + '\n' + time + '\n' + current + '\n' + average + '\n' + samples + '\n' + min_temp + '\n' + max_temp + '\n' #add to data section of sensorData self.sensorData.loggingData = data #create the concatenation for logging logData = self.sensorData.timeStamp + ",INFO:SenseHAT API Humidity: " + str( self.sensorData.getCurrentValue()) #log the current sensorData values logging.info(logData) #return the sensor data return self.sensorData #method to return the current instance of the sensor data def getSensorData(self): #return the reference to the sensor data return self.sensorData
import socket import sense_hat ip = socket.gethostname() port = 420 server = socket.socket() while True: sensors = sense_hat.SenseHat() server.bind((ip, port)) print("Bound to " + ip + ":" + str(port)) server.listen() client, clientaddress = server.accept() print("Just connected to " + clientaddress) while client.getpeername() is not None: orientation = sensors.get_orientation_degrees() pitch = str(round(orientation["pitch"], 1)) yaw = str(round(orientation["yaw"], 1)) roll = str(round(orientation["roll"], 1)) xyz = "|" + pitch + "|" + yaw + "|" + roll + "|" client.send(xyz.encode("UTF8"))
import sense_hat from time import sleep # Petla sprawdzajaca wilgotnosc wokol rassbery okienko = sense_hat.SenseHat() while True: print(okienko.get_humidity()) sleep(2)
def __init__(self): self.sense = sense_hat.SenseHat()
def main(): # Read from configuration cf = configparser.ConfigParser({ 'dbfile': "/tmp/pimsgboard.db", 'scrollspeed':2.0, 'pollinterval':5.0, 'webhost':'', 'webport':8080, 'lowlight':True, 'autoplay':False}) cf.add_section('pimsgboard') if os.path.isfile(os.path.expanduser("~/.pimsgboard")): cf.read(os.path.expanduser("~/.pimsgboard")) # Location of the database we will read from db_file = cf.get("pimsgboard", "dbfile") # How fast to scroll. 1 is default. 2 is twice as fast, etc. msg_speed = cf.getfloat("pimsgboard", "scrollspeed") # How frequently to poll for new messages, in seconds poll_interval = cf.getfloat("pimsgboard", "pollinterval") # Where to serve the webpage web_host = cf.get("pimsgboard", "webhost") web_port = cf.getint("pimsgboard", "webport") # Set low light mode to protect retinas low_light = cf.getboolean("pimsgboard", "lowlight") # Shoudl messages automatically scroll or wait for buttons? auto_play = cf.getboolean("pimsgboard", "autoplay") # Check if the database exists and is in the correct format if not db.check_db(db_file): sys.exit("Error reading database file {}".format(db_file)) # Create the sense hat object: shared by all threads sense = sense_hat.SenseHat() sense.low_light = low_light # Lock to coordinate access to the sense's LED display led_lock = threading.RLock() # Start threads for handling joystick input, idle inbox display, # and web interface. If autoplay is on, start thread for autoplaying if auto_play: auto_thread = threading.Thread( target=check_and_autoplay, args=(sense, led_lock, db_file), kwargs={'msg_speed':msg_speed, 'poll_interval':poll_interval}) auto_thread.start() else: input_thread = threading.Thread( target=handle_joystick_input, args=(sense, led_lock, db_file), kwargs={'msg_speed':msg_speed}) inbox_thread = threading.Thread( target=check_inbox, args=(sense, led_lock, db_file), kwargs={'poll_interval':poll_interval}) input_thread.start() inbox_thread.start() web_thread = threading.Thread( target=web.start_server, args=(web_host, web_port, db_file), kwargs={}) web_thread.start() print("Ready") # Wait indefinitely for them to end web_thread.join() if auto_play: auto_thread.join() else: inbox_thread.join() input_thread.join() # Clear sense hat display sense.clear()
__double = not __double if __delgte is not True : # The indicator variable `__fready' is flipped to signal # new display frames are ready at the variable `oframe # _inc'. # __fready = not __fready # The __double flag is inverted, therefore, the predicate # should be inverted, i.e., True when (255, 255, 255) and # False when (0, 0, 0). # print("Displayed 1-D Frame of {}".format("Full Brightness" if __double is True else "Full Darkness")) __sen_inst = sense_hat.SenseHat() # Generation of Single Frame Array for Displaying in Sense Hat LED Matrix. # frm_2d = [[colour["violet"] for _ in range(DISP_DIMX)] for _ in range(DISP_DIMY)] frm_1d = [colour["white"] for _ in range(DISP_DIMY * DISP_DIMX)] # Generation of Multi-Frame Array (Animation) for Displaying in Sense Hat LED Matrix. # ani_2d = [[[colour[name] for _ in range(DISP_DIMX)] for _ in range(DISP_DIMY)] for name in ["red", "green", "blue"]] ani_1d = [[colour[name] for _ in range(DISP_DIMY * DISP_DIMX)] for name in ["yellow", "black", "red"]] for i in [ani_2d, ani_1d] : display_single(i) for i in [frm_2d, frm_1d] :
import sense_hat as sh #import matplotlib.pyplot as plt import time sense = sh.SenseHat() sense.set_imu_config(False, True, True) # gyro + accel sense.show_message("Joystick>>stop:", text_colour=[200, 40, 20], scroll_speed=0.05) run = True while run: orientation = sense.get_orientation() print("%5.1f" % (orientation["yaw"])) time.sleep(0.2) if sense.stick.get_events() != []: run = False
def sensor_acquisition(sysInput): rate_hz,queue_size = float(sysInput[1]),float(sysInput[2]) sense = sense_hat.SenseHat() # Enable sensor acc_enable = True if ('accxyz' in sysInput) or ('accrpy' in sysInput) else False gyr_enable = True if ('gyrxyz' in sysInput) or ('gyrrpy' in sysInput) else False cps_enable = True if ('magxyz' in sysInput) or ('magcps' in sysInput) else False env_enable = True if ('envall' in sysInput) else False joy_enable = True if ('joystk' in sysInput) else False sense.set_imu_config(cps_enable,gyr_enable,acc_enable) if ('accxyz' in sysInput): pub_accxyz = rospy.Publisher('/sensehat/accxyz', std_msgs.msg.Vector3, queue_size=queue_size) if acc_enable else None if ('accrpy' in sysInput): pub_accrpy = rospy.Publisher('/sensehat/accrpy', std_msgs.msg.Vector3, queue_size=queue_size) if acc_enable else None if ('gyrxyz' in sysInput): pub_gyrxyz = rospy.Publisher('/sensehat/gyrxyz', std_msgs.msg.Vector3, queue_size=queue_size) if gyr_enable else None if ('gyrrpy' in sysInput): pub_gyrrpy = rospy.Publisher('/sensehat/gyrrpy', std_msgs.msg.Vector3, queue_size=queue_size) if gyr_enable else None if ('magxyz' in sysInput): pub_magxyz = rospy.Publisher('/sensehat/magxyz', std_msgs.msg.Vector3, queue_size=queue_size) if cps_enable else None if ('magcps' in sysInput): pub_magcps = rospy.Publisher('/sensehat/magcps', std_msgs.msg.Float64, queue_size=queue_size) if cps_enable else None if ('envall' in sysInput): pub_envhmd = rospy.Publisher('/sensehat/envhmd', std_msgs.msg.Float64, queue_size=queue_size) if env_enable else None pub_envtph = rospy.Publisher('/sensehat/envtph', std_msgs.msg.Float64, queue_size=queue_size) if env_enable else None pub_envtpp = rospy.Publisher('/sensehat/envtpp', std_msgs.msg.Float64, queue_size=queue_size) if env_enable else None pub_envprs = rospy.Publisher('/sensehat/envprs', std_msgs.msg.Float64, queue_size=queue_size) if env_enable else None if ('joystk' in sysInput): pub_joystk = rospy.Publisher('/sensehat/joystick', std_msgs.msg.String, queue_size=queue_size) if joy_enable else None rospy.init_node('raspi_sense_hat_sensor', anonymous=True) rate = rospy.Rate(rate_hz) while not rospy.is_shutdown(): # IMU sensor if acc_enable: accxyz = sense.get_accelerometer_raw() pub_accxyz.publish(std_msgs.msg.Vector3(x=accxyz['x'],y=accxyz['y'],z=accxyz['z'])) accrpy = sense.get_orientation_degrees() pub_accrpy.publish(std_msgs.msg.Vector3(x=accrpy['roll'],y=accrpy['pitch'],z=accrpy['yaw'])) if gyr_enable: gyrxyz = sense.get_gyroscope_raw() pub_gyrxyz.publish(std_msgs.msg.Vector3(x=gyrxyz['x'],y=gyrxyz['y'],z=gyrxyz['z'])) gyrrpy = sense.get_gyroscope() pub_gyrrpy.publish(std_msgs.msg.Vector3(x=gyrrpy['roll'],y=gyrrpy['pitch'],z=gyrrpy['yaw'])) if cps_enable: magxyz = sense.get_compass_raw() pub_magxyz.publish(std_msgs.msg.Vector3(x=magxyz['x'],y=magxyz['y'],z=magxyz['z'])) magcps = sense.get_compass() pub_magcps.publish(std_msgs.msg.Float64(magcps)) # Environment sensor if env_enable: pub_envhmd.publish(std_msgs.msg.Float64(sense.get_humidity())) pub_envtph.publish(std_msgs.msg.Float64(sense.get_temperature_from_humidity())) pub_envtpp.publish(std_msgs.msg.Float64(sense.get_temperature_from_pressure())) pub_envprs.publish(std_msgs.msg.Float64(sense.get_pressure())) # Joystick event if joy_enable: getEvents = sense.stick.get_events() for eachEvent in getEvents: pub_joystk.publish(eachEvent.direction+'_'+eachEvent.action) rate.sleep()
import sense_hat import time """ Simple utility to test SenseHat joystick and LEDs are working. Uses sense_hat.SenseStick for input """ stick = sense_hat.SenseStick() screen = sense_hat.SenseHat() def react(event): n = event[1] + (event[1] - 100) * 10 color = [(n, n, n)] * 64 screen.set_pixels(color) if press[1] == stick.KEY_RIGHT: print("Right!") elif press[1] == stick.KEY_LEFT: print("Left!") elif press[1] == stick.KEY_UP: print("UP!") elif press[1] == stick.KEY_DOWN: print("Down!") print("Test joystick directions. Click joystick to exit") while True: press = stick.read() if press[1] == stick.KEY_ENTER:
def set_up_sense_hat(): """Creates a SenseHat instance, sets the configuration, and returns the instance""" sense = sense_hat.SenseHat() sense.low_light = True return sense
""" Light up frames randomly in a Disco style. """ import sense_hat as S import random as R s = S.SenseHat() def clear(): for x in range(8): for y in range(8): s.set_pixel(x, y, 0, 0, 0) def frame(): for x in range(8): for y in range(8): r = R.randint(0, 255) g = R.randint(0, 255) b = R.randint(0, 255) s.set_pixel(x, y, r, g, b) def main(): try: print("Blinking...") while True: frame() except KeyboardInterrupt:
def on_message(mqttc, obj, msg): data = "TempActuatorData arrived from :" + msg.topic + " QoS = " + str( msg.qos) + " Message:" + str(msg.payload.decode("utf-8")) print(data) sh = sense_hat.SenseHat() sh.show_message(data, scroll_speed=0.1)
def __init__(self, location): self.location = location self.sensehat = sense_hat.SenseHat()
import pygame from pygame.locals import * import time, sense_hat, commands pygame.init() #setup display for event recieving DISPLAY = pygame.display.set_mode((400, 400)) pygame.display.set_caption("Pipod event reciever") #audio system mixer = pygame.mixer mixer.music.set_endevent( USEREVENT) #this event is triggered when the music ends hat = sense_hat.SenseHat() #the hat #implement settings (other than PATH) if SHUFFLE: import random if SPEAK: try: import espeak.espeak as espeak #espeak settings. may be in the SETTINGS section in the future espeak.set_parameter(7, 5) espeak.set_voice("en-us") except ImportError as e: print("Error: espeak import failed! " + str(e))
import sense_hat, random, time """ Rock Paper Scissors Play Rock Paper Scissors with your Raspberry Pi. Select rock, paper or scissors with the joystick. The Pi picks randomly. Keeps track of your score- try best out of 5! Note: Requires sense_hat version 2.2.0 or later """ sense = sense_hat.SenseHat() game_state = { "comp_pick": None, "user_pick": None, "picks": ("rock", "paper", "scissors"), "choice_index": 0, "comp_score": 0, "user_score": 0 } start_over_state = game_state.copy() Y = (255, 255, 0) G = (0, 255, 0) B = (0, 0, 255) X = (0, 0, 0)
#from sense_hat import SenseHat #sense = SenseHat() #sense.clear() import sense_hat sense_hat.SenseHat().clear() #library.module().function()