• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python sense_hat.SenseHat类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sense_hat.SenseHat的典型用法代码示例。如果您正苦于以下问题:Python SenseHat类的具体用法?Python SenseHat怎么用?Python SenseHat使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了SenseHat类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: Display

class Display(base_display.DisplayBase):

    """
    Control Raspberry Pi Sense Hat LED Matrix
    """

    def __init__(self):
        self.sense = SenseHat()
        self.defer = None

    def cb_show_text(self, *args, **kwargs):
        self.defer = None

    def show_text(self, text):
        self.show(text, None, None)
        
    def show(self, text, textcolor, bgcolor):
        if not textcolor:
            textcolor = (0xff,0xff,0xff)
        if not bgcolor:
            bgcolor = (0,0,0)
            
        if self.defer is None:
            self.sense.set_rotation(90, False)
            self.defer = threads.defer_to_thread(self.sense.show_message, text, text_colour=textcolor, back_colour=bgcolor)
            self.defer.addCallback(self.cb_show_text)
            self.defer.addErrback(self.cb_show_text)

    def clear(self):
        self.sense.clear()
开发者ID:f1soft,项目名称:calvin-base,代码行数:30,代码来源:display.py


示例2: main

def main(frames=FRAMES):
    """Show the frames on the sense hat."""
    sense = SenseHat()

    for frame in frames:
        sense.set_pixels(frame)
        time.sleep(0.25)
开发者ID:zeth,项目名称:princess,代码行数:7,代码来源:sheshiller.py


示例3: index

def index():
    user = {'nickname': 'Miguel'}  # fake user
    sense = SenseHat()
    sense.show_message("Hello world!")
    return render_template('index.html',
                           title='Home',
                           user=user)
开发者ID:rtibell,项目名称:sens1,代码行数:7,代码来源:flaskweb.py


示例4: time

class SensorHatLogger:

    """
    Logs the hostname, time (unixtime), temperature, humidity, and pressure to Kafka in JSON format. The data is
    generated by a Raspberry Pi with a Sense Hat: https://www.raspberrypi.org/products/sense-hat/
    
    This captures a read approx. every 10 seconds.

    TODO: https://github.com/initialstate/wunderground-sensehat/wiki/Part-3.-Sense-HAT-Temperature-Correction
    
    """

    def __init__(self):
        self.producer = KafkaProducer(bootstrap_servers='hdp01.woolford.io:6667')
        self.sense = SenseHat()
        self.sensor_record = dict()

    def read_values_from_sensor(self):
        self.sensor_record['host'] = socket.gethostname()
        self.sensor_record['timestamp'] = int(time.time())
        self.sensor_record['temperature'] = self.sense.get_temperature()
        self.sensor_record['humidity'] = self.sense.get_humidity()
        self.sensor_record['pressure'] = self.sense.get_pressure()

    def send_record_to_kafka(self):
        sensor_record_json = json.dumps(self.sensor_record)
        self.producer.send("temperature_humidity_json", sensor_record_json)

    def run(self):
        self.read_values_from_sensor()
        self.send_record_to_kafka()
开发者ID:alexwoolford,项目名称:htu21d_logger,代码行数:31,代码来源:pi_sense_hat_logger.py


示例5: music

def music():
    root = tkinter.Tk()
    root.geometry("150x150")
    root.wm_title("Music")
    b1 = ttk.Button(root, text = 'V+', command = vdown)
    b2 = ttk.Button(root, text = 'V-', command = vup)
    b3 = ttk.Button(root, text = 'Next', command = nextm)
    b4 = ttk.Button(root, text = 'Previous', command = previousm)
    b5 = ttk.Button(root, text = 'On/Off', command = moff)
    b1.pack()
    b2.pack()
    b3.pack()
    b4.pack()
    b5.pack()
    sense = SenseHat()
    sense.clear()
    pygame.init()
    pygame.display.set_mode((15, 15))
    mixer.init()
    #music
    global path
    path = "/home/pi/Desktop/Smart House/Music"
    global mfiles
    mfiles = [f for f in os.listdir(path) if f.endswith('.mp3')]
    global abc
    abc = 2
    global state
    state = "Off"
开发者ID:Coding4Kids,项目名称:cidadeinteligente,代码行数:28,代码来源:interface.py


示例6: interp

