Пример #1
0
if __name__ == "__main__":
    s = SenseHat()
    temp = min(
        [s.get_temperature_from_humidity(),
         s.get_temperature_from_pressure()]) - 4.0  # correction
    hum = s.get_humidity()
    s.rotation = 180
    pres = s.get_pressure() / 1000.0
    s.low_light = True
    t = datetime.datetime.now().strftime("%b %d, %Y. %H:%M")

    for i in range(0, 29 - 8):
        p = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                         "img_{}.png".format(i))
        s.load_image(p)
        time.sleep(0.3)
    time.sleep(1)
    for i in reversed(range(0, 29 - 8)):
        p = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                         "img_{}.png".format(i))
        s.load_image(p)
        time.sleep(0.3)
    time.sleep(1)

    for i in range(2):
        s.show_message(t, scroll_speed=0.05, text_colour=[255, 0, 0])
        message = "T: {:1.1f} C".format(temp)
        s.show_message(message, scroll_speed=0.05, text_colour=[239, 83, 80])
        message = "H: {:1.1f}%".format(hum)
        s.show_message(message, scroll_speed=0.05, text_colour=[38, 166, 154])
Пример #2
0
#!/usr/bin/python
from sense_hat import SenseHat

sense = SenseHat()
sense.clear()
sense.load_image("rakuten.png")
			hue = hue - 1.0
	if currentMode == 1:
		if lastRun is not currentMode:
			sense.set_rotation(0)
			lastRun = currentMode
		temp = sense.temp
		temp = temp*1.8 + 32
		humidity = sense.get_humidity()
		humidity_value = 64 * humidity / 100
		humidity_value = round(humidity_value,1)
		temp = round(temp, 1)
		sense.show_message("Temp: " + str(temp) + " Humidity: " + str(humidity_value) + "%", scroll_speed=.05)
		currentMode = 0
	if currentMode == 2:
		if lastRun is not currentMode:
			sense.load_image("/home/pi/logo.png")
			lastRun = currentMode
		x, y, z = sense.get_accelerometer_raw().values()
		x = round(x, 0)
		y = round(y, 0)
		if x == -1:
			sense.set_rotation(180)
		elif y == 1:
			sense.set_rotation(270)
		elif y == -1:
			sense.set_rotation(90)
		else:
			sense.set_rotation(0)

	if currentMode == 3:
		if lastRun is not currentMode:
Пример #4
0
import sys
import json
from sense_hat import SenseHat

sense = SenseHat()
lines = sys.stdin.readlines()

if len(sys.argv) > 1:
	# Load the image from file
	try:
		sense.load_image(sys.argv[1])
	except Exception e:
		print("ERROR failed to load image")
		exit(1)
elif len(lines) > 0:
	# Expects a 64 length list (8x8) each containing a smaller list of the [R, G, B] values. 
	try:
		sense.set_pixels(json.loads(lines))
	except:
		print("ERROR failed to parse JSON")
		exit(2)
else:
	# Default action
	print(sense.get_pixels())
Пример #5
0
from sense_hat import SenseHat
sense = SenseHat()

sense.load_image("/home/pi/testit1/CoffeeCup.gif")
sense.low_light = False
Пример #6
0
GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.IN)

sense = SenseHat()
sense.set_rotation(180)
#load initial image if wanted

GPIO.add_event_detect(21, GPIO.FALLING, bouncetime=800)  # add rising edge detection on a channel
currentCompany = "none"
time_elapsed = 0

while True:
	time.sleep(0.1)

	if GPIO.event_detected(21):
		sense.load_image("smile.png")
		response = requests.post("http://warren.ngrok.io/coin", data = {"key":"value"})
		
	    	time.sleep(1)
		print('Button pressed')
		sense.load_image(response.json()["selectedCompany"] + ".png")
		time.sleep(1)

		if (float(response.json()["coeficient"]) > 1):
			sense.load_image("arrow_up.png")
			time.sleep(1)
		else:
			sense.load_image("arrow_down.png")
			time.sleep(1)
		
		sense.show_message(str( int(response.json()["value"]) * float(response.json()["coeficient"]) ) + "e", text_colour=[0, 255, 0])
Пример #7
0
# loop
play_game = True

### add main def and play again###
while play_game == True:
  play_again = 1
  time.sleep(1)

  sense.set_pixels(enemySea)
  time.sleep(1)

  ### Begin the main game ###
  main()

  ### Play again? ###
  print ('Would you like to play again?')
    
  sense.load_image("choice.png")

  while play_again == 1:
    for event in pygame.event.get():
      if event.type == KEYDOWN:
        if event.key == K_DOWN:
          play_again = 0
          play_game = False
          print ('goodbye')
          break

        elif event.key == K_UP:
          play_again = 0
Пример #8
0
#!/usr/bin/python
from sense_hat import SenseHat

sense = SenseHat()
sense.clear()
sense.load_image("space_invader.png")
Пример #9
0
        yt = (p - offset) // 3
        sense.set_pixel(xt + xd, yt + yd, r * NUMS[p], g * NUMS[p],
                        b * NUMS[p])


# Displays a two-digits positive number (0-99)
def show_number(val, r, g, b):
    abs_val = math.trunc(float(val))
    tens = abs_val // 10
    units = abs_val % 10
    if (abs_val > 9): show_digit(tens, OFFSET_LEFT, OFFSET_TOP, r, g, b)
    show_digit(units, OFFSET_LEFT + 4, OFFSET_TOP, r, g, b)


sense.clear()
sense.load_image("img/balena.png")
time.sleep(2)
sense.clear()

count = 0

RED = [255, 0, 0]
GREEN = [0, 255, 0]
BLUE = [0, 0, 255]
ORANGE = [255, 69, 0]


def read_cpu_temperature():
    cpu_temp = subprocess.check_output("vcgencmd measure_temp",
                                       shell=True).decode('utf-8')
    temperature = float(cpu_temp.split("=")[1].split("'")[0])
