def main(): sense = SenseHat() sense.clear() soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.connect(("127.0.0.1", 50007)) print("Connected.") while True: data = input("Client (q: quit, y: recv data) > ") soc.send(data.encode()) if data == "q": soc.close() break data = (soc.recv(1024)).decode() print("cServer > ", data) if (data[0] >= "0" or data[0] <= "9"): datastr = data.split(",") print("data received: ", datastr) mylist = [float(i) for i in datastr] THI = 0.81 * mylist[0] + 0.01 * mylist[1] * (0.99 * mylist[0] - 14.3) + 46.3 if (THI < 60): x = 255 * (THI - 45) / 60 RGB = [x, 0, 255 - x] elif (THI < 75): RGB = [0, 255, 0] else: x = 255 * (THI - 75) / 110 RGB = [x, 255 - x, 0] print("THI: " + str(THI) + ", RGB:" + str(RGB)) sense.clear(RGB[0], RGB[1], RGB[2]) print("Finished.")
def main(): path = "data.csv" sense = SenseHat() sense.clear() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 50007)) s.listen(1) soc, addr = s.accept() print("Connected by " + str(addr)) while True: data = (soc.recv(1024)).decode() print("Client > ", data) if data == "q": soc.close() break elif data == "y": t = str(sense.get_temperature()) h = str(sense.get_humidity()) p = str(sense.get_pressure()) data = t + "," + h + "," + p with open(path, mode="a") as f: f.write( (datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S") + "," + data + "\n") else: data = input("Server > ") print("data = " + data) soc.send(data.encode()) print("Finished.")
def main() -> None: global desired_temperature, room_temperature, screen, sense, semaphore sensor_thread: Thread events_thread: Thread try: print( f'{colors.GREEN}Initializing the thermostat using sense hat{colors.END}' ) sense = SenseHat() sense.clear() desired_temperature = room_temperature = sense.get_temperature() print(f'{colors.GREEN}Connecting to screen via socket{colors.END}') screen = connect(host, port) print(f'{colors.GREEN}Initializing application threads{colors.END}') semaphore = Semaphore() sensor_thread = Thread(target=display) events_thread = Thread(target=process) except: print(f'{colors.RED}Failed to initialize the thermostat{colors.END}') print('Error: {}'.format(sys.exc_info())) sys.exit(1) print(f'{colors.GREEN}Initialization complete!{colors.END}') sensor_thread.start() events_thread.start()
def main(): ip = sys.argv[1] port = int(sys.argv[2]) multicast = False # CREATE CoAP server server = CoAPServer(ip, port, multicast) print server # Create thread to get client threshold thread = Thread(target=listener, args=(server, )) thread.setDaemon(True) thread.start() # Initialize emulator sense = SenseHat() # Red color red = (255, 0, 0) while True: time.sleep(1) # Get values from emulator t = sense.get_temperature() p = sense.get_pressure() if t > server.t_lim or p > server.p_lim: # if temperature and pressure values are above threshold sense.clear(red) # turn on all red lights else: sense.clear() # turn off all leds
def actuator_observer(): sense = SenseHat() global temp_t global humi_t while True: time.sleep(1) print("TT = " + str(temp_t) + "\tTemp = " + str(sense.get_temperature()) + "\tHU= " + str(humi_t) + "\tHumidity = " + str(sense.get_humidity())) if sense.get_temperature() > float( temp_t) or sense.get_humidity() > float(humi_t): sense.clear(red) else: sense.clear(black)
def shat(): sense = SenseHat() sense.clear() g = (0, 255, 0) k = (0, 0, 0,) r = (255, 0, 0,) y = (255, 255, 0,) draw_pixels = [ g, g, g, g, g, g, g, g, g, g, g, g, g, g, g, g, g, k, k, g, g, k, k, g, g, k, k, g, g, k, k, g, g, g, g, k, k, g, g, g, g, g, k, k, k, k, g, g, g, g, k, k, k, k, g, g, g, g, k, g, g, k, g, g, ] sense.set_pixels(draw_pixels)
from sense_emu import SenseHat from coapthon.client.helperclient import HelperClient from coapthon.utils import parse_uri import argparse sense = SenseHat() sense.clear() # rgb para cor vermalha r = 255 g = 0 b = 0 # recebendo os argumentos de temperatura e pressao da linha de comando parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("-t", "--temp", help="Valor limite para temperatura", default=40) parser.add_argument("-p", "--pres", help="Valor limite para Pressao", default=600) args = parser.parse_args() tlim = float(args.temp) plim = float(args.pres) tempx = 0 pressurex = 0 print 'Modifique a temperatura e pressao no painel Sense HAT' print 'Clique em ctrl C para sair' global client client = HelperClient(server=('127.0.0.1', 5683)) while True: # obtendo os valores do servidor COAP responseT = client.get('temp')
def display_readings(hat): """ Display the temperature, pressure, and humidity readings of the HAT as red, green, and blue bars on the screen respectively. """ temperature_range = (0, 40) pressure_range = (950, 1050) humidity_range = (0, 100) temperature = 7 - round( scale(clamp(hat.temperature, *temperature_range), *temperature_range)) pressure = 7 - round( scale(clamp(hat.pressure, *pressure_range), *pressure_range)) humidity = 7 - round( scale(clamp(hat.humidity, *humidity_range), *humidity_range)) # Scroll screen 1 pixel left, clear the right column, and render new points screen = np.array(hat.get_pixels(), dtype=np.uint8).reshape((8, 8, 3)) screen[:, :-1, :] = screen[:, 1:, :] screen[:, 7, :] = (0, 0, 0) screen[temperature, 7, :] += np.array((255, 0, 0), dtype=np.uint8) screen[pressure, 7, :] += np.array((0, 255, 0), dtype=np.uint8) screen[humidity, 7, :] += np.array((0, 0, 255), dtype=np.uint8) hat.set_pixels([pixel for row in screen for pixel in row]) hat = SenseHat() hat.clear() while True: display_readings(hat) sleep(1)
from sense_emu import SenseHat import time #instancia em python sense = SenseHat() #criando variaveis com cores red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) #controla a velodidade a padrão é 0.1 scroll_speed = 0.005 sense.show_message("Olá Mundo!", scroll_speed, green) nome = input("Digite seu nome: ") sense.show_message(nome, scroll_speed, green) #limpando matriz de led sense.clear() int_red = 0 int_green = 0 int_azul = 0 cor = (int_red, int_green, int_azul) while True: time.sleep(1) sense.clear(red) time.sleep(5) #pega a humidade do sensor humidity = sense.get_humidity() print("Umidade: " + str(humidity)) sense.show_message("Umidade: " + str(humidity), scroll_speed, green)
from math import ceil aio = Client(my_username, my_key) try: # access a feed and store in feeds dictionary weather_feed = aio.feeds('weatherfeed') weather_map = aio.feeds('weathermap') except RequestError: # weather_feed = aio.create_feed(Feed(name='weatherfeed', key='weatherfeed', history=False)) weather_map = aio.create_feed( Feed(name='weathermap', key='weathermap', history=False)) # test sense = SenseHat() sense.clear() url = 'http://api.openweathermap.org/data/2.5/weather?q=Trento&units=metric&appid=0e53fa039f38945cd1d62c6423362dd9' response = get(url) result = response.json() print(response) ## Creates the String to def make_text(): string = city + '\n' for items, value in output_list: if items == 'Humidity:': string += str(items) + ' ' + str(int(ceil(value))) + ' %' + '\n'
from sense_emu import SenseHat sense = SenseHat() blue = (0, 0, 255) green = (0, 255, 0) yellow = (255, 255, 0) white = (255, 255, 255) red = (255, 0, 0) black = (0, 0, 0) def random_colour(): return (randint(0, 255), randint(0, 255), randint(0, 255)) sense.clear(random_colour()) sleep(1) # light corners maxc = 7 sense.clear() sense.set_pixel(0, 0, white) sense.set_pixel(0, maxc, white) sense.set_pixel(maxc, 0, white) sense.set_pixel(maxc, maxc, white) sleep(1) # draw smiley sense.clear() sense.set_pixel(2, 2, (0, 0, 255)) sense.set_pixel(4, 2, (0, 0, 255))
#!/usr/bin/python from sense_emu import SenseHat import os import time import pygame # See http://www.pygame.org/docs from pygame.locals import * print("Press Escape to quit") time.sleep(1) pygame.init() pygame.display.set_mode((640, 480)) sense = SenseHat() sense.clear() # Blank the LED matrix # 0, 0 = Top left # 7, 7 = Bottom right UP_PIXELS = [[3, 0], [4, 0]] DOWN_PIXELS = [[3, 7], [4, 7]] LEFT_PIXELS = [[0, 3], [0, 4]] RIGHT_PIXELS = [[7, 3], [7, 4]] CENTRE_PIXELS = [[3, 3], [4, 3], [3, 4], [4, 4]] def set_pixels(pixels, col): for p in pixels: sense.set_pixel(p[0], p[1], col[0], col[1], col[2])
def senseclear(): sense = SenseHat() sense.clear()
from mcpi.minecraft import Minecraft from sense_emu import SenseHat mc = Minecraft.create() sense = SenseHat() owool = (35, 1) mwool = (35, 2) lbwool = (35, 3) ywool = (35, 4) lwool = (35, 5) pwool = (35, 6) gwool = (35, 7) lgwool = (35, 8) cwool = (35, 9) purwool = (35, 10) bwool = (35, 11) brwool = (35, 12) grwool = (35, 0) rwool = (35, 0) blwool = (35, 0) while True: x, y, z = mc.player.getPos() block_beneath = mc.getBlock(x, y-1, z) print(block_beneath) if block_beneath == (35): sense.clear(255, 255, 255) if block_beneath == (35,: sense.clear(255, 165, 0)
break # Create CoAP client client = HelperClient(server=(host, port)) # Create thread to get user input thread = Thread(target=getUserInput) thread.setDaemon(True) thread.start() while True: time.sleep(1) response_t = client.get(path_t) # get temperature value from server response_p = client.get(path_p) # get pressure value from server t = 0 p = 0 try: t = float(response_t.payload) p = float(response_p.payload) if t > t_lim or p > p_lim: # if temperature and pressure values are above threshold sense.clear(red) # turn on all red lights else: sense.clear() # turn off all leds except: print('Sensors not defined or in wrong format') # Error with payload client.stop()
o, o, b, o, o, o, o, o, o, ] return logo letters = [letter_r(), letter_f()] s.clear() # clear the screen count = 0 # keep track of what letter to show next while True: for event in s.stick.get_events(): # Check if the joystick was pressed if event.action == "pressed": s.set_pixels(letters[count % len(letters)]) # increment count count += 1 """ change letters to TA only change every second time you change button
print(event) def move_down(event): global y if y < 6 and event.action=='pressed': y += 1 print(event) def draw_ball(): sense.set_pixel(ball_position[0], ball_position[1], 0, 0, 255) ball_position[0] += ball_velocity[0] ball_position[1] += ball_velocity[1] if ball_position[0] == 7: ball_velocity[0] = -ball_velocity[0] if ball_position[1] == 0 or ball_position[1] == 7: ball_velocity[1] = -ball_velocity[1] if ball_position[0] == 0: sense.show_message("You Lose", text_colour=(255, 0, 0)) quit() if ball_position[0] == 1 and y - 1 <= ball_position[1] <= y+1: ball_velocity[0] = -ball_velocity[0] sense.stick.direction_up = move_up sense.stick.direction_down = move_down while True: sense.clear(0, 0, 0) draw_bat() draw_ball() sleep(0.25)
class Board(object): """ An instance of this class represents a game board Attributes: _grid -- 2d list of GridPos objects _ships -- list of ships on board Methods: place_ship(ship) -- place Ship object onto board guess(x, y) -- fire a shot at position x, y """ def __init__(self, n): """ Initializes a Board object of size n x n Parameters: n -- size for n x n grid to create Post-Condition: An instance of a Board object """ self._grid = [] self._ships = [] self._sense = SenseHat() self._sense.clear(0, 0, 255) for i in range(n): row = [] for j in range(n): new_pos = GridPos(i, j) row.append(new_pos) self._grid.append(row) def place_ship(self, ship): """ Places a ship onto the board Parameters: ship -- ship to add Returns: T/F if ship was successfully placed without overlapping an existing ship Pre-Condition: Ship is valid Post-Condition: Ship object is added to the board and list of ships """ success = True self._ships.append(ship) positions = ship.get_positions() for pos in positions: print(pos) x, y = (pos[1], pos[0]) current = self._grid[-1 - x][y] if current.contains_ship(): success = False else: current.set_ship_at_pos(ship) ## self._sense.set_pixel(x,y,0,0,0) return success def guess(self, x, y): """ Processes a guess at position x, y After guess is processed, any sunken ships are removed from the list of ships. If all ships are removed, the game ends. Parameters: x -- x coordinate of guess y -- y coordinate of guess Pre-Conditions: Guess is valid """ print(x, y) if 0 <= x < len(self._grid[0]) and 0 <= y < len(self._grid): current = self._grid[-1 - x][y] if not current.contains_ship() and not current.was_guessed(): current.miss() ## self._sense.set_pixel(x, y, 255,255,255) elif not current.contains_ship() and current.was_guessed(): print("miss (again)") elif current.contains_ship() and not current.was_guessed(): current.hit() ## self._sense.set_pixel(x, y, 255,0,0) elif current.contains_ship() and current.was_guessed(): print("hit (again)") else: print("illegal guess") for ship in self._ships: if ship.is_sunk(): self._ships.remove(ship) if len(self._ships) == 0: print("all ships sunk: game over") sys.exit(0) def __str__(self): """ String representation of the game board. When printed, shows a visual of the current game board """ results = "" for i in range(len(self._grid)): results += f"{len(self._grid)- 1 - i}\t" for j in range(len(self._grid[0])): results += str(self._grid[i][j]) + '\t' results += '\n' for i in range(len(self._grid)): results += f"\t{i}" return results def __len__(self): """ Used to determine the bounds of the game board """ return len(self._grid)
from sense_emu import SenseHat sh = SenseHat() sh.clear(225, 225, 225)
def listColorsRainbow(): for i in range(1, 256, 4): c = i / 256 col = colorsys.hls_to_rgb(c, 0.5, 1) color = (int(col[0] * 255), int(col[1] * 255), int(col[2] * 255)) pos = i // 4 x = pos // 8 y = pos % 8 #print('(x,y) = ({}/{}), c is {}, color is {}, col2 is {}'.format(x, y, c, col, color)) s.set_pixel(x, y, color) #c = i/256 return color s.clear() time.sleep(2) #listColors(getColorRed) listColors(getColorRed2Green) time.sleep(2) #listColors(getColorGreen2Blue) #time.sleep(2) #listColors(getColorBlue2Red) #listColors(getColorYellow) #listColors(getColorGreen) #listColors(getColorBlue) #listColors(getColorViolet) listColorsRainbow()
from sense_emu import SenseHat # Import SenseHat Emulator sense = SenseHat() red = (255,0,0) # Instantiate RED pixel pressure_threshold = 1000 # Set Pressure threshold temp_threshold = 60 # Set Temperature threshold while True: temperature = sense.temperature # Get current Temperature pressure = sense.pressure # Get current Pressure if temperature > temp_threshold and pressure > pressure_threshold: sense.clear(red) # Set LEDs red if temperature and pressure are above the threshold. else: sense.clear() # If not, keep the LEDs off.
v = (0, 255, 0) x = 0 y = 0 # matrice de couleur pour l'affichage # (le centre de cible est en [4,4]car la matrice led n'est pas impaire) couleur = [[r, r, r, r, r, r, r, r], [r, o, o, o, o, o, o, r], [r, o, o, o, o, o, o, r], [r, o, o, o, o, o, o, r], [r, o, o, o, v, o, o, r], [r, o, o, o, o, o, o, r], [r, o, o, o, o, o, o, r], [r, r, r, r, r, r, r, r]] sense = SenseHat() # instanciation Sense-HAT # configuration de l'IMU, seulement les gyroscopes sense.set_imu_config(False, True, False) sense.clear() # efface l'affichage def lect_capt(): global x, y o = sense.get_orientation_radians() tang = o["pitch"] roul = o["roll"] # formattage des données x = int((pi + roul) * 8 / (2 * pi)) y = int((pi + tang) * 8 / (2 * pi)) print(x, y)
def main(): global sense # Initial setup sense = SenseHat() # sense.set_rotation(180) # sense.low_light = True update_interval = 7 background_colour = [0, 0, 0] shape_types = [ ShapeType([ Point2(0, 0), Point2(0, 1), Point2(0, 2), Point2(0, 3), ]), ShapeType([ Point2(0, 0), Point2(0, 1), Point2(1, 0), Point2(1, 1), ]), ShapeType([ Point2(0, 0), Point2(0, 1), Point2(0, 2), Point2(1, 1), ]), ShapeType([ Point2(0, 0), Point2(0, 1), Point2(0, 2), Point2(1, 0), ]), ShapeType([ Point2(0, 0), Point2(0, 1), Point2(0, 2), Point2(1, 2), ]), ShapeType([ Point2(0, 1), Point2(0, 2), Point2(1, 0), Point2(1, 1), ]), ShapeType([ Point2(0, 0), Point2(0, 1), Point2(1, 1), Point2(1, 2), ]), ] shapes = [] count = 0 sense.stick.direction_left = lambda event: move_left(event, shapes) sense.stick.direction_right = lambda event: move_right(event, shapes) sense.stick.direction_up = lambda event: rotate_shape(event, shapes) while True: sense.clear(background_colour) # Update shape velocities for shape in shapes: if shape.pos.y >= 8 - shape.shape_type.compute_height( ) or shape.collides(shapes, Vector2(0, 1)): shape.vel = Vector2(0, 0) # Update shape positions based on their updated velocities for shape in shapes: shape.pos += shape.vel # Set count to zero if update interval exceed if count >= update_interval: count = 0 # If interval reached, choose random shape type then add to `moving_shapes` list if count == 0: shape_type = shape_types[randrange(len(shape_types))] pos = Point2(randrange(9 - shape_type.compute_width()), 1 - shape_type.compute_height()) initial_vel = Vector2(0, 1) shape = Shape(shape_type, pos, initial_vel) shapes.append(shape) # Display shapes for shape in shapes: shape.display() # Increment count and wait count += 1 sleep(1)
from sense_emu import SenseHat sense = SenseHat() import time import random sense.clear(0, 0, 0) purple = (150, 117, 175) blue = (0, 249, 182) x = random.randint(1, 6) y = random.randint(1, 6) x_sens = 1 y_sens = 1 rx = 0 ry = 0 def pongRaquette(): sense.set_pixel(rx, ry, blue) sense.set_pixel(rx, ry + 1, blue) sense.set_pixel(rx, ry + 2, blue) def down(): global ry if ry + 2 < 7:
porta_servidor = int( sys.argv[2]) # Recebendo a porta do servidor irá operar servidor = CoAPServer( ip_servidor, porta_servidor ) # iniciando o servidor no ip e porta informados como parâmetro rgb_vermelho = (255, 0, 0) # Setando o rgb da cor vermelha # Iniciando threads para possibilitar que os clientes sejam ouvidos # e o senseHat seja usado simultaneamente thread = Thread(target=ouvir_clientes, args=(servidor, )) thread.setDaemon(True) thread.start() while True: # Capturando informações de pressão e temperatura informados no sensor pressao_atual = sensor.get_pressure() temperatura_atual = sensor.get_temperature() print("Limite de temperatura " + str(servidor.limtemperatura)) print("Limite de pressao " + str(servidor.limpressao)) # Teste para acender ou apagar os leds if temperatura_atual > servidor.limtemperatura and pressao_atual > servidor.limpressao: # Acende o led na cor vermelha pixels = [rgb_vermelho for i in range(64) ] # Configurando a cor vermelha para cada um dos 64 leds sensor.set_pixels(pixels) else: # Apagando os leds sensor.clear()
from sense_emu import SenseHat from colorzero import Color sense = SenseHat() c = Color('green') sense.clear(c.rgb_bytes)
sleep(0.5) sense.show_letter("E", random_colour(), back_colour=r) sleep(0.5) """Replace with your child's name""" sense.show_letter("M", random_colour(), back_colour=r) sleep(0.5) sense.show_letter("Y", random_colour(), back_colour=g) sleep(0.8) sense.show_letter("K", random_colour(), back_colour=b) sleep(0.5) sense.show_letter("I", random_colour(), back_colour=y) sleep(0.5) sense.show_letter("D", random_colour(), back_colour=r) sleep(0.5) """scroll goodnight my Darling""" sense.show_message("Goodnight my Darling !", text_colour=y, back_colour=b, scroll_speed=0.08) """Optional infinite Sacha loop with a while True: """ sense.show_letter("L", random_colour(), back_colour=r) sleep(0.5) sense.show_letter("O", random_colour(), back_colour=g) sleep(0.5) sense.show_letter("V", random_colour(), back_colour=b) sleep(0.5) sense.show_letter("E", random_colour(), back_colour=y) sleep(0.5) """clear the sense Hat""" sense.clear()
def render_POST(self, request): # Instantiate SenseHat sensor sense = SenseHat() sense.clear(red) self.payload = "OK" return self