def interp(doc):
        ''' boilermake
	devices.setup()
        devices.set_in('Button',devices.Button(16, GPIO.PUD_DOWN))
	devices.set_in('TempSensor',devices.TemperatureHumiditySensor(7))
	devices.set_out('Servo', devices.Servo(12))
	devices.set_out('RgbLed', devices.RgbLed(11, 13, 15, 100))
	devices.set_out('BlueLed', devices.Led(19,120))
	devices.set_out('GreenLed', devices.Led(18,120))
	devices.set_out('RedLed', devices.Led(22, 120))
        '''
	try:
		global page_decls
		page_decls = {}
                global sense
                sense = SenseHat()
		if 'Pages' not in doc:
			raise Exception("Malformed doc {}".format(json.dumps(doc)))
		for page_doc in doc['Pages']:
			page_decl = translate_page_decl(page_doc)
			page_decls[page_decl.name] = page_decl
		if 'Main' not in page_decls:
			raise Exception('Malformed doc - no main {}'.format(json.dumps(doc)))
		page_decls['Main'].interp()
		sense.clear()
                #devices.cleanup()
	except Exception as e:
                if sense:
                    sense.clear()
		#devices.cleanup()
		raise e
开发者ID:boilermake2015iot,项目名称:piclient,代码行数:31,代码来源:interpreter.py


示例7: get_sensors

def get_sensors(precision):
	sense = SenseHat()
	data = {}
	data['temperature'] = round(sense.get_temperature(), precision)
	data['pressure'] = round(sense.get_pressure(), precision)
	data['humidity'] = round(sense.get_humidity(), precision)
	return data
开发者ID:sofixa,项目名称:Pi-Sense-Hat-to-InfluxDB,代码行数:7,代码来源:sense-influxdb.py


示例8: main

def main():

	#initialize Pygame which handles joystick inputs on SenseHat
	pygame.init()
	pygame.display.set_mode((640, 480))

	subprocess.call(["mpc","clear"])
	subprocess.call(["mpc","load","playlist1"])
	subprocess.call(["mpc","enable","1"])


	# SenseHat initialization and configuration
	sense = SenseHat()
	sense.low_light = True
	sense.rotation = 90

	#initialize last weather update time
	last_update_time = 0

	#Main loop

	while True:  

		#Handle Senshat Joystick inputs
		for event in pygame.event.get():
			#if event.type == KEYDOWN:
				#radio_commands(event)
				#print('DN')
			if event.type == KEYUP:
				radio_commands(event)
				print('SenseHat Input')
开发者ID:amonsain,项目名称:Raspberry,代码行数:31,代码来源:SenseRadio.py


示例9: __init__

class RunTime:
    def __init__(self):
        self.apps = []
        self.apps.append(Clock())
        self.sense = SenseHat()

    def start(self):
        pygame.init()
        pygame.display.set_mode((640, 480))
        running = True
        icon = self.apps[0].get_icon()
        self.display_icon(icon)
        """
		while running:
			for event in pygame.event.get():
				if event.type == QUIT:
					running = False
				else:
					if event.key == K_RIGHT:
						self.sense.clear()
					elif event.key == K_LEFT:
						self.display_icon(icon)
					else:
						running = False
		"""

    def display_icon(self, icon):
        e = [0, 0, 0]
        padded_icon = []
        for i in range(0, len(icon)):
            padded_icon.append(e)
            padded_icon.extend(icon[i])
            padded_icon.append(e)
        padded_icon.extend([e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e])
        self.sense.set_pixels(padded_icon)
开发者ID:yjlo123,项目名称:runtime,代码行数:35,代码来源:RunTime.py


示例10: VibrateSensor

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
开发者ID:gdfuego,项目名称:pybrate,代码行数:27,代码来源:pybrate.py


示例11: readSensor

	def readSensor(self):
		from sense_hat import SenseHat
		senseHat = SenseHat()
		self.humidity   = senseHat.get_humidity()
		self.tempH      = senseHat.get_temperature_from_humidity()
		self.pressure   = senseHat.get_pressure() + PRESSURE_OFFSET
		self.tempP      = senseHat.get_temperature_from_pressure()
		self.mesureTime = time.time()
开发者ID:vrampal,项目名称:RpiWeather,代码行数:8,代码来源:SenseHat.py


示例12: __init__

class Sensor :
    def __init__(self) :
        self.sensor_id = "sensor hat"
        self.fileplace = 'tempplace.conf'
        self.total_count = 0
        self.device_file = "/dev/null"
        self.sense = SenseHat()
        self.place = self.readplacename()

    def reinit(self) :
        self.__init__()

    def sensorid(self) :
        return self.sensor_id

    def total_count(self) :
        return self.total_count

    def placename(self):
        return self.place

    def setplacename(self, name):
        self.place = setplace_db(name)

    def readplacename(self):
        self.place = getplace_db()
        return self.place

    def read_temp(self):
        temp = "null"
        tt = self.sense.get_temperature()
        th = self.sense.get_temperature_from_humidity()
        tf = self.sense.get_temperature_from_pressure()

        tf = float(tt)
        tf = tf - 10.0 # Fattore di correzione
        tt = round(tt, 2)
        tc = round(tf, 2)
        th = round(th, 2)
        tf = round(tf, 2)

        self.total_count += 1
        return str(tc)

    def read_pressure(self):
        p = self.sense.get_pressure()
        p = round(p, 2)
        self.total_count += 1
        return str(p)

    def read_humidity(self):
        h = self.sense.get_humidity()
        h = round(h, 2)
        self.total_count += 1
        return str(h)

    def sensordebug(self):
        return 'Sense Hat'
