Ejemplo n.º 1
0
def senseStickService():
    print 'Starting SenseHat Stick Service'

    STICK_MIDDLE = 28
    stick = SenseStick()

    while True:
        if stick.wait(timeout=0.10) == True:

            #   Get the input from the joystick
            stick_input = stick.read()
            direction = stick_input[1]
            state = stick_input[2]  #   1 = pressed, 2 = held, 0 = released

            if (state == 0):    #   Only register if the joystick has been released
                if (direction == STICK_MIDDLE):
                    #   cycle the currentDisplayMode through the allDisplayModes array
                    currentDisplayMode.value = allDisplayModes[(allDisplayModes.index(currentDisplayMode.value) + 1) % len(allDisplayModes)]
Ejemplo n.º 2
0
#camera.rotation = 180 #use this if the camera rotation is not correct
camera.resolution = (3280, 2464)  #this can be changed

#starting the Sense Stick
joystick = SenseStick()

#opening the output files
filestamp = localtime()
delay = 1  #use this number to set the delay between camera captures in seconds
pic_number = 1  #this is the starting number for taking pictures
pic_dir = "/home/pi/Desktop/Pictures_" + repr(filestamp.tm_year) + '-' + repr(
    filestamp.tm_mon) + '-' + repr(filestamp.tm_mday) + '__' + repr(
        filestamp.tm_hour) + '-' + repr(filestamp.tm_min)
if not os.path.isdir(pic_dir):
    os.makedirs(pic_dir)
camera_check = True

## This is the main picture taking loop
while camera_check:
    camera.capture(pic_dir + '/image%s.jpg' % pic_number)
    pic_number += 1

    led_display.data_display('camera')

    joystick_press = joystick.wait(timeout=delay)
    if joystick_press:
        event = joystick.read()
        if event.state == joystick.STATE_PRESS:
            if event.key == joystick.KEY_ENTER:
                camera_check = False
Ejemplo n.º 3
0
    for pixel in component.pixels:
        sense.set_pixel(pixel[0], pixel[1], 0, 0, 0)


def mainLoop():
    print("Running")


# draw the wall
for brick in game.wall.bricks:
    render(brick)

# draw the ball
render(game.ball)

# draw the bat
render(game.bat)

running = True

try:
    while running:
        mainLoop()
        if stick.wait(timeout=0.01) == True:
            input = joystick.read()[1]
            if input == KEY_DOWN:
                print("Key Down")
except KeyboardInterrupt:
    sense.clear()
    running = False
Ejemplo n.º 4
0
class Rollerball(object):
    def __init__(self, platform=SENSE_HAT):

        # init correct display renderer
        if platform == SENSE_HAT:
            print 'Using SenseHAT display'
            self.renderer = renderer.get_sensehat_renderer()
            self.stick = SenseStick()
        else:
            print 'Using desktop display'
            self.renderer = renderer.get_pygame_renderer()

        self.platform = platform

        self.init_assets()

        self.maze = Maze('maze_01.png')
        self.maze_width = self.maze.width
        self.maze_height = self.maze.height
        self.board = Board()
        self.ball = Ball(3, 3)
        self.set_viewport(0, 15)

    def handle_keyboard_events(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                return True
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                return True
            elif event.type == KEYDOWN and (event.key == K_LEFT):
                self.move_left()
            elif event.type == KEYDOWN and (event.key == K_RIGHT):
                self.move_right()
            elif event.type == KEYDOWN and (event.key == K_UP):
                self.move_up()
            elif event.type == KEYDOWN and (event.key == K_DOWN):
                self.move_down()

    def handle_stick_events(self):
        event = self.stick.read()
        print event
        if event.key == SenseStick.KEY_UP and event.state == SenseStick.STATE_PRESS:
            print 'Move up'
            self.move_up()
        elif event.key == SenseStick.KEY_DOWN and event.state == SenseStick.STATE_PRESS:
            self.move_down()
        elif event.key == SenseStick.KEY_RIGHT and event.state == SenseStick.STATE_PRESS:
            self.move_right()
        elif event.key == SenseStick.KEY_LEFT and event.state == SenseStick.STATE_PRESS:
            self.move_left()

    def init_assets(self):
        # this is where we load all the game assets
        self.ball_image = load_image('ball.png')

    def move_down(self):
        if self.view_y < self.maze_height - renderer.ROWS:
            cell_1 = self.board.cells[self.ball.x][self.ball.y + 2]
            cell_2 = self.board.cells[self.ball.x + 1][self.ball.y + 2]
            if cell_1.colour != renderer.BLACK and cell_2.colour != renderer.BLACK:
                self.view_y += 1

    def move_left(self):
        if self.view_x > 0:
            # check maze is clear to move right
            cell_1 = self.board.cells[self.ball.x - 1][self.ball.y]
            cell_2 = self.board.cells[self.ball.x - 1][self.ball.y + 1]
            if cell_1.colour != renderer.BLACK and cell_2.colour != renderer.BLACK:
                self.view_x -= 1

    def move_right(self):
        if self.view_x < self.maze_width - renderer.COLS:
            # check maze is clear to move right
            cell_1 = self.board.cells[self.ball.x + 2][self.ball.y]
            cell_2 = self.board.cells[self.ball.x + 2][self.ball.y + 1]
            if cell_1.colour != renderer.BLACK and cell_2.colour != renderer.BLACK:
                self.view_x += 1

    def move_up(self):
        if self.view_y > 0:
            cell_1 = self.board.cells[self.ball.x][self.ball.y - 1]
            cell_2 = self.board.cells[self.ball.x + 1][self.ball.y - 1]
            if cell_1.colour != renderer.BLACK and cell_2.colour != renderer.BLACK:
                self.view_y -= 1

    def render(self):
        '''
        render_board creates an 8x8 board that can be passed to a renderer
        '''

        self.board.cells = self.maze.get_cells(self.view_x, self.view_y)
        self.overlay_ball_cells()
        self.renderer.render(self.board.cells)

    def overlay_ball_cells(self):
        # overlay ball position
        ball_cells = self.ball.get_cells()

        board_cell = self.board.cells[3][3]
        ball_cell = ball_cells[0][0]
        self.average_colour(board_cell, ball_cell)
        board_cell = self.board.cells[4][3]
        ball_cell = ball_cells[1][0]
        self.average_colour(board_cell, ball_cell)
        board_cell = self.board.cells[3][4]
        ball_cell = ball_cells[0][1]
        self.average_colour(board_cell, ball_cell)
        board_cell = self.board.cells[4][4]
        ball_cell = ball_cells[1][1]
        self.average_colour(board_cell, ball_cell)

    def average_colour(self, board_cell, ball_cell):
        if board_cell.colour != renderer.WHITE:
            temp_colour = ball_cell.colour - board_cell.colour
            board_cell.colour = temp_colour
        else:
            board_cell.colour = ball_cell.colour

    def run(self):
        '''
        Run forever
        '''

        quit = False

        while not quit:
            if self.platform == SENSE_HAT:
                self.handle_stick_events()
            else:
                quit = self.handle_keyboard_events()

            self.render()
            time.sleep(0.1)

    def set_viewport(self, x, y):
        self.view_x = x
        self.view_y = y
Ejemplo n.º 5
0
Archivo: s4data.py Proyecto: rb6/s4-pi
        filestamp.tm_hour) + '-' + repr(filestamp.tm_min) + '_data.csv'
f = open(data_filename, 'w')

####################################################################
####################################################################
####################################################################
# MAIN LOOP
while True:
    timestamp = time.time()
    data_record(timestamp)
    led_display.data_display('data')

    #checking if the center joystick has been pushed
    stick_press = stick.wait(timeout=0.01)
    if stick_press:
        event = stick.read()
        if event.state == stick.STATE_PRESS:
            if event.key == stick.KEY_ENTER:
                break

#closing the data files
f.close()

####################################################################
####################################################################
####################################################################
# ALTITUDE REPORTING SCRIPT
while True:
    start_alt_ft = (1 - (start_pressure / 1013.25)**0.190284) * 145366.45
    max_alt_ft = (1 - (min_pressure / 1013.25)**0.190284) * 145366.45
    sense.show_message("Max Alt: " + str(round(max_alt_ft - start_alt_ft)) +
Ejemplo n.º 6
0
class SenseHATLink(dslink.DSLink):
    def __init__(self, config):
        self.sense = SenseHat()
        self.sense.clear()
        self.stick = SenseStick()
        self.stick_thread = Thread(target=self.evdev_loop)
        self.stick_thread.daemon = True
        self.stick_thread.start()
        self.msg = MessageHandler(self.sense)
        dslink.DSLink.__init__(self, config)

    def evdev_loop(self):
        while self.stick_thread.is_alive:
            event = self.stick.read()
            if event.key is SenseStick.KEY_UP:
                key = self.responder.get_super_root().get("/stick/up")
                self.set_key_state(key, event)
            elif event.key is SenseStick.KEY_DOWN:
                key = self.responder.get_super_root().get("/stick/down")
                self.set_key_state(key, event)
            elif event.key is SenseStick.KEY_LEFT:
                key = self.responder.get_super_root().get("/stick/left")
                self.set_key_state(key, event)
            elif event.key is SenseStick.KEY_RIGHT:
                key = self.responder.get_super_root().get("/stick/right")
                self.set_key_state(key, event)
            elif event.key is SenseStick.KEY_ENTER:
                key = self.responder.get_super_root().get("/stick/button")
                self.set_key_state(key, event)

    @staticmethod
    def set_key_state(key, event):
        if key.is_subscribed():
            if (event.state == SenseStick.STATE_PRESS or event.state == SenseStick.STATE_HOLD) and key.get_value() is not "DOWN":
                key.set_value("DOWN", check=False)
            elif event.state == SenseStick.STATE_RELEASE and key.get_value() is not "UP":
                key.set_value("UP", check=False)

    def start(self):
        self.responder.profile_manager.create_profile("show_message")
        self.responder.profile_manager.register_callback("show_message", self.start_show_message)

        self.responder.profile_manager.create_profile("set_pixel")
        self.responder.profile_manager.register_callback("set_pixel", self.set_pixel)

        self.responder.profile_manager.create_profile("clear_screen")
        self.responder.profile_manager.register_callback("clear_screen", self.clear_screen)

        self.responder.profile_manager.create_profile("set_pixels")
        self.responder.profile_manager.register_callback("set_pixels", self.set_pixels)

        reactor.callLater(0.5, self.update)
        reactor.callLater(0.01, self.location_update)

    def get_default_nodes(self, root):
        # Screen Manipulation
        show_message = dslink.Node("show_message", root)
        show_message.set_display_name("Show Message")
        show_message.set_invokable(dslink.Permission.WRITE)
        show_message.set_profile("show_message")
        show_message.set_parameters([
            {
                "name": "Message",
                "type": "string"
            },
            {
                "name": "Scroll Speed",
                "type": "number",
                "default": "0.1"
            },
            {
                "name": "Foreground",
                "type": "dynamic",
                "editor": "color"
            },
            {
                "name": "Background",
                "type": "dynamic",
                "editor": "color"
            }
        ])

        set_pixel = dslink.Node("set_pixel", root)
        set_pixel.set_display_name("Set Pixel")
        set_pixel.set_profile("set_pixel")
        set_pixel.set_invokable(dslink.Permission.WRITE)
        set_pixel.set_parameters([
            {
                "name": "X",
                "type": "int",
                "default": 0
            },
            {
                "name": "Y",
                "type": "int",
                "default": 0
            },
            {
                "name": "Color",
                "type": "dynamic",
                "editor": "color"
            }
        ])
        set_pixel.set_columns([
            {
                "name": "Message",
                "type": "string"
            }
        ])

        clear_screen = dslink.Node("clear_screen", root)
        clear_screen.set_display_name("Clear Screen")
        clear_screen.set_profile("clear_screen")
        clear_screen.set_invokable(dslink.Permission.WRITE)

        set_pixels = dslink.Node("set_pixels", root)
        set_pixels.set_display_name("Set Pixels")
        set_pixels.set_profile("set_pixels")
        set_pixels.set_invokable(dslink.Permission.WRITE)
        set_pixels.set_parameters([
            {
                "name": "Pixels",
                "type": "string"
            }
        ])

        # Temperature
        temperature = dslink.Node("temperature", root)
        temperature.set_display_name("Temperature")
        temperature.set_type("number")
        temperature.set_value(self.sense.temperature)
        temperature.set_attribute("@unit", "C")

        # Humidity
        humidity = dslink.Node("humidity", root)
        humidity.set_display_name("Humidity")
        humidity.set_type("number")
        humidity.set_value(self.sense.humidity)
        humidity.set_attribute("@unit", "%")

        # Pressure
        pressure = dslink.Node("pressure", root)
        pressure.set_display_name("Pressure")
        pressure.set_type("number")
        pressure.set_value(self.sense.pressure)
        pressure.set_attribute("@unit", "MB")

        # Gyroscope
        gyroscope = dslink.Node("gyroscope", root)
        gyroscope.set_display_name("Gyroscope")

        values = self.sense.gyroscope

        pitch = dslink.Node("pitch", root)
        pitch.set_display_name("Pitch")
        pitch.set_type("number")
        pitch.set_value(values["pitch"])

        roll = dslink.Node("roll", root)
        roll.set_display_name("Roll")
        roll.set_type("number")
        roll.set_value(values["roll"])

        yaw = dslink.Node("yaw", root)
        yaw.set_display_name("Yaw")
        yaw.set_type("number")
        yaw.set_value(values["yaw"])

        gyroscope.add_child(pitch)
        gyroscope.add_child(roll)
        gyroscope.add_child(yaw)

        # Accelerometer
        accelerometer = dslink.Node("accelerometer", root)
        accelerometer.set_display_name("Accelerometer")

        values = self.sense.accelerometer

        pitch = dslink.Node("pitch", root)
        pitch.set_display_name("Pitch")
        pitch.set_type("number")
        pitch.set_value(values["pitch"])

        roll = dslink.Node("roll", root)
        roll.set_display_name("Roll")
        roll.set_type("number")
        roll.set_value(values["roll"])

        yaw = dslink.Node("yaw", root)
        yaw.set_display_name("Yaw")
        yaw.set_type("number")
        yaw.set_value(values["yaw"])

        accelerometer.add_child(pitch)
        accelerometer.add_child(roll)
        accelerometer.add_child(yaw)

        # Compass
        north = self.sense.compass

        compass = dslink.Node("compass", root)
        compass.set_display_name("Compass")
        compass.set_type("number")
        compass.set_value(north)

        # Joystick
        joystick = dslink.Node("stick", root)
        joystick.set_display_name("Stick")

        up = dslink.Node("up", joystick)
        up.set_display_name("Up")
        up.set_type(dslink.Value.build_enum(["UP, DOWN"]))
        up.set_value("UP", check=False)

        down = dslink.Node("down", joystick)
        down.set_display_name("Down")
        down.set_type(dslink.Value.build_enum(["UP, DOWN"]))
        down.set_value("UP", check=False)

        left = dslink.Node("left", joystick)
        left.set_display_name("Left")
        left.set_type(dslink.Value.build_enum(["UP, DOWN"]))
        left.set_value("UP", check=False)

        right = dslink.Node("right", joystick)
        right.set_display_name("Right")
        right.set_type(dslink.Value.build_enum(["UP, DOWN"]))
        right.set_value("UP", check=False)

        button = dslink.Node("button", joystick)
        button.set_display_name("Button")
        button.set_type(dslink.Value.build_enum(["UP, DOWN"]))
        button.set_value("UP", check=False)

        joystick.add_child(up)
        joystick.add_child(down)
        joystick.add_child(left)
        joystick.add_child(right)
        joystick.add_child(button)

        # Update configuration
        location_update = dslink.Node("location_update", root)
        location_update.set_display_name("Location Update Time")
        location_update.set_writable(dslink.Permission.CONFIG)
        location_update.set_type("number")
        location_update.set_value(0.05)

        # Add Nodes to root
        root.add_child(show_message)
        root.add_child(set_pixel)
        root.add_child(clear_screen)
        root.add_child(set_pixels)
        root.add_child(temperature)
        root.add_child(humidity)
        root.add_child(pressure)
        root.add_child(gyroscope)
        root.add_child(accelerometer)
        root.add_child(compass)
        root.add_child(joystick)
        root.add_child(location_update)

        return root

    def start_show_message(self, parameters):
        thread = Thread(target=self.show_message, args=[parameters])
        thread.start()
        return []

    def show_message(self, parameters):
        self.msg.do_cancel()
        message = str(parameters[1]["Message"])
        scroll_speed = float(parameters[1]["Scroll Speed"])
        if "Foreground" in parameters[1]:
            fgin = str(parameters[1]["Foreground"]).lstrip("#")
            fgred, fggreen, fgblue = rgb(hex(int(fgin))[2:].zfill(6))
            fg = [fgred, fggreen, fgblue]
        else:
            fg = [255, 255, 255]
        if "Background" in parameters[1]:
            bgin = str(parameters[1]["Background"]).lstrip("#")
            bgred, bggreen, bgblue = rgb(hex(int(bgin))[2:].zfill(6))
            bg = [bgred, bggreen, bgblue]
        else:
            bg = [0, 0, 0]
        self.msg.show_message(message,
                              scroll_speed=scroll_speed,
                              text_colour=fg,
                              back_colour=bg)

    def set_pixel(self, parameters):
        x = int(parameters[1]["X"])
        y = int(parameters[1]["Y"])
        if (x < 0 or x > 7) or (y < 0 or y > 7):
            return [
                [
                    "Invalid coordinate, 0-7 is valid."
                ]
            ]
        if "Color" in parameters[1]:
            input = str(parameters[1]["Color"]).lstrip("#")
            red, green, blue = rgb(hex(int(input))[2:].zfill(6))
        else:
            red = green = blue = 255

        thread = Thread(target=self.sense.set_pixel, args=[x, y, red, green, blue])
        thread.start()

        return [
            [
                "Success"
            ]
        ]

    def clear_screen(self, parameters):
        thread = Thread(target=self.sense.clear)
        thread.start()

        return []

    def set_pixels(self, parameters):
        pixels = json.loads(parameters[1]["Pixels"])
        for pixel in pixels:
            if len(pixel) is not 3:
                return [
                    [
                        "Pixel arrays must contain three values: red, green, and blue"
                    ]
                ]
            for p in pixel:
                if p > 255 or p < 0:
                    return [
                        [
                            "Pixel colors must be 0-255"
                        ]
                    ]

        thread = Thread(target=self.sense.set_pixels, args=[pixels])
        thread.start()

        return [
            [
                "Success"
            ]
        ]

    def update(self):
        """
        Function that runs every 500 ms for values that need slow updates.
        """
        temperature = self.responder.get_super_root().get("/temperature")
        humidity = self.responder.get_super_root().get("/humidity")
        pressure = self.responder.get_super_root().get("/pressure")

        if temperature.is_subscribed():
            temperature.set_value(self.sense.temperature)
        if humidity.is_subscribed():
            humidity.set_value(self.sense.humidity)
        if pressure.is_subscribed():
            pressure.set_value(self.sense.pressure)

        reactor.callLater(0.5, self.update)

    def location_update(self):
        """
        Function that runs every 50 ms for values that need quick updates.
        """
        # Gyroscope
        pitch = self.responder.get_super_root().get("/gyroscope/pitch")
        roll = self.responder.get_super_root().get("/gyroscope/roll")
        yaw = self.responder.get_super_root().get("/gyroscope/yaw")

        values = self.sense.gyroscope

        if pitch.is_subscribed():
            pitch.set_value(values["pitch"])
        if roll.is_subscribed():
            roll.set_value(values["roll"])
        if yaw.is_subscribed():
            yaw.set_value(values["yaw"])

        # Accelerometer
        pitch = self.responder.get_super_root().get("/accelerometer/pitch")
        roll = self.responder.get_super_root().get("/accelerometer/roll")
        yaw = self.responder.get_super_root().get("/accelerometer/yaw")

        values = self.sense.accelerometer

        if pitch.is_subscribed():
            pitch.set_value(values["pitch"])
        if roll.is_subscribed():
            roll.set_value(values["roll"])
        if yaw.is_subscribed():
            yaw.set_value(values["yaw"])

        # Compass
        compass = self.responder.get_super_root().get("/compass")

        north = self.sense.compass

        if compass.is_subscribed():
            compass.set_value(north)

        update_time = self.responder.get_super_root().get("/location_update").get_value()
        reactor.callLater(update_time, self.location_update)
Ejemplo n.º 7
0
                grid[row][column]=0
            if grid[row][column+1]==grid[row][column]:
                grid[row][column+1]=grid[row][column+1]+grid[row][column]
                grid[row][column]=0


grid[random.choice([0,1,2,3])][random.choice([0,1,2,3])]=2

while True:
    for y in range(4):
        for x in range(4):
           drawTile(y,x,grid[y][x])

    keypressed=""
    while keypressed=="":
        keypressed  = sensestick.read()[1]
       # print keypressed 
        if (keypressed!=KEY_UP) and (keypressed!=KEY_DOWN) and (keypressed!=KEY_LEFT) and (keypressed!=KEY_RIGHT) and (keypressed!=KEY_ENTER):
            keypressed=""

    if keypressed!=KEY_ENTER:
        updateGrid(keypressed)
        listForRow = []
        listForColumnn = []
        count = 0
        for row in range(0,4):
            for column in range(0,4):
                if grid[row][column]==0:
                    count+=1
                    listForRow.append(row)
                    listForColumnn.append(column)