Пример #10
0
from sense_hat import SenseHat
s = SenseHat()
s.flip_h()
s.show_message("Hello Master")
s.load_image("sword1.png")
    jaff_open_mouth = True
    espeak.synth(text_to_speech)
    while espeak.is_playing():
        time.sleep(0.3)
        jaff_open_mouth = not jaff_open_mouth
        sense.load_image("jaffar3.png" if jaff_open_mouth else "jaffar.png")
    sense.load_image("jaffar.png")


# configuration
enable_cheerlights = True

# print('Initiate Sense Hat')
sense = SenseHat()
sense.low_light = False
sense.load_image("jaffar.png")

# add a backgroudn thread to flip image horizonally
thread1 = threading.Thread(target=flip_image_horizontally)
thread1.start()

# print('Initiate TTS')
#espeak.set_voice("en-us+f5") # female's voice
espeak.set_voice("en-us+m3")  # male's voice
speak("Initiate Jaffar's Pi Bot!")

# print('Set up tweepy')
with open('twitter_auth.json') as file:
    secrets = json.load(file)

# print('Authenticate the access token')
Пример #12
0
class SenseHATPlugin(EPLPluginBase):
    def __init__(self, init):
        super(SenseHATPlugin, self).__init__(init)
        self.getLogger().info("SenseHATPlugin initialised with config: %s" %
                              self.getConfig())
        self.sense = SenseHat()

    @EPLAction("action<integer >")
    def setRotation(self, angle=None):
        """
		Orientation of the message/image 
		
		@param message:	Orientation of the message, The supported values of orientation are 0, 90, 180, and 270..
		"""
        if angle == None: angle = 90

        self.sense.set_rotation(angle)

    @EPLAction("action<integer, integer, integer, integer, integer >")
    def setPixel(self, x, y, r, g, b):
        self.sense.set_pixel(x, y, r, g, b)

    @EPLAction("action< sequence <sequence <integer> > >")
    def setPixels(self, pixels):
        if not isinstance(pixels, list): return
        self.sense.set_pixels(pixels)

    @EPLAction("action< >")
    def clear(self):
        self.sense.clear()

    @EPLAction("action< integer, integer, integer >")
    def Clear(self, r, g, b):
        self.sense.clear(r, g, b)

    @EPLAction("action<string >")
    def showMessage(self, message):
        self.sense.show_message(message)

    @EPLAction("action<string, float, sequence<integer>, sequence<integer> >")
    def displayMessage(self,
                       message,
                       scrollingSpeed=None,
                       textColor=None,
                       backgroundColor=None):
        """
		This method will scrolls a text message across the LED Matrix.
				
		@param message:	The Scrolling message to be displayed.
		@param scrollingSpeed:	Scrolling message speed.
		@param textColor:	 The text color of the scrolling message i.e [R G B] .
		@param backgroundColor:	 The background color of the scrolling message [R G B].
		
		"""
        if scrollingSpeed == None: scrollingSpeed = 0.1
        if (textColor == None) or (not isinstance(textColor, list)):
            textColor = [255, 255, 255]
        if (backgroundColor
                == None) or (not isinstance(backgroundColor, list)):
            backgroundColor = [0, 0, 0]

        self.sense.show_message(message,
                                scroll_speed=scrollingSpeed,
                                text_colour=textColor,
                                back_colour=backgroundColor)

    @EPLAction("action<string >")
    def showLetter(self, letter):
        if not isinstance(letter, basestring): return
        self.sense.show_letter(letter)

    @EPLAction("action<boolean >")
    def lowLight(self, islowLight):
        self.sense.low_light = islowLight

    @EPLAction("action<string >")
    def loadImage(self, imagePath):
        self.sense.load_image(imagePath)

    ##########################################################################################################

    #				Environmental sensors

    ##########################################################################################################

    @EPLAction("action<> returns float")
    def getHumidity(self):
        humidity = self.sense.get_humidity()
        return round(humidity, 2)

    @EPLAction("action<> returns float")
    def getTemperature(self):
        temp = self.sense.get_temperature()
        return round(temp, 2)

    @EPLAction("action<> returns float")
    def getTemperatureFromHumidity(self):
        temp = self.sense.get_temperature_from_humidity()
        return round(temp, 2)

    @EPLAction("action<> returns float")
    def getTemperatureFromPressure(self):
        temp = self.sense.get_temperature_from_pressure()
        return round(temp, 2)

    @EPLAction("action<> returns float")
    def getPressure(self):
        pressure = self.sense.get_pressure()
        return round(pressure, 2)

    ##########################################################################################################

    #				Joystick

    ##########################################################################################################

    @EPLAction("action<boolean > returns com.apamax.sensehat.InputEvent")
    def waitForEvent(self, emptyBuffer=False):
        jevent = self.sense.stick.wait_for_event(emptybuffer=emptyBuffer)
        evtInstance = Event(
            'com.apamax.sensehat.InputEvent', {
                "actionValue": jevent.action,
                "directionValue": jevent.direction,
                "timestamp": jevent.timestamp
            })
        return evtInstance

    @EPLAction("action<> returns sequence<com.apamax.sensehat.InputEvent >")
    def getEvents(self):

        events = list()
        for event in self.sense.stick.get_events():
            evtInstance = Event(
                'com.apamax.sensehat.InputEvent', {
                    "actionValue": jevent.action,
                    "directionValue": jevent.direction,
                    "timestamp": jevent.timestamp
                })
            events.append(evtInstance)

        return events

    def pushed_up(event):
        if event.action == ACTION_RELEASED:
            joyevt = Event('com.apamax.sensehat.JoystickControl',
                           {"controlType": 1})
            Correlator.sendTo("sensedhat_data", joyevt)

    def pushed_down(event):
        if event.action == ACTION_RELEASED:
            joyevt = Event('com.apamax.sensehat.JoystickControl',
                           {"controlType": 2})
            Correlator.sendTo("sensedhat_data", joyevt)

    def pushed_left(event):
        if event.action == ACTION_RELEASED:
            joyevt = Event('com.apamax.sensehat.JoystickControl',
                           {"controlType": 3})
            Correlator.sendTo("sensedhat_data", joyevt)

    def pushed_right(event):
        if event.action == ACTION_RELEASED:
            joyevt = Event('com.apamax.sensehat.JoystickControl',
                           {"controlType": 4})
            Correlator.sendTo("sensedhat_data", joyevt)

    def pushed_in(event):
        if event.action == ACTION_RELEASED:
            self.sense.show_message(str(round(sense.temp, 1)), 0.05, b)

    ##########################################################################################################

    #				IMU Sensor

    ##########################################################################################################

    @EPLAction("action<boolean, boolean, boolean >")
    def setIMUConfig(self, compassEnabled, gyroscopeEnabled,
                     accelerometerEnabled):
        '''
     	Enables and disables the gyroscope, accelerometer and/or magnetometer contribution to the get orientation functions
     
     	@param compassEnabled :        enable compass
     	@param gyroscopeEnabled :      enable gyroscope
      	@param accelerometerEnabled :  enable accelerometer
      	
     	'''
        self.sense.set_imu_config(compassEnabled, gyroscopeEnabled,
                                  accelerometerEnabled)

    @EPLAction("action< > returns com.apamax.sensehat.IMUData")
    def getOrientationRadians(self):
        '''		
     	Gets the current orientation in radians using the aircraft principal axes of pitch, roll and yaw
     
     	@return event with pitch, roll and yaw values. Values are floats representing the angle of the axis in radians
     
		'''

        pitch, roll, yaw = self.sense.get_orientation_radians().values()
        evtInstance = Event('com.apamax.sensehat.IMUData', {
            "pitch": pitch,
            "roll": roll,
            "yaw": yaw
        })
        return evtInstance

    @EPLAction("action< > returns com.apamax.sensehat.IMUData")
    def getOrientationDegrees(self):
        '''		
     	Gets the current orientation in degrees using the aircraft principal axes of pitch, roll and yaw
     
     	@return event with pitch, roll and yaw values. Values are Floats representing the angle of the axis in degrees
     
		'''

        pitch, roll, yaw = self.sense.get_orientation_degrees().values()
        evtInstance = Event('com.apamax.sensehat.IMUData', {
            "pitch": pitch,
            "roll": roll,
            "yaw": yaw
        })
        return evtInstance

    @EPLAction("action< > returns com.apamax.sensehat.IMUData")
    def getOrientation(self):
        '''
     	@return event with pitch, roll and yaw representing the angle of the axis in degrees
     
		'''

        pitch, roll, yaw = self.sense.get_orientation().values()
        evtInstance = Event('com.apamax.sensehat.IMUData', {
            "pitch": pitch,
            "roll": roll,
            "yaw": yaw
        })
        return evtInstance

    @EPLAction("action< > returns float")
    def getCompass(self):
        '''
		Calls set_imu_config internally in Python core to disable the gyroscope and accelerometer
     	then gets the direction of North from the magnetometer in degrees
     
     	@return The direction of North
     	
		'''
        return self.sense.get_compass()

    @EPLAction("action< > returns com.apamax.sensehat.IMUDataRaw")
    def getCompassRaw(self):
        '''
		
     	Gets the raw x, y and z axis magnetometer data     
     	@return event representing the magnetic intensity of the axis in microteslas (uT)
     
     	'''
        x, y, z = self.sense.get_compass_raw().values()
        evtInstance = Event('com.apamax.sensehat.IMUDataRaw', {
            "x": x,
            "y": y,
            "z": z
        })
        return evtInstance

    @EPLAction("action< > returns com.apamax.sensehat.IMUData")
    def getGyroscope(self):
        '''
		Calls set_imu_config internally in Python core to disable the magnetometer and accelerometer
     	then gets the current orientation from the gyroscope only
     	
     	@return event with pitch, roll and yaw representing the angle of the axis in degrees
     
		'''

        pitch, roll, yaw = self.sense.get_gyroscope().values()
        evtInstance = Event('com.apamax.sensehat.IMUData', {
            "pitch": pitch,
            "roll": roll,
            "yaw": yaw
        })
        return evtInstance

    @EPLAction("action< > returns com.apamax.sensehat.IMUDataRaw")
    def getGyroscopeRaw(self):
        '''		
     	Gets the raw x, y and z axis gyroscope data     
     	@return event representing the rotational intensity of the axis in radians per second
     
     	'''
        x, y, z = sense.get_gyroscope_raw().values()
        evtInstance = Event('com.apamax.sensehat.IMUDataRaw', {
            "x": x,
            "y": y,
            "z": z
        })
        return evtInstance

    @EPLAction("action< > returns com.apamax.sensehat.IMUData")
    def getAccelerometer(self):
        '''
		Calls set_imu_config in Python core to disable the magnetometer and gyroscope
        then gets the current orientation from the accelerometer only
     
        @return Object representing the angle of the axis in degrees
             
		'''

        pitch, roll, yaw = self.sense.get_accelerometer().values()
        evtInstance = Event('com.apamax.sensehat.IMUData', {
            "pitch": pitch,
            "roll": roll,
            "yaw": yaw
        })
        return evtInstance

    @EPLAction("action< > returns com.apamax.sensehat.IMUDataRaw")
    def getAccelerometerRaw(self):
        '''		
     	Gets the raw x, y and z axis accelerometer data    
     	@return event representing the acceleration intensity of the axis in Gs
     
     	'''
        x, y, z = sense.get_accelerometer_raw().values()
        evtInstance = Event('com.apamax.sensehat.IMUDataRaw', {
            "x": x,
            "y": y,
            "z": z
        })
        return evtInstance
Пример #13
0
#!/usr/bin/python
from sense_hat import SenseHat
from imapclient import IMAPClient
import time
import sys

HOSTNAME = 'imap.gmail.com'
USERNAME = '******'
PASSWORD = '******'
MAILBOX = 'Inbox'
NEWMAIL_OFFSET = 0
MAIL_CHECK_FREQ = 20

sense = SenseHat()
sense.load_image("hello.png")

try:
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)
except:
    connected = False
    sense.load_image("error.png")
else:
    connected = True
    sense.load_image("done.png")
    select_info = server.select_folder(MAILBOX)

try:
    while connected:
        folder_status = server.folder_status(MAILBOX, 'UNSEEN')
        newmails = int(folder_status['UNSEEN'])
Пример #14
0
from time import sleep
import sys
import os
from sense_hat import SenseHat

sense = SenseHat()
sense.clear()
sense.load_image('./images/space_invader.png')

while True:
    try:
        sleep(1)

    except KeyboardInterrupt:
        print('Interrupted')
        sense.clear()
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

sense.clear()
Пример #15
0
#!/usr/bin/python
from sense_hat import SenseHat

sense = SenseHat()
sense.clear()
sense.load_image("plus.png")
Пример #16
0
import locale
import sys
import enterMod
from pytz import timezone