开发者ID:ernitron,项目名称:temperature-server,代码行数:58,代码来源:SensorHat.py


示例13: get_press

def get_press(altitude):
 # enable SenseHat modules
    from sense_hat import SenseHat
    
    sense=SenseHat()
    raw_pressure = sense.get_pressure()
    pressure = raw_pressure/math.pow(1 - 0.0065*altitude/288.15,5.25588)
    #print(pressure)
    return pressure
开发者ID:amonsain,项目名称:Raspberry,代码行数:9,代码来源:PressureAvg.py


示例14: __init__

class Screen:
    def __init__(self):
        self.sense = SenseHat()
        self.general_level = 0
        self.wait_time = 4
        self.cur_time = 0
        self.clear()
        self.balance = 0

    def clear(self):
        for i in range(SIZE):
            for j in range(SIZE):
                self.sense.set_pixel(i, j, BLACK)

    def clear_col(self, x):
        for i in range(0, 7):
            self.sense.set_pixel(x, i, BLACK)

    def plot_bar(self, x, height, colors=None):
        if colors is None:
            colors = BAR_COLORS
        self.clear_col(x)
        for i in range(height):
            self.sense.set_pixel(x, 7 - i, colors[7 - i])

    def plot_balance(self):
        for i in range(SIZE):
            self.plot_bar(i, max(1, self.general_level), BAR_COLORS)

    def show_amount(self):
        self.show_message(str(self.balance), color=list(BAR_COLORS[min(7, 8 - self.general_level)]))

    def show_message(self, message, speed=0.1, color=[255, 255, 255]):
        self.sense.show_message(message, speed, color)
        self.plot_balance()

    """ Parses an input in the form:
        balance percentage """

    def parse_input(self, line):
        self.cur_time = 0
        # Split balance and percentage.
        [self.balance, percent] = [float(x) for x in line.split()]
        self.general_level = int(round(min(max(0, percent), 100) / 100.0 * SIZE))
        self.draw_check()

    def draw_check(self):
        types = [BLACK, GREEN]
        pixels = [types[CHECK[i / SIZE][i % SIZE]] for i in range(SIZE * SIZE)]
        self.sense.set_pixels(pixels)

    def no_text(self):
        self.cur_time += SLEEP_TIME
        if self.cur_time > self.wait_time:
            self.cur_time = 0
            self.show_amount()
开发者ID:albertnez,项目名称:pep,代码行数:56,代码来源:screen.py


示例15: SH_show_colour

def SH_show_colour(): # Thread to update colour on LED matrix
    sh = SenseHat()
    global running
    while running:
        red_val =red_var.get()
        green_val =green_var.get()
        blue_val =blue_var.get()
        time.sleep(0.05)
        sh.clear(red_val,green_val,blue_val)
    sh.clear([0,0,0])
开发者ID:topshed,项目名称:HATColourSlider,代码行数:10,代码来源:HATColourSlider.py


示例16: login

def login():
    form = LoginForm()
    if form.validate_on_submit():
        sense = SenseHat()
        sense.show_message("Hello {}!".format(form.openid.data))
        #flash('Login requested for OpenID="{}", remember_me={}'.format(form.openid.data, form.remember_me.data))
        return redirect('/index')
    return render_template('login.html', 
                           title='Sign In',
                           form=form)
开发者ID:Daniel-Rix,项目名称:personal-trainer,代码行数:10,代码来源:views.py


示例17: Hat

