示例#1
0
def main():
    sense = SenseHat()
    sense.low_light = True
    print( "<---- SinusGraph ---->\n" )
    pixelStatuses = [ [ 0, 0, 0 ] for i in range( 64 ) ]
    for i in range( 150 ):
        assert len( pixelStatuses ) == 64
        del pixelStatuses[ : 8 ]
        pixelStatuses.extend( [ [ 0, 0, 0 ] for i in range( 8 ) ] )
        pixelStatuses[ 60 + round( cos( i / 1.5 ) * 3 ) ] = [ 0, 255, 0 ]
        pixelStatuses[ 60 + round( sin( i / 2 ) * 3 ) ] = [ 255, 255, 255 ]
        sense.set_pixels( pixelStatuses )
        pixelStatuses = sense.get_pixels()
        print( pixelStatuses )
        sleep( 0.096 )
    sense.clear()
示例#2
0
文件: led.py 项目: MagorokuYohei/hoby
def main():
	sense = SenseHat()
	"""
	sense.show_message("Hello World!!");
	sense.set_rotation(180)
	sense.show_message("Hello World!!");
	"""
	sense.flip_v()
	list = sense.get_pixels()
	#print list

	sense.set_pixel(0,0,255,0,0)
	sense.clear()
 	for i in range(0, 5):
		sense.show_letter(str(i))
		time.sleep(1)	
	sense.clear()	
示例#3
0
def display_cabin_alt():
    sampling_interval = astro_display.orbitPosIncrementSeconds

    global displaying
    displaying = True
    sense = SenseHat()
    current_pixels = sense.get_pixels()
    sense.clear()
    p = sense.get_pressure()
    a = (1 - (p / 1013.25)**0.190284) * 145366.45
    alt = int(round(a))

    if alt > 9999:
        c = [255, 0, 0]
    else:
        c = [0, 255, 0]

    sense.show_message("Cabin Alt: " + str(alt) + "ft", text_colour=c)
    displaying = False
    sense.set_pixels(current_pixels)
    threading.Timer(sampling_interval, display_cabin_alt).start()
# https://pythonhosted.org/sense-hat/api/#get_pixels

import argparse

from _return import finish

parser = argparse.ArgumentParser(description='Get all 8x8 pixels')

args = parser.parse_args()

try:
    from sense_hat import SenseHat

    sense = SenseHat()

    result = sense.get_pixels()

    finish({"result": result})
except Exception, e:
    finish(e, 1)
示例#5
0
                sense.flip_h(True)

            if key == "flipV":
                if showDebug:
                    print("[ledMatrixBridge] flip vertical")
                sense.flip_v(True)

            if key == "setPixels":
                if showDebug:
                    print("[ledMatrixBridge] set pixels from array")
                sense.set_pixels(payload["value"])

            if key == "getPixels":
                if showDebug:
                    print("[ledMatrixBridge] flip vertical")
                print(sense.get_pixels())

            if key == "setPixel":
                if showDebug:
                    print("[ledMatrixBridge] set single pixel")
                sense.set_pixel(payload["x"], payload["y"], payload["r"],
                                payload["g"], payload["b"])

            if key == "getPixel":
                if showDebug:
                    print("[ledMatrixBridge] get single pixel")
                print(sense.get_pixel(payload["x"], payload["y"]))

            if key == "loadImage":
                if showDebug:
                    print("[ledMatrixBridge] load image", payload["value"])
    display = matrix.tolist()
    # Flatten the list one more layer
    display = [item for sublist in display for item in sublist]
    sense.set_pixels(display)


sense = SenseHat()

height = 8
width = 8
depth = 3

#matrix = np.zeros([height,width,depth],dtype=np.uint8)

# read the current pixels and transform it to a 3d matrix
matrix = np.array(sense.get_pixels(), dtype=np.uint8).reshape(8, 8, 3)
# change color
matrix[:, :] = [255, 100, 0]

#print(matrix)
#print((matrix*0.5).astype(int))
displayMatrix(matrix)
# color the 2nd row white
matrix[1:2, :] = [128, 255, 128]
# color the 2 col white
matrix[:, 1:2] = [128, 128, 255]

fade_in_out(matrix, 2)

background = [255, 34, 34]
matrix[:, :] = background
示例#7
0
def darken(color):
    step = 10
    if color[0] > step:
        color[0] -= step

    if color[1] > step:
        color[1] -= step

    if color[2] > step:
        color[2] -= step

    return color


# Second we make a loop that at each iteration darken the "image"
for i in range(0, 50):
    pixel_list = myHAT.get_pixels()

    # We create a new list of colors to store the new values
    new_list = []

    # We need to get the current status of each LED
    for pixel in pixel_list:
        print(type(pixel))
        # For each pixel we darken the color and store it in new_list
        pixel = darken(pixel)
        new_list.append(pixel)

    # Finally we draw the new image
    myHAT.set_pixels(new_list)
    sleep(0.1)
示例#8
0
ladders = game.getLadders()
players = game.getPlayers()


##Cursor
cursorPositionX = 0
cursorPositionY = 7
cursorColour = [255,255,255]

##Main Loop

while True:
    for player in players:

        turnPlayed = False
        image = sense.get_pixels()

        while not turnPlayed:
            for event in sense.stick.get_events():
                ##Add cursor
                sense.set_pixels(image)
                sense.set_pixel(cursorPositionX, cursorPositionY, cursorColour)

                if event.action == "pressed":
                    if event.direction == "up":
                        cursorPositionY -= 1
                        if cursorPositionY < 0:
                            cursorPositionY = 7
                    elif event.direction == "down":
                        cursorPositionY += 1
                        if cursorPositionY > 7:
示例#9
0
from sense_hat import SenseHat

sense = SenseHat()
pixel_list = sense.get_pixels()
    async def handle(self, context: RequestContext, responder: BaseResponder):
        """
        Message handler logic for basic messages.

        Args:
            context: request context
            responder: responder callback
        """
        self._logger.debug(f"ReadSensorHandler called with context {context}")
        assert isinstance(context.message, ReadSensor)

        self._logger.info("Received read sensor: %s", context.message.sensors)

        sensors = context.message.sensors

        meta = {"sensors": sensors}

        conn_mgr = ConnectionManager(context)
        await conn_mgr.log_activity(
            context.connection_record,
            "read_sensor",
            context.connection_record.DIRECTION_RECEIVED,
            meta,
        )

        await responder.send_webhook(
            "read_sensor",
            {
                "message_id": context.message._id,
                "sensors": sensors,
                "state": "received"
            },
        )

        sense = SenseHat()
        temperature = None
        humidity = None
        pressure = None
        orientation = None
        accelerometer = None
        compass = None
        gyroscope = None
        stick_events = None
        pixels = None

        if "temperature" in sensors:
            temperature = sense.get_temperature()
        if "humidity" in sensors:
            humidity = sense.get_humidity()
        if "pressure" in sensors:
            pressure = sense.get_pressure()
        if "orientation" in sensors:
            orientation = sense.get_orientation_degrees()
        if "accelerometer" in sensors:
            accelerometer = sense.get_accelerometer_raw()
        if "compass" in sensors:
            compass = sense.get_compass_raw()
        if "gyroscope" in sensors:
            gyroscope = sense.get_gyroscope_raw()
        if "stick_events" in sensors:
            stick_events = []
            stick_event_objects = sense.stick.get_events()
            for event in stick_event_objects:
                event_dict = {}
                event_dict['timestamp'] = event.timestamp
                event_dict['direction'] = event.direction
                event_dict['action'] = event.action
                stick_events.append(event_dict)
        if "pixels" in sensors:
            pixels = sense.get_pixels()

        reply_msg = SensorValue(temperature=temperature,
                                humidity=humidity,
                                pressure=pressure,
                                orientation=orientation,
                                accelerometer=accelerometer,
                                compass=compass,
                                gyroscope=gyroscope,
                                stick_events=stick_events,
                                pixels=pixels)

        await responder.send_reply(reply_msg)
        await conn_mgr.log_activity(
            context.connection_record,
            "sensor_value",
            context.connection_record.DIRECTION_SENT,
            {"content": "reply"},
        )
示例#11
0
sense = SenseHat()  # This will be used to control the the SenseHat.
initialise(
    sense
)  # Initialises the senselib library, that provides us with some useful functions
sense.clear()  # Clears all pixels on the screen.

#### 1.3 Set up the variables

posx = 4
posy = 4
posvx = 0.5
posvy = 0.5
rot = 0.1

fade_factor = 0.9
screen = sense.get_pixels()

#### 2. Main game code

while True:

    posvx = posvx * math.cos(rot) - posvy * math.sin(rot)
    posvy = posvx * math.sin(rot) + posvy * math.cos(rot)

    posx += posvx
    posy += posvy

    ix = int(posx % 8)
    iy = int(posy % 8)

    #sense.set_pixel(0, 1, 255, 255, 255 )
示例#12
0
        set_color(x, y)

    if sense.get_pixel(previous_x, previous_y) == [
            248, 252, 248
    ]:  #verifie si la position precedente est blanche,si oui, efface
        sense.set_pixel(previous_x, previous_y, 0, 0, 0)

    if event.direction == "down" and event.action == "held":  # clean l'ecran
        sense.clear()

    if event.direction == "up" and event.action == "held":  #quand validation
        pixel = sense.get_pixel(x, y)  #Prend la couleur du pixel
        if pixel == [248, 252, 248]:  #Si le pixel est blanc, efface le curseur
            sense.set_pixel(x, y, nothing)

        if sense.get_pixels(
        ) == dessin and event.action == "held" and event.direction == "up":  #Tant que corresond au dessin secret et que le joystick est maintenu vers le haut
            tempb = sense.get_temperature()  #Prend une deuxieme temperature
            tempc = sense.get_temperature_from_pressure()
            if tempb > temp + 0.3 or tempc > temp + 0.3:  #si la t augmente, affiche du vert et lance le .py correspondant a la situation
                print("b")
                pro = False  #Arrete la boucle permettant de dessiner
                sense.clear(0, 255, 0)
                time.sleep(2)
                sense.clear()
                #Verifie s il y a un message enregistre, si oui lance le .py pour rentrer le mdp. S il n y en a pas lance message.py pour en rentrer un.
                f = open("message.txt", "r")  #ouvre le document message.txt
                message = f.read()  #string message = contenu du doc
                f.close()
                if message == "":
                    import encode_key.py  # Permet de rentrer la clef
                else:
示例#13
0
import time
import sys
import os
import base64
import StringIO
from PIL import Image  # pillow
from sense_hat import SenseHat

sense = SenseHat()
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]):
示例#14
0
import atexit
import subprocess
import os
from subprocess import Popen

from sense import rainbow
"""
Response to joystick presses and update the Sense Hat for a Raspberry Pi
"""

x = 0
y = 0
sense = SenseHat()
rainbow_pixels = rainbow.default_pixels()

total_pixels = len(sense.get_pixels())
dim_size = int(math.sqrt(total_pixels))
max_value = dim_size - 1

processes = []

last_press_time = 0


def on_exit():
    sense.clear()


def index(x, y):
    return y * dim_size + x
示例#15
0
class Paint(object):
    def motion(self, event):
        #tbd: sense LED 'cursor'?
        x, y = self.scale_sense_pixels(event.x, event.y)
        old_value = self.sense.get_pixel(x, y)
        print value

    def key(self, event):
        global current_paint_brush
        if event.char == ' ':
            current_paint_brush += 1
            if current_paint_brush == len(paint_brushes):
                current_paint_brush = 0
                return
        if event.char == 'i':
            pixels = self.sense.get_pixels()
            print pixels

    def scale_sense_pixels(self, canvas_x, canvas_y):
        x = canvas_x / self.x_step
        y = canvas_y / self.y_step
        if x < 0:
            x = 0
        if y < 0:
            y = 0
        if x >= self.sense_width:
            x = self.sense_width - 1
        if y >= self.sense_height:
            y = self.sense_height - 1
        return (x, y)

    # Clear the pixel
    def right_click(self, event):
        x, y = self.scale_sense_pixels(event.x, event.y)
        self.sense.set_pixel(x, y, eraser)
        w = event.widget.find_closest(event.x, event.y)
        self.canvas.itemconfigure(w, fill='black')  # sort of cheating here

    # 'Paint' the pixel
    def left_click(self, event):
        global current_paint_brush
        global paint_brushes
        x, y = self.scale_sense_pixels(event.x, event.y)
        self.sense.set_pixel(x, y, paint_brushes[current_paint_brush])
        w = event.widget.find_closest(event.x, event.y)
        self.canvas.itemconfigure(w,
                                  fill="#%02X%02X%02X" %
                                  (paint_brushes[current_paint_brush][0],
                                   paint_brushes[current_paint_brush][1],
                                   paint_brushes[current_paint_brush][2]))

    def __init__(self, width=200, height=200):
        self.sense = SenseHat()
        self.sense.set_rotation(
            180
        )  # this actually messes up our 'get_pixels()' , since it doesn't seem to take into account the rot !
        self.sense.clear(
            (0, 0, 0)
        )  # which is why we have to clear them each time  (I guess we should store the rotation value and compensate for each startup?)
        self.width = width
        self.height = height
        self.sense_width = 8
        self.sense_height = 8

        self.x_step = self.width / self.sense_width
        self.y_step = self.height / self.sense_height

        self.root = Tk()
        self.root.title('LED Painter')
        self.canvas = Canvas(self.root, width=self.width, height=self.height)
        self.mypixels = self.sense.get_pixels()
        pixel_counter = 0

        for x in range(0, self.width, self.x_step):
            for y in range(0, self.height, self.y_step):
                fill_colour = 'black'  # temporary hack, should really take the 'clear' off earlier and map FROM senseboard to Tkinter initially
                p = self.canvas.create_rectangle(x,
                                                 y,
                                                 x + self.x_step,
                                                 y + self.y_step,
                                                 outline='white',
                                                 fill=fill_colour)
                pixel_counter += 1
                self.canvas.tag_bind(p, '<ButtonPress-1>', self.left_click)
                self.canvas.tag_bind(p, '<B1-Motion>', self.left_click)
                self.canvas.tag_bind(p, '<ButtonPress-3>', self.right_click)
                self.canvas.tag_bind(p, '<B3-Motion>', self.right_click)

                self.root.bind("<Key>", self.key)

    #			self.root.bind("<Motion>", self.motion)
        self.canvas.pack()
        self.root.mainloop()
示例#16
0
import time
import sys
import os
import base64
import StringIO
from PIL import Image  # pillow
from sense_hat import SenseHat

sense = SenseHat()
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]):
示例#17
0
class LedResource(Resource):
    sensehat = None  # senseHat object
    payload = ""

    def __init__(self, name="LedResource", coap_server=None):
        '''
        Constructor
        '''
        super(LedResource, self).__init__(name, coap_server, visible=True, observable=True, allow_children=True)
        # instantiate senseHat
        self.sensehat = SenseHat()
    
    def render_GET_advanced(self, request, response):
        '''
        GET request handler
        return led status if possible (2.05 CONTENT)
        if error, return 5.03
        '''
        try:
            response.payload = self.LedStatus()
            response.code = defines.Codes.CONTENT[0]
            return self, response
        except (RuntimeError, OSError):
            response.code = defines.Codes.SERVICE_UNAVAILABLE[0]
            return self, response
            
    def render_POST_advanced(self, request, response):
        '''
        POST request handler
        try to trigger the LED actuator according to request
        return OK in payload and 2.01 CREATED
        if error, return 5.03
        '''
        # set default color
        color = (110, 90, 255)
        if request.payload == "on":
            try:
                self.sensehat.clear(color)
                response.payload = "OK"
                response.code = defines.Codes.CREATED[0]
                return self, response
            except (RuntimeError, OSError):
                response.code = defines.Codes.SERVICE_UNAVAILABLE[0]
                return self, response
        elif request.payload == "off":
            try:
                self.sensehat.clear()
                response.payload = "OK"
                response.code = defines.Codes.CREATED[0]
                return self, response
            except (RuntimeError, OSError):
                response.code = defines.Codes.SERVICE_UNAVAILABLE[0]
                return self, response
        elif request.payload == "dim":
            try:
                self.sensehat.low_light = True
                response.payload = "OK"
                response.code = defines.Codes.CREATED[0]
                return self, response
            except (RuntimeError, OSError):
                response.code = defines.Codes.SERVICE_UNAVAILABLE[0]
                return self, response
        elif request.payload == "brighten":
            try:
                self.sensehat.low_light = False
                response.payload = "OK"
                response.code = defines.Codes.CREATED[0]
                return self, response
            except (RuntimeError, OSError):
                response.code = defines.Codes.SERVICE_UNAVAILABLE[0]
                return self, response

    def LedStatus(self):
        '''
        Helper function to check the LED status
        '''
        # black/off RGB for led pixel
        black = [0, 0, 0]
        # get list containing 64 smaller lists of [R, G, B] pixels
        pixel_list = self.sensehat.get_pixels()
        # set default status to off
        status = "off"
        # check if it is on (no all pixel is [0,0,0])
        for p in pixel_list:
            if p != black:
                status = "on"
                break
        # check if it is in low_light mode
        if status == "on":
            if self.sensehat.low_light == True:
                status = "dim"
        return status
示例#18
0
def fade( pixel ):
	new_pixel=[]
	for comp in pixel:
		if comp>0:
			new_pixel.append( comp-1)
		else:
			new_pixel.append( 0 )
	return new_pixel
	

while True:
	rx=random.randint(0,3)
	ry=random.randint(0,3)
	if random.randint(0,100) < 25:
		col=[	random.randint(0,255),
			random.randint(0,255),
			random.randint(0,255)
		]
		if sense.get_pixel(rx,ry)==[0,0,0]:
			sense.set_pixel(rx, ry, col)	
			sense.set_pixel(7-rx, ry, col)
			sense.set_pixel(7-rx, 7-ry, col)
			sense.set_pixel(rx, 7-ry, col)
	pixels=sense.get_pixels()	
	new_pixels=[]
	for p in pixels:
		new_pixels.append( fade( p ) )
	sense.set_pixels( new_pixels )
	#sleep(0.1)
示例#19
0
文件: c.py 项目: greerben0/pi_scripts
        green = int(rgb[1])
        blue = int(rgb[2])

#Initialize the pixels with random colors
sense.set_pixels([[randint(0, 255),
                   randint(0, 255),
                   randint(0, 255)] for x in xrange(0, 64)])

print "rgb={},{},{}, isMatch={}".format(red, green, blue,
                                        inspect.getsourcelines(isMatch))

iteration = 0
try:
    matches = 0
    while True:
        grid = sense.get_pixels()
        for i in xrange(0, len(grid)):
            if not isMatch(grid[i]):
                grid[i] = [randint(0, 255), randint(0, 255), randint(0, 255)]
            else:
                print "Pixel {} matches [{},{},{}]".format(i, red, green, blue)
                matches += 1
        if matches == 64:
            print "Took {} iterations to all match goal".format(iteration)
            try:
                input("Press Enter to exit")
            except NameError:
                pass
            finally:
                sys.exit()
        else:

##Player 1
playerPostionX = 0
playerPositionY = 7
playerColour = [100,255,100]

##Player 2

##Cursor
cursorPositionX = 0
cursorPositionY = 7
cursorColour = [255,255,255]


image = sense.get_pixels() # Save the sreen as it is for now
sense.set_pixel(cursorPositionX,cursorPositionY,cursorColour)
##Main Loop

while True:

    for event in sense.stick.get_events():
        if event.action == "pressed":
            if event.direction == "up":
                cursorPositionY -= 1
                if cursorPositionY < 0:
                    cursorPositionY = 7
            elif event.direction == "down":
                cursorPositionY += 1
                if cursorPositionY > 7:
                    cursorPositionY = 0
示例#21
0
class MatrixController():

    WHITE = [255, 255, 255]
    BLACK = [0, 0, 0]
    RED = [255, 0, 0]
    USER_EXIT = 'exit'

    def __init__(self):
        self.trying = False
        self.sense = SenseHat()
        self.handler = {
            "up": self.pushed_up,
            "down": self.pushed_down,
            "right": self.pushed_right,
            "left": self.pushed_left,
            "middle": self.pushed
        }

    def get_username(self):
        os.system("clear")
        self.sense.clear()
        print "Enter your Username. Type 'exit' to close the app \n"
        return raw_input("Username: "******"\nEnter your authentication pattern in the Raspberry Pi"
        print "\n	- Move the joystick to move around"
        print "\n	- Press the joystick to select/deselect"
        print "\n	- Select any spot in the green lines to submit"
        self.trying = True
        self.sense.load_image("res/start_pattern.png")
        self.x, self.y = [3, 3]
        self.next_x, self.next_y = [3, 3]
        self.hold_color = MatrixController.BLACK
        while self.trying:
            event = self.sense.stick.wait_for_event(emptybuffer=True)
            self.handler[event.direction](event)
            self.refresh()
            if self.trying == False:
                pattern_entered = self.sense.get_pixels()
                del pattern_entered[56:]  # Delete last row
                del pattern_entered[7::8]  # Delete last coloumn
                for i in range(len(pattern_entered)):
                    pattern_entered[
                        i] = pattern_entered[i] != MatrixController.BLACK
        self.sense.clear()
        return pattern_entered

    def exit(self):
        print "\nBye!!"
        self.sense.show_message("Bye!!")

    def display_error(self, error):
        self.sense.load_image("res/error.png")
        print "\nAn error has occured: \n"
        print error
        print "\nPress Enter to continue"
        raw_input()
        self.sense.clear()

    def display_success(self, user):
        self.sense.load_image("res/success.png")
        print "\n\n Welcome " + user['name'] + "!"
        print "\n We will send you an email to <" + user[
            'mail'] + "> every " + str(
                user['wait']) + " seconds with the weather data."
        print "\n Press Ctrl + C to logout"
        time.sleep(1)
        self.sense.clear()

    def animation(self):
        "One second animation"
        self.sense.load_image("res/cloud1.png")
        time.sleep(0.25)
        self.sense.load_image("res/cloud2.png")
        time.sleep(0.25)
        self.sense.load_image("res/cloud3.png")
        time.sleep(0.25)
        self.sense.load_image("res/cloud4.png")
        time.sleep(0.25)

    def clamp(self, value, min_value=0, max_value=7):
        "Check it doesn't go out of the boundaries of the matrix"
        return min(max_value, max(min_value, value))

    def pushed_up(self, event):
        if event.action != ACTION_RELEASED:
            self.next_y = self.clamp(self.y - 1)

    def pushed_down(self, event):
        if event.action != ACTION_RELEASED:
            self.next_y = self.clamp(self.y + 1)

    def pushed_left(self, event):
        if event.action != ACTION_RELEASED:
            self.next_x = self.clamp(self.x - 1)

    def pushed_right(self, event):
        if event.action != ACTION_RELEASED:
            self.next_x = self.clamp(self.x + 1)

    def pushed(self, event):
        if event.action != ACTION_RELEASED:
            if self.x == 7 or self.y == 7:
                self.trying = False
            else:
                self.toggle_color()

    def toggle_color(self):
        "If the joystick is pressed, change the color from Black to Red or viceversa"
        if self.hold_color == MatrixController.BLACK:
            self.hold_color = MatrixController.RED
        else:
            self.hold_color = MatrixController.BLACK

    def refresh(self):
        #Color the current pixel with the proper color before moving
        self.sense.set_pixel(self.x, self.y, self.hold_color)
        #Saves the color of the next pixel
        self.hold_color = self.sense.get_pixel(self.next_x, self.next_y)
        #Moves to the next pixel, coloring it white
        self.sense.set_pixel(self.next_x, self.next_y, MatrixController.WHITE)
        #Updates the current position
        self.x, self.y = self.next_x, self.next_y