sense = SenseHat()

sense.low_light = True
sense.set_rotation(180)
sense.clear()

inky = []
for nbr in range(1, 15):
    inky.append(
        sense.load_image("/home/pi/sensehat-examples/sprites/inky" + str(nbr) +
                         ".png",
                         redraw=False))
clyde = []
for nbr in range(1, 15):
    clyde.append(
        sense.load_image("/home/pi/sensehat-examples/sprites/clyde" +
                         str(nbr) + ".png",
                         redraw=False))

pinky = []
for nbr in range(1, 15):
    pinky.append(
        sense.load_image("/home/pi/sensehat-examples/sprites/pinky" +
                         str(nbr) + ".png",
                         redraw=False))
Пример #17
0
                                        song = song + 1
                                        print ("I played a new song")
                                        print (song)
                                        pygame.mixer.music.load(songs_found[song])
                                        pygame.mixer.music.play()
                                        animation()
                                        

        except:
                print ("No MP3s")
                songs = 1
                print (songs)
                sense.show_message("NO MP3s", text_colour = [255, 0, 0])
                ####scroll NO MP3S

sense.load_image("/home/pi/Astro_MP3/Images8x8/hi.png")
time.sleep(2)
pygame.mixer.music.load("/home/pi/Astro_MP3/MP3_files/Intro.mp3")
sense.load_image("/home/pi/Astro_MP3/Images8x8/Rasp.png")
pygame.mixer.music.play()
time.sleep(3.8)

while running:
    Co_Ord = {"0, 0": "A" }
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            '''Turns Pixel Off'''
            sense.set_pixel(x, y, 0, 0, 0)  # Black 0,0,0 means OFF

            sense.set_pixels(music_interface)
atexit.register(stopMotor)

def stopMotor():
    print("Wow! thats much better!")
    mh.getMotor(2).run(Adafruit.MotorHAT.RELEASE)

def runMotor():
    print("Too hot! Cooling myself down!")
    myMotor=mh.getMotor(MOTOR)
    myMotor.run(Adafruit.MotorHAT.FORWARD)
    myMotor.setSpeed(150)

while(True):    
    v=s.get_humidity()
    print("%f" % s.get_humidity())
    if(v>40 and v<50):
        s.load_image("/home/pi/triniBot/assets/8x8_red_smiley.png",True)
    elif(v>=50 ):
        s.load_image("/home/pi/triniBot/assets/8x8_red_happy.png",True)
        stopMotor()
    elif(v>=60 and v<100):
        s.load_image("/home/pi/triniBot/assets/8x8_red_angry.png",True)
        runMotor()

    key_press, run = logger.check_input()  

    if key_press:
        logger.on_key_press()
        print("Writing data to log")
Пример #19
0
        color=[120,220,0] #Green
        tmax = 25
    elif temp >= 25 and temp <= 32:
        color=[255,140,0] #Orange
        tmax = 25
    elif temp >= 33:
        color=[233,33,33] #Red
        tmax = 40
    else:
        color=[0,0,0] #White
        tmax = 0
    temp = temp - (tmax - 8)
    for y in range(0, temp+1):
        sense.set_pixel(7, 7-y, color)
    for y in range(temp+1, 7):
        sense.set_pixel(7, 7-y, 0, 0, 0)

while True:
    # Download the JSON data from OpenWeatherMap.org's API.
    getData()
    
    print('Current weather in %s:' % (weatherData['name']))
    print(weatherData['weather'][0]['main'])
    print(weatherData['main']['temp'])
    print(weatherData['main']['pressure'])
    print(weatherData['main']['humidity'])
    
    sense.load_image("icon/"+weatherData['weather'][0]['icon']+".png")
    thermometer(weatherData['main']['temp'])
    
    time.sleep(180)
Пример #20
0
 if event.key == K_DOWN and y < 7:
     new_y = y + 1
 elif event.key == K_UP and y > 0:
     new_y = y - 1
 elif event.key == K_RIGHT and x < 6:
     new_x = x + 2
     new_x1 = x1 +2
 elif event.key == K_LEFT and x > 0:
     new_x = x - 2
     new_x1 = x1 -2
 elif event.key == K_RETURN:
     print('press')
     # display a png or animation
     if pos in pngs:
         sh.set_rotation(90)
         sh.load_image("pngs/dec"+str(int(pos))+".png")
         time.sleep(5)
         sh.set_rotation(0)
         sh.set_pixels(cal)
     elif pos in anis: # days with animations
         if int(pos) == 5:
             ani.play5()
         elif int(pos) == 10:
             ani.play10()
         elif int(pos) == 15:
             ani.play15()
         elif int(pos) == 1:
             ani.play1()
         elif int(pos) == 20:
             ani.play20()
         elif int(pos) == 23:
Пример #21
0
sense.low_light = True

try:
    data = sys.argv[1]
except IndexError:
    display_pixels = sense.get_pixels()
    img = Image.new("RGB", (8, 8), "black")
    pixels = img.load()
    ## Set pixels ...
    idx = 0
    for i in range(8):
        for j in range(8):
            pixels[i, j] = tuple(display_pixels[idx])
            idx += 1
    img = img.rotate(-90)
    output = StringIO.StringIO()
    img.save(output, format="PNG")
    print base64.b64encode(output.getvalue())
    sys.exit(0)

if os.path.exists(sys.argv[1]):
    sense.clear()
    sense.load_image(sys.argv[1])
else:
    try:
        img = base64.b64decode(sys.argv[1])
        sense.clear()
        sense.load_image(img)
    except TypeError:
        sys.exit(1)
Пример #22
0
from sense_hat import SenseHat
import time

sense = SenseHat()
sense.clear()
for i in range(1, 100):
    sense.load_image("pics/1.png")
    time.sleep(0.5)
    sense.load_image("pics/2.png")
    time.sleep(0.5)
    sense.load_image("pics/3.png")
    time.sleep(0.5)
Пример #23
0
    'Loads an image file, converts it to RGB format and displays it on the LED matrix. The image must be 8 x 8 pixels in size.'
)
parser.add_argument('file_path',
                    type=str,
                    help='The file system path to the image file to load.')
parser.add_argument(
    'redraw',
    type=str2bool,
    nargs='?',
    default=True,
    help=
    'Whether or not to redraw the loaded image file on the LED matrix. Defaults to True'
)

args = parser.parse_args()

try:
    path = './led/{}.png'.format(
        re.sub('[^a-zA-Z0-9_\-\/]+', '', args.file_path))

    from sense_hat import SenseHat

    sense = SenseHat()

    result = sense.load_image(path, args.redraw)

    # A list containing 64 smaller lists of [R, G, B] pixels (red, green, blue) representing the loaded image after RGB conversion.
    finish({"result": result})
except Exception, e:
    finish(e, 1)
Пример #24
0
 if event.key == K_DOWN and y < 7:
     new_y = y + 1
 elif event.key == K_UP and y > 0:
     new_y = y - 1
 elif event.key == K_RIGHT and x < 6:
     new_x = x + 2
     new_x1 = x1 + 2
 elif event.key == K_LEFT and x > 0:
     new_x = x - 2
     new_x1 = x1 - 2
 elif event.key == K_RETURN:
     print('press')
     # display a png or animation
     if pos in pngs:
         sh.set_rotation(90)
         sh.load_image("pngs/dec" + str(int(pos)) + ".png")
         time.sleep(5)
         sh.set_rotation(0)
         sh.set_pixels(cal)
     elif pos in anis:  # days with animations
         if int(pos) == 5:
             ani.play5()
         elif int(pos) == 10:
             ani.play10()
         elif int(pos) == 15:
             ani.play15()
         elif int(pos) == 1:
             ani.play1()
         elif int(pos) == 20:
             ani.play20()
         elif int(pos) == 23:
Пример #25
0
from sense_hat import SenseHat
import time

sense = SenseHat()
sense.clear()
sense.load_image("sprites/creeper.png", True)
time.sleep(1)
sense.clear()
time.sleep(1)
pixel_list = sense.load_image("sprites/creeper.png", False)
print("Wait!!!")
time.sleep(1)
print("Display!!!")
sense.set_pixels(pixel_list)
time.sleep(1)
sense.clear()
Пример #26
0
#import sense hat libraries
from sense_hat import SenseHat

#make a sense hat
sense = SenseHat()

#load and show the space invader image found at https://raw.githubusercontent.com/astro-pi/python-sense-hat/master/examples/space_invader.png
sense.load_image("trees.png")

#set pixels manually
#sense.set_pixel(0,2, [0,0,255])
#sense.set_pixel(7,4,[255,0,0])
Пример #27
0
import os
import time
from sense_hat import SenseHat
from influxdb import InfluxDBClient

influx_client = InfluxDBClient('influxdb', 8086, database='balena-sense')
influx_client.create_database('balena-sense')

sense = SenseHat()

sense.clear()
sense.load_image("balena.png")
time.sleep(2)
sense.show_message("balena")

count = 0

while 1:
    measurements = [{
        'measurement': 'temperature',
        'fields': {
            'value': float(sense.temperature)
        }
    }]

    measurements.extend([{
        'measurement': 'humidity',
        'fields': {
            'value': float(sense.humidity)
        }
    }])
Пример #28
0
parser = argparse.ArgumentParser(
    description=
    'Loads an image file, converts it to RGB format and displays it on the LED matrix. The image must be 8 x 8 pixels in size.'
)
parser.add_argument('file_path',
                    type=str,
                    help='The file system path to the image file to load.')
parser.add_argument(
    '--redraw',
    type=str2bool,
    nargs='?',
    default=True,
    help=
    'Whether or not to redraw the loaded image file on the LED matrix. Defaults to True'
)

args = parser.parse_args()

try:
    from sense_hat import SenseHat

    sense = SenseHat()

    result = sense.load_image(args.file_path, args.redraw)

    # A list containing 64 smaller lists of [R, G, B] pixels (red, green, blue) representing the loaded image after RGB conversion.
    finish({"result": result})
except Exception, e:
    finish(e, 1)
Пример #29
0
			hue = hue - 1.0
	if currentMode == 1:
		if lastRun is not currentMode:
			sense.set_rotation(0)
			lastRun = currentMode
		temp = sense.temp
		temp = temp*1.8 + 32
		humidity = sense.get_humidity()
		humidity_value = 64 * humidity / 100
		humidity_value = round(humidity_value,1)
		temp = round(temp, 1)
		sense.show_message("Temp: " + str(temp) + " Humidity: " + str(humidity_value) + "%", scroll_speed=.05)
		currentMode = 0
	if currentMode == 2:
		if lastRun is not currentMode:
			sense.load_image("/home/pi/maker-faire-sense-hat-demo/logo.png")
			lastRun = currentMode
		x, y, z = sense.get_accelerometer_raw().values()
		x = round(x, 0)
		y = round(y, 0)
		if x == -1:
			sense.set_rotation(180)
		elif y == 1:
			sense.set_rotation(270)
		elif y == -1:
			sense.set_rotation(90)
		else:
			sense.set_rotation(0)

	if currentMode == 3:
		if lastRun is not currentMode:
# import sense_hat module
from sense_hat import SenseHat
import time
# Create an instance (object) of the SenseHat() class called 'sense'
sense = SenseHat()

# Fix display orientation if neccessary
sense.set_rotation(180)

# Load image to sense hat LED matrix (image must be 8 pixels wide by 8 pixels tall)
# Use the load_image() method and supply the file path to the image as an argument

# Create an infinite loop so that the user can change the image repeatedly.
# Press Ctrl+C to quit the application
while (True):
    # Get the image name and/or path from user (example: santa.png)
    image_path = "images/" + input("Enter image name/path: ")
    # Load the desired image into the sense hat LED matrix
    sense.load_image(image_path)
Пример #31
0
from sense_hat import SenseHat
sense = SenseHat()
sense.load_image("dao.jpg")
Пример #32
0
music_interface = [
X, X, X, X, X, X, X, X, #ALPHA
X, X, X, X, X, X, X, X,
X, X, X, X, X, X, X, X,
X, X, X, X, X, X, X, X,
X, X, X, X, X, X, X, X,

X, X, X, X, X, X, X, X, #MOOD AND VOLUME
X, X, X, X, X, X, X, M,

X, X, X, X, X, X, X,X] #PLAYLISTS

sense.set_pixels(music_interface)
time.sleep(10)
pygame.mixer.music.stop()

sense.load_image("/home/pi/Astro_MP3/Images8x8/relax.png")

pygame.mixer.music.load("/home/pi/Astro_MP3/MP3_files/Instructions/Voice010.mp3")                
pygame.mixer.music.play()
time.sleep(9)
pygame.mixer.music.load("/home/pi/Astro_MP3/MP3_files/Instructions/Voice011.mp3")                
pygame.mixer.music.play()
time.sleep(3)





Пример #33
0
# import sense_hat module
from sense_hat import SenseHat

# Create an instance (object) of the SenseHat() class called 'sense'
sense = SenseHat()

# Fix display orientation if neccessary
sense.set_rotation(180)

# Load image to sense hat LED matrix (image must be 8 pixels wide by 8 pixels tall)
# Use the load_image() method and supply the file path to the image as an argument
sense.load_image("images/golden_cross.png")
Пример #34
0
from sense_hat import SenseHat
sense = SenseHat()

temp = sense.get_temperature()

press = sense.get_pressure()

#sense.show_message(str(temp))
#sense.show_message(str(press))
#print (temp)
print(sense.pressure)
print(sense.temperature)
print(sense.humidity)

if sense.pressure >= 1023:
    sense.load_image("soleil.png")
elif sense.pressure >= 1013:
    sense.load_image("variable.png")
elif sense.pressure >= 1000:
    sense.load_image("nuage.png")
else:
    sense.load_image("pluie.png")

sense.set_pixel(0, 7, 0, 255, 0)

sense.set_pixel(0, 7, 0, 255, 00)
nbpix = sense.humidity / 100 * 6 + 1
print(nbpix)
nbpixint = math.floor(nbpix)
print(nbpixint)
sense.set_pixel(nbpixint, 7, 0, 255, 0)
Пример #35
0
def run_romaji_qcm():
    # Initialisation de variables
    sense = SenseHat()
    has_picked_an_answer = False
    chosen_answers = []
    color_of_answers = {
        "left": [0, 0, 255],
        "up": [255, 0, 0],
        "right": [0, 255, 0],
        "down": [255, 255, 0]
    }
    romaji_answers = [{
        "left": "ga",
        "up": "su",
        "right": "ne",
        "down": "se"
    }, {
        "left": "ja",
        "up": "mya",
        "right": "fu",
        "down": "no"
    }, {
        "left": "nama",
        "up": "sa",
        "right": "zu",
        "down": "ro"
    }, {
        "left": "mo",
        "up": "oi",
        "right": "wa",
        "down": "e"
    }, {
        "left": "ra",
        "up": "a",
        "right": "ri",
        "down": "hi"
    }]
    correct_answers = ["su", "no", "nama", "mo", "ri"]

    def japanese_characters():
        """
        Cree des images 8x8 noires et blanches
        de caracteres japonais pour le QCM.
        :return: (list) Une liste des caracteres japonais
        qui sont chacun representes par une matrice 8x8 de tuples RGB
        """
        W = (255, 255, 255)  # white
        O = (0, 0, 0)  # nothing/black

        # Les noms de variable sont les romaji du caract?re japonais

        # ?
        su = [
            O,
            O,
            O,
            O,
            W,
            O,
            O,
            O,
            O,
            O,
            W,
            W,
            W,
            W,
            W,
            O,
            O,
            W,
            O,
            O,
            W,
            O,
            O,
            O,
            O,
            O,
            O,
            W,
            W,
            O,
            O,
            O,
            O,
            O,
            W,
            O,
            W,
            O,
            O,
            O,
            O,
            O,
            O,
            W,
            W,
            O,
            O,
            O,
            O,
            O,
            O,
            O,
            W,
            O,
            O,
            O,
            O,
            O,
            W,
            W,
            O,
            O,
            O,
            O,
        ]
        # ?
        no = [
            O,
            O,
            O,
            O,
            O,
            O,
            O,
            O,
            O,
            O,
            W,
            W,
            W,
            W,
            O,
            O,
            O,
            W,
            O,
            W,
            O,
            O,
            W,
            O,
            O,
            W,
            O,
            W,
            O,
            O,
            W,
            O,
            O,
            W,
            O,
            W,
            O,
            O,
            W,
            O,
            O,
            W,
            O,
            W,
            O,
            O,
            W,
            O,
            O,
            W,
            W,
            O,
            O,
            O,
            W,
            O,
            O,
            O,
            O,
            O,
            W,
            W,
            O,
            O,
        ]
        # ?
        nama = [
            O,
            W,
            O,
            W,
            O,
            O,
            O,
            O,
            O,
            W,
            W,
            W,
            W,
            W,
            W,
            O,
            O,
            W,
            O,
            W,
            O,
            O,
            O,
            O,
            O,
            O,
            O,
            W,
            O,
            O,
            O,
            O,
            O,
            W,
            W,
            W,
            W,
            W,
            W,
            O,
            O,
            O,
            O,
            W,
            O,
            O,
            O,
            O,
            O,
            O,
            O,
            W,
            O,
            O,
            O,
            O,
            W,
            W,
            W,
            W,
            W,
            W,
            W,
            W,
        ]
        # ?
        mo = [
            O, O, W, O, O, O, O, O, O, O, W, O, O, O, O, O, O, W, W, W, W, O,
            O, O, O, O, W, O, O, O, O, O, O, W, W, W, W, O, W, O, O, O, W, O,
            O, O, W, O, O, O, W, O, O, O, W, O, O, O, O, W, W, W, O, O
        ]
        # ?
        ri = [
            O, O, O, O, O, O, O, O, O, O, O, O, O, W, O, O, O, O, W, O, O, W,
            O, O, O, O, W, O, O, W, O, O, O, O, O, O, O, W, O, O, O, O, O, O,
            O, W, O, O, O, O, O, W, W, O, O, O, O, O, O, O, O, O, O, O
        ]
        return [su, no, nama, mo, ri]

    for i in range(len(japanese_characters())):
        # Affichage du caractere japonais sur l'ecran pdt 2s.
        sense.set_pixels(japanese_characters()[i])
        time.sleep(2)
        has_picked_an_answer = False
        while not has_picked_an_answer:
            # Affichage du menu central invitant l'utilisateur a
            # naviguer a l'aide du joystick dans une des 4 directions.
            sense.load_image("ressources/images/central_menu.png")
            joystick_direction = userinput.get_joystick_direction()
            if joystick_direction in romaji_answers[i].keys():
                # Affichage de la proposition de reponse.
                sense.show_message(romaji_answers[i][joystick_direction], 0.05,
                                   color_of_answers[joystick_direction])
                # Selection de cette proposition de reponse.
                if userinput.get_joystick_direction() == "middle":
                    # Ajout de la reponse choisie dans la liste `chosen_answers`.
                    chosen_answers.append(
                        romaji_answers[i][joystick_direction])
                    # Feedback visuel comme quoi le choix a bien ete enregistre.
                    sense.load_image("ressources/images/pencil.png")
                    # Ce time.sleep() sert a garder le feedback visuel a l'ecran
                    # pendant plus d'une fraction de seconde.
                    time.sleep(2)
                    # 'Cassage' de la boucle while.
                    has_picked_an_answer = True

    # Affichage du score final
    # en comptant le nb de bonnes reponses
    sense.show_message(
        "Score: " +
        str(len(set(chosen_answers).intersection(correct_answers))) + "/" +
        str(len(japanese_characters())), 0.05)
Пример #36
0
from sense_hat import SenseHat
sense = SenseHat()
sense.load_image("picasso michel.png")
Пример #37
0
from sense_hat import SenseHat
import time
import datetime

sense = SenseHat()

sense.set_rotation(180)

inky = []
for nbr in range(1, 15):
    inky.append(
        sense.load_image("sprites/inky" + str(nbr) + ".png", redraw=False))


def Move(sprites, direction):
    if direction:
        animation = sprites
    else:
        animation = reversed(sprites)
    for sprite in animation:
        sense.set_pixels(sprite)
        time.sleep(0.1)  # delays for 100 miliseconds


Move(inky, 1)
sense.clear()  # no arguments defaults to off
time.sleep(1)
Move(inky, 0)
sense.clear()  # no arguments defaults to off
time.sleep(1)
Пример #38
0
def main():

	sense = SenseHat()
	sense.low_light = True
	last_update_time = 0
	sense.rotation = 90

	SunPictos = [1,2,3,4,5,6,13,14,15]
	SunCloudPictos = [7,8,9,10,11,12,31,32]
	CloudPictos = [16,17,18,19,20,21,22,23]
	RainPictos = [23,25,33,35]
	SnowPictos = [24,26,29,34]
	StormPictos = [27,28,30]

	while True:  

		# Fetch weather data every update period
		if time.time()-last_update_time > update_period*60:
			Weather = get_weather(url)
			last_update_time = time.time()
			Baro = get_press(AltitudeAboveSeaLevel)
			Humidity = sense.get_humidity()
			print('Current, Max, Min temp, Picto:',Weather.CurrentTemp,Weather.ForecastMaxTemp,Weather.ForecastMinTemp,Weather.Picto)
			print('Weather info updated at:', strftime("%a, %d %b %Y %H:%M:%S", localtime()))
			print('Local Pressure',Baro)


 
		# display Time & Weather info on SenseHat

		if ShowTime:
			sense.show_message('{} {}'.format('Heure:',strftime("%H:%M",localtime())),text_colour=(180,180,180))

		if ShowTemperature:
			sense.show_message('{} {}{}'.format('T:', str(Weather.CurrentTemp),' '), text_colour=Weather.CurrentColor,scroll_speed=0.15)
			sense.show_message('{} {}'.format('Max:', str(Weather.ForecastMaxTemp)), text_colour=Weather.MaxColor,scroll_speed=0.15)
			sense.show_message('{} {}'.format('Min:', str(Weather.ForecastMinTemp)), text_colour=Weather.MinColor,scroll_speed=0.15)

		if ShowWeatherPicto:

			if Weather.Picto in SunPictos:
				for i in range (0,10):
					sense.load_image("/home/pi/SenseHat/WeatherMonitor/Images/soleil.png")
					time.sleep(0.3)
					sense.load_image("/home/pi/SenseHat/WeatherMonitor/Images/soleil2.png")
					time.sleep(0.3)
			elif Weather.Picto in SunCloudPictos:
				sense.load_image("/home/pi/SenseHat/WeatherMonitor/Images/soleil&nuage.png")
				time.sleep(5)
			elif Weather.Picto in CloudPictos:
				sense.load_image("/home/pi/SenseHat/WeatherMonitor/Images/nuage.png")
				time.sleep(5)
			elif Weather.Picto in RainPictos:
				sense.load_image("/home/pi/SenseHat/WeatherMonitor/Images/nuage&pluie.png")
				time.sleep(5)
			elif Weather.Picto in SnowPictos:
				sense.load_image("/home/pi/SenseHat/WeatherMonitor/Images/nuage&neige.png")
				time.sleep(5)
			elif Weather.Picto in StormPictos:
				sense.load_image("/home/pi/SenseHat/WeatherMonitor/Images/nuages&eclairs.png")
				time.sleep(5)												
		
		if ShowPressure:
			sense.show_message('{} {}'.format(format(Baro, '.1f'),'hPa'), text_colour=Weather.CurrentColor,scroll_speed=0.15)
			#print(format(Baro, '.1f'),'hPa')

		if ShowHumidity:
			sense.show_message('{} {} {}'.format(format(Humidity, '.1f'),'%','Hum.'), text_colour=Weather.CurrentColor,scroll_speed=0.15)
			#print(format(Humidity, '.1f'),'%','Hum.')


		time.sleep(1)
Пример #39
0
def printConfig(config):
  sense = SenseHat()
  sense.load_image("images/veryHot.png")
          
from sense_hat import SenseHat
import time

hat = SenseHat()

red = (255, 0, 0)

hat.load_image('small_image.png')
time.sleep(1)
hat.set_rotation(90)
time.sleep(1)
hat.set_rotation(180)
time.sleep(1)
hat.set_rotation(270)
time.sleep(1)

hat.clear()
hat.set_rotation(0)
for xy in range(0, 8):
    hat.set_pixel(xy, xy, red)
    hat.set_pixel(xy, 7-xy, red)
Пример #41
0
from sense_hat import SenseHat

s = SenseHat()
s.load_image("Noel.png")
        return json.dumps({'Stmt':cmd,'Workspace':"",'Opts':{}})

def getData(server,cmdStr):
        r = requests.post(server,data=cmd2JSON(cmdStr) , stream=True)
        for content in json_stream(r.raw):
                return (json.dumps(content))

def json_stream(fp):
        for line in fp:
                yield json.loads(line)
                
if __name__ == "__main__":
        sense = SenseHat()
        sense.set_rotation(180)
        sense.low_light = True
        sense.load_image("logo8.png")
        sleep(1)

        #sense.clear()
        #humidity = round(sense.get_humidity(),2)
        #temp = round(sense.get_temperature(),2)
        #pressure = round(sense.get_pressure(),2)

        sense.show_message("Data collection starting.",scroll_speed=0.05)
        sense.load_image("logo8.png")
        sense.set_imu_config(True, True, True)
        count = 0
        while True:
                sleep(1)
                count = count + 1
                if count%60 == 0:
Пример #43
0
def newImage():
    global stream
    stream.seek(0)
    camera.capture(stream, format='jpeg')
    stream.seek(0)
    return list(Image.open(stream).getdata())


with open("/home/pi/Documents/SurveillanceRunning.txt", 'w') as file:
    file.write(str(os.getpid()))
stream = io.BytesIO()
camera = picamera.PiCamera()
camera.vflip = camera.hflip = True
sense = SenseHat()
sense.load_image("/home/pi/Documents/interrogation.png")
redColor = [[255, 0, 0] for i in range(0, 64)]
r = [255, 0, 0]
b = [255, 255, 255]
exclamation = [
    r, r, r, b, b, r, r, r, r, r, r, b, b, r, r, r, r, r, r, b, b, r, r, r, r,
    r, r, b, b, r, r, r, r, r, r, b, b, r, r, r, r, r, r, r, r, r, r, r, r, r,
    r, b, b, r, r, r, r, r, r, b, b, r, r, r
]
newPhoto = newImage()
while True:
    oldPhoto = newPhoto
    newPhoto = newImage()
    differents = 0
    for i in range(0, len(oldPhoto), 500):
        if newPhoto[i][0] - 50 > oldPhoto[i][0] or newPhoto[i][
Пример #44
0
  forecast_key = os.environ['FORECAST_KEY']
except KeyError as e:
  print 'FORECAST_KEY not set'
  sys.exit(1)

latitude = os.getenv('FORECAST_LATITUDE', 53.4667)
longitude = os.getenv('FORECAST_LONGITUDE', -2.2333)

url = 'https://api.darksky.net/forecast/%s/%s,%s' % (forecast_key, latitude, longitude)

while True:
  response = requests.get(url)

  if(response.ok):
    jData = json.loads(response.content)

    current = jData['currently']['icon']

    max_counter = 60 * 5
    counter = 0
    while counter < max_counter:
        icon = icon_mapper.get_images(current)

        for icon_frame in icon:
            sense.load_image(icon_frame[0])
            counter = counter + 1
            sleep(icon_frame[1])

  else:
    sense.show_message('ERROR', text_colour=[255,0,0])
                a,a,a,a,a,a,a,a,
                a,a,a,a,a,a,a,a,
                a,a,a,a,a,a,a,a,
                a,a,a,a,a,a,a,a
              ]


devices = [InputDevice(fn) for fn in list_devices()]
for dev in devices:
    if dev.name == "Raspberry Pi Sense HAT Joystick":
        js = dev

while True:
    sense.set_rotation(r=180)
    if currently.icon == "partly-cloudy-day":
        sense.load_image("icn_cloudysun_color.png")
    elif currently.icon == "partly-cloudy-night":
        sense.load_image("icn_cloudynight_color.png")
    elif currently.icon == "clear-day":
        sense.load_image("icn_sun_color.png")
    elif currently.icon == "clear-night":
        sense.load_image("icn_moon_color.png")
    elif currently.icon == "fog":
        sense.load_image("icn_fog_color.png")
    elif currently.icon == "wind":
        sense.load_image("icn_wind_color.png")
    elif currently.icon == "rain":
        sense.load_image("icn_rain_color.png")
    elif currently.icon == "sleet":
        sense.load_image("icn_sleet_color.png")
    elif currently.icon == "snow":