class Hat(object):
    ''' `sensed` sensor module for the Raspberry Pi Sense HAT. This
        module returns a dictionary of all built in sensors. '''

    def __init__(self, config: DotMap) -> None:
        if config.sensed.test is not True:
            from sense_hat import SenseHat
            self.sense = SenseHat()

    def get_data(self) -> dict:
        # Environmental sensors
        humid = self.sense.humidity
        temp = self.sense.temperature
        temp_h = self.sense.get_temperature_from_humidity()
        temp_p = self.sense.get_temperature_from_pressure()
        press = self.sense.pressure

        # IMU (inertial measurement unit) sensors
        orient_r = self.sense.orientation_radians
        orient_d = self.sense.orientation
        compass = self.sense.compass
        compass_r = self.sense.compass_raw
        gyro = self.sense.gyroscope
        gyro_r = self.sense.gyroscope_raw
        accel = self.sense.accelerometer
        accel_r = self.sense.accelerometer_raw

        return {'environment': {'humidity': humid,
                                'temperature': temp,
                                'temperature_h': temp_h,
                                'temperature_p': temp_p,
                                'pressure': press},
                'imu': {'orientation_rad': orient_r,
                        'orientation_deg': orient_d,
                        'compass': compass,
                        'compass_r': compass_r,
                        'gyroscope': gyro,
                        'gyroscope_r': gyro_r,
                        'accelerometer': accel,
                        'accelerometer_raw': accel_r}}

    def test(self) -> dict:
        return {'environment': {'humidity': 1,
                                'temperature': 2,
                                'temperature_h': 3,
                                'temperature_p': 4,
                                'pressure': 5},
                'imu': {'orientation_rad': 6,
                        'orientation_deg': 7,
                        'compass': 8,
                        'compass_r': 9,
                        'gyroscope': 10,
                        'gyroscope_r': 11,
                        'accelerometer': 12,
                        'accelerometer_raw': 13}}
开发者ID:sli,项目名称:sensed,代码行数:55,代码来源:hat.py


示例18: SensorClient

class SensorClient(object):

	def __init__(self, broker, broker_port):
		self.sense=SenseHat()
		self.broker=broker
		self.broker_port=broker_port
		self.client_id=uname()[1]
		
		sub_topics=	{	"temperature"	:	lambda: self.sense.get_temperature(),
					"humidity"	:	lambda: self.sense.get_humidity(),
					"pressure"	:	lambda:	self.sense.get_pressure() }

		self.topics={}
		root_topic="%s/sensehat"%self.client_id
		for sub_topic in sub_topics.keys():
			topic="%s/%s"%(root_topic, sub_topic)
			self.topics[topic]=sub_topics[sub_topic]
			

	def on_connect(self, client, userdate, flags, rc):
		for topic in sorted(self.topics):
			print "Subscribing to %s"%(topic)
			client.subscribe( topic )
		self.publish_sensor_topics()

	# If we recieve the payload of '?' (question-mark)
	# Then publish the value to the topic
	def on_message(self, client, userdata, msg):
		if msg.payload=="?":
			try:
				self.publish_topic( msg.topic )
			except Exception as e:
				print "Error when trying to publish '%s' ?"%msg.topic
		else:
			print "Ignoring message %s=%s"%(msg.topic, msg.payload)
		
	
	def publish_topic( self, topic ):
		topic_value=self.topics[topic]() # execute the Lambda to fetch value
		print "Publishing %s=%s"%(topic, topic_value)
		self.mqtt_client.publish( topic, topic_value )

	# Publish all topics (called when we first connect)
	def publish_sensor_topics(self):
		for topic in sorted(self.topics):
			self.publish_topic( topic )

	def run(self):
		self.mqtt_client=mqtt.Client( self.client_id )
		self.mqtt_client.on_message=self.on_message
		self.mqtt_client.on_connect=self.on_connect
		self.mqtt_client.connect(broker, broker_port)
		self.mqtt_client.loop_forever()
开发者ID:midijohnny,项目名称:sensehat,代码行数:53,代码来源:sensor_client.py


示例19: main

def main(v):
	if v is None:
		v=0.5
	else:
		v=float(v)
	sense=SenseHat()
	for i in range(8):
 		for j in range(8):
    			(h,s,v)=XY_to_HSV(i,j,v)
    			(r,g,b)=HSV_to_RGB(h,s,v)
    			#print (i,j,int(r),int(g),int(b),int(h),int(s),int(v))
    			sense.set_pixel(i,j,int(r),int(g),int(b))
开发者ID:mskovacic,项目名称:Projekti,代码行数:12,代码来源:sense_proba.py


示例20: update

 def update(self):
     """Get the latest data from Sense HAT."""
     from sense_hat import SenseHat
     sense = SenseHat()
     temp_from_h = sense.get_temperature_from_humidity()
     temp_from_p = sense.get_temperature_from_pressure()
     t_cpu = get_cpu_temp()
     t_total = (temp_from_h + temp_from_p) / 2
     t_correct = t_total - ((t_cpu - t_total) / 1.5)
     t_correct = get_average(t_correct)
     self.temperature = t_correct
     self.humidity = sense.get_humidity()
     self.pressure = sense.get_pressure()
开发者ID:Teagan42,项目名称:home-assistant,代码行数:13,代码来源:sensehat.py



注:本文中的sense_hat.SenseHat类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python time_utils.ts2datetime函数代码示例发布时间:2022-05-27
下一篇:
Python i18n._函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap