def gyroGame(maxDegs): sense = SenseHat() while 1: orientation = sense.get_orientation_degrees() if orientation['pitch'] < maxDegs: realpitch = orientation['pitch'] else: realpitch = -1 * (360 - orientation['pitch']) if orientation['roll'] < maxDegs: realroll = orientation['roll'] else: realroll = -1 * (360 - orientation['roll']) x_pos = 7 - int( round(((maxDegs + realpitch) / (2.0 * maxDegs)) * 8.0, 0)) y_pos = int(round(((maxDegs + realroll) / (2.0 * maxDegs)) * 8.0, 0)) if x_pos > 7: x_pos = 7 if x_pos < 0: x_pos = 0 if y_pos > 7: y_pos = 7 if y_pos < 0: y_pos = 0 sense.clear() if (1 <= x_pos <= 6) and (1 <= y_pos <= 6): sense.set_pixel(x_pos, y_pos, 0, 0, 255) else: sense.set_pixel(x_pos, y_pos, 255, 0, 0)
def gyroGame(maxDegs): sense = SenseHat() while 1: orientation = sense.get_orientation_degrees() if orientation['pitch'] < maxDegs: realpitch=orientation['pitch'] else: realpitch=-1*(360-orientation['pitch']) if orientation['roll'] < maxDegs: realroll=orientation['roll'] else: realroll=-1*(360-orientation['roll']) x_pos=7-int(round(((maxDegs+realpitch)/(2.0*maxDegs))*8.0,0)) y_pos=int(round(((maxDegs+realroll)/(2.0*maxDegs))*8.0,0)) if x_pos > 7: x_pos = 7 if x_pos < 0: x_pos = 0 if y_pos > 7: y_pos = 7 if y_pos < 0: y_pos = 0 sense.clear() if (1 <= x_pos <=6) and (1 <= y_pos <=6): sense.set_pixel(x_pos,y_pos,0,0,255) else: sense.set_pixel(x_pos,y_pos,255,0,0)
class Board(): def __init__(self): self.sense = SenseHat() self.walls = self.set_walls() self.food = self.set_food() self.player = (1, 1) # change to player class once created def set_walls(self): walls = set() # set boarder walls for x in range(8): walls.add((0, x)) walls.add((7, x)) walls.add((x, 0)) walls.add((x, 7)) # add obstical walls.add((3, 3)) walls.add((4, 3)) walls.add((4, 4)) walls.add((4, 5)) return walls def get_walls(self): return self.walls def set_food(self): food = set() for i in range(5): pos = (random.randint(0, 7), random.randint(0, 7)) if pos not in self.walls: food.add(pos) return food def get_food(self): return self.food def has_food(self): if len(self.food) > 0: return True else: return False def display_walls(self): wall_colour = (255, 255, 255) for pos in self.walls: self.sense.set_pixel(pos[0], pos[1], wall_colour) def display_food(self): food_colour = (0, 0, 255) for pos in self.food: self.sense.set_pixel(pos[0], pos[1], food_colour) def clear_display(self): self.sense.clear() def display_board(self): self.display_walls() self.display_food()
def __init__(self): sense = SenseHat() x = 0 y = 0 w = white b = black d = dark_blue B = blue o = orange aquariem = [ [d, d, d, d, d, d, d, d], [d, d, d, d, d, d, d, d], [d, d, d, d, d, d, d, d], [d, d, d, d, d, d, d, d], [d, d, d, d, d, d, d, d], [d, d, d, d, d, d, d, d], [d, d, d, d, d, d, d, d], [d, d, d, d, d, d, d, d] ] sense = GridSenseHat() sense.set_pixels(aquariem) sense.set_pixel(0,0,255,255,255)
class ReadAndDisplay(): def __init__(self): self.sense = SenseHat() self.dataCount = self.countCurrentRowNum() self.api = api() def countCurrentRowNum(self): conn = sqlite3.connect(c.dbname) curs = conn.cursor() count = len(curs.fetchall()) conn.close() return count # Displays a single digit (0-9) def showDigit(self, val, xd, yd, r, g, b): offset = val * 15 for p in range(offset, offset + 15): xt = p % 3 yt = (p - offset) // 3 self.sense.set_pixel(xt + xd, yt + yd, r * c.nums[p], g * c.nums[p], b * c.nums[p]) # Displays a two-digits positive number (0-99) def showNumber(self, val, r, g, b): abs_val = abs(val) tens = abs_val // 10 units = abs_val % 10 if (abs_val > 9): self.showDigit(tens, c.offset_left, c.offset_top, r, g, b) self.showDigit(units, c.offset_left + 4, c.offset_top, r, g, b) def displayTemparature(self): data = json.loads(self.api.getLastData()) temp = int(round(data[2])) # set color r, g, b = c.g if (temp > c.max): r, g, b = c.r elif (temp < c.min): r, g, b = c.b if (temp > 99): temp = 99 #display self.showNumber(temp, r, g, b) def execute(self): self.sense.clear() self.displayTemparature() while True: currentCount = self.countCurrentRowNum() if currentCount > self.dataCount: # update the display if there's a new record detected self.displayTemparature() self.dataCount = currentCount # update global row count time.sleep(c.update_interval) self.sense.clear()
def set_color(payload): sense = SenseHat() message = payload.decode('utf-8') new_color = json.loads(message).get("color") color_dict = {'red': (255, 0, 0), 'green': (0, 255, 0), 'none': (0, 0, 0)} for i in range(8): for j in range(8): sense.set_pixel(i, j, color_dict.get(new_color))
def pixel(x,y): # create random colors for each pixel red = randomizer() green = randomizer() blue = randomizer() hat = SenseHat() # if you want a single color set the rgb components in the color variable color = (red, green, blue) hat.set_pixel(x, y, color)
class SensehatDisplayAdapter(DisplayAdapter): ADAPTER_TITLE = "SensehatDisplayAdapter" ADAPTER_TYPE = AdapterTypes.display def __init__(self): self._sensehat = SenseHat() self._maze = inject(DIContainerKeys.maze, Maze) self._sensehat.low_light = True def call(self, args, kwargs): action = args[0] action_data = args[1] if action == DisplayAdapterCalls.clear: self._clear() elif action == DisplayAdapterCalls.show_text: self._show_text(action_data) elif action == DisplayAdapterCalls.show_maze: self._show_maze(action_data) def _clear(self): self._sensehat.clear() def _show_text(self, text): raise NotImplementedError def _show_maze(self, layout): layout = self._maze.render() if not(len(layout) == 8 and len(layout[0]) == 8): display_center = self._maze.character_coords display_start_delta = { "x": display_center["x"] - 8, "y": display_center["y"] - 8 } else: display_start_delta = { "x": 0, "y": 0 } for row_count, row in enumerate(layout): for pixel_count, pixel in enumerate(row): if row_count >= display_start_delta["x"] and \ pixel_count >= display_start_delta["y"]: if pixel == "O": pixel_color = (0, 0, 0) elif pixel == "X": pixel_color = (190, 190, 190) elif pixel == "A": pixel_color = (0, 255, 0) elif pixel == "B": pixel_color = (0, 0, 255) else: pixel_color = (0, 0, 0) self._sensehat.set_pixel(row_count - display_start_delta["x"], pixel_count - display_start_delta["y"], pixel_color)
class SenseDisplay: """Interacts with the LED display on the Raspberry Pi Sense HAT Methods for displaying direction pixels and moon phase images, as well as clearing the display. """ size = 8 on_color = (0, 0, 255) # blue def __init__(self): self.sense = SenseHat() def display_direction(self, degrees=0): """Take the cardinal direction in degrees and light up a pixel in that direction.""" # Hard code North, as magnetometer calibration didn't work. # TODO: Adjust direction to the current orientation of the HAT # using sense.get_compass() and calibrating with RTIMULibCal north = 0 adjusted_degrees = 180 - (int(degrees) + north) % 360 radians = math.radians(adjusted_degrees) # Pretend there's a circle on the grid, and light up the LED on the edge # of the circle in the direction we want to "point" to. x = math.floor( math.sin(radians) * (self.size / 2 - 0.001) + self.size / 2) y = math.floor( math.cos(radians) * (self.size / 2 - 0.001) + self.size / 2) self.sense.clear() self.sense.set_pixel(int(x), int(y), self.on_color) def display_moon_phase(self, phase_info): """Display an image of the moon at the given phase.""" (trend, _, illumination) = phase_info percent = round(illumination * 10) * 10 if percent == 100: img_fname = "full100.png" elif percent == 0: img_fname = "new0.png" else: img_fname = "%s%s.png" % (trend, percent) # The full white is too bright self.sense.low_light = True self.sense.load_image("phase-images/%s" % img_fname) def clear_display(self): """Turn off all of the LEDs off the display""" self.sense.clear()
def blinkMove(x, y, tile): sense = SenseHat() if tile == 'X': r, g, b = X else: r, g, b = O for blinks in range(3): sense.set_pixel(x, y, r, g, b) msleep(500) sense.set_pixel(x, y, 0, 0, 0) msleep(500)
def main(): """Test function to display all available colors.""" sense = SenseHat() colors = (BLACK, LEMON, PINK, RED, MINT, BLUE, GREEN, MAGENTA, CYAN, YELLOW, ORANGE, GRAY, CORAIL, BORDEAU, WHITE) n = len(colors) print(n, 'colors') for x in range(8): for y in range(8): (r, g, b) = colors[(y * 8 + x) % n] sense.set_pixel(x, y, r, g, b)
def main(v): if v is None: v=0.5 else: v=float(v) sense=SenseHat() for i in range(8): for j in range(8): (h,s,v)=XY_to_HSV(i,j,v) (r,g,b)=HSV_to_RGB(h,s,v) #print (i,j,int(r),int(g),int(b),int(h),int(s),int(v)) sense.set_pixel(i,j,int(r),int(g),int(b))
def uploadSensorValues(): global sensorData, data_send_last, data_temp, data_temp_array_index, data_temp_index, data_send_flag send_target_index = 0 # 次に出力するバッファ番号 url = 'http://192.168.30.110:3000' # url = 'http://133.19.62.11:9200/hakuba_sencing_info_3/a' # url = 'http://192.168.100.121:20000/mnt/data/sensor1/' sense = SenseHat() while True: if (data_send_last < DATA_TEMP_ARRAY_MAX - 1): send_target_index = data_send_last + 1 else: send_target_index = 0 if (data_send_flag[send_target_index] == True): print(send_target_index) outdatatmp = data_temp[0] print(outdatatmp) # サーバへの送信 stime = time.time() response = None sensdsucess = False for i in range(1, CONNECTION_RETRY + 1): try: response = requests.post(url, json=outdatatmp, timeout=(2.0, 8.0)) except Exception as e: print("サーバ送信エラー" + str(e) + " retry:{i}/{max}:wait{w}s".format( i=i, max=CONNECTION_RETRY, w=i * 5)) time.sleep(i * 5) else: sendsucess = True print("SEND_SUCCES") break if (sendsucess): # print(response.status_code) print(response.content) # デバック用(送信できたらLEDが光る) sense.clear() sense.set_pixel(0, 0, [0, 0, 255]) else: print("送信失敗、データは破棄されます") etime = time.time() print("送信にかかった時間:" + str(etime - stime)) data_send_flag[send_target_index] = False data_send_last = send_target_index time.sleep(0.1)
def sayIt(): sense = SenseHat() x = 0 y = 0 while x < 8: while y < 8 : sense.set_pixel(x, y, (randint(0,255), randint(0,255), randint(0,255))) y+= 1 sleep(0.1) sense.clear() x += 1 y = 0 sayIt()
def move(self,sense): sense = SenseHat() x = 0 y = 0 while True: while(x<8): time.sleep(1) sense.set_pixel(0,0,0,0,255) x = x+1 else: while(0<x): time.sleep(1) sense.set_pixel(0,0,0,0,255) x = x-1
def main(): sense = SenseHat() try: while True: x = randint(0, 7) y = randint(0, 7) r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) sense.set_pixel(x, y, r, g, b) sleep(0.001) except KeyboardInterrupt: print("Exiting...") finally: sense.clear()
def main(): sense = SenseHat() color = (255, 0, 0) prev_x = -1 prev_y = -1 while True: acc = sense.get_accelerometer_raw() x = round(limit(-10 * acc['x'] + 3)) y = round(limit(-10 * acc['y'] + 3)) if x != prev_x or y != prev_y: sense.clear() sense.set_pixel(x, y, *color) prev_x = x prev_y = y time.sleep(0.08)
class MyApp(QMainWindow): def __init__(self): super().__init__() loadUi("hi.ui", self) self.main() def main(self): self.sense = SenseHat() def go(self): #self.sense.show_message(self.lineEdit.text()) for y in range(8): for x in range(8): self.sense.set_pixel(x, y, 200, 192, 188) sleep(0.1) self.sense.clear()
class SensehatScanner: worker = None logger = None sense = None repeated_timer_inst = None def start(self, logger): self.logger = logger self.repeated_timer_inst = RepeatedTimer(5, self.log_scan) self.worker = threading.Thread(target=self.start_continous_scan) self.sense = SenseHat() self.worker.do_run = True self.worker.start() self.repeated_timer_inst.start() def stop(self): self.logger = None self.repeated_timer_inst.stop() self.worker.do_run = False self.worker.join() def log_scan(self): self.logger.log_gyro(time.time(), self.orientation['yaw'], self.orientation['pitch'], self.orientation['roll']) def start_continous_scan(self): print 'starting continous sensehat scan' yaw = 0 while True: if (not getattr(self.worker, "do_run", True)): break gyro_only = self.sense.get_gyroscope() self.sense.set_pixel(0, int(yaw / 45), 0, 0, 0) self.orientation = self.sense.get_orientation_degrees() yaw = self.orientation['yaw'] # print yaw self.logger.log_gyro_raw(time.time(), self.orientation['yaw'], self.orientation['pitch'], self.orientation['roll']) self.sense.set_pixel(0, int(yaw / 45), 0, 255, 0) #accel_only = self.sense.get_accelerometer() #print("get_accelerometer p: {pitch}, r: {roll}, y: {yaw}".format(**accel_only)) print 'stopped continous self.sensehat scan'
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()
class SenseHATRenderer(AbstractRenderer): def __init__(self): super(AbstractRenderer,self).__init__() os.environ['SDL_VIDEODRIVER'] = 'dummy' pygame.init() pygame.display.set_mode((1,1)) self.sense = SenseHat() def render(self, cells): print "Rendering cells" for x in range(0, COLS): for y in range(0, ROWS): colour = cells[x][y].colour r = colour[0] g = colour[1] b = colour[2] self.sense.set_pixel(x, y, (r, g, b))
class MyColorDialog(QtGui.QColorDialog): def __init__(self, *args, **kwargs): super(MyColorDialog, self).__init__(*args, **kwargs) self.currentColorChanged.connect(self.color_changed) self.sense = SenseHat() self.init_lcd() def color_changed(self, color): t_RGBA = color.getRgb() # (r, g, b, a) t_RGB = t_RGBA[0:3] for x in range(8): for y in range(8): self.sense.set_pixel(x, y, *t_RGB) def init_lcd(self): for x in range(8): for y in range(8): self.sense.set_pixel(x, y, 255, 255, 255)
class HatPen: def __init__(self): from sense_hat import SenseHat self.hat = SenseHat() self.hat.clear() self.cursor_pos = (0, 0) self.cursor_color = HSBColor() self.display = HSBDisplay() def apply(self): x, y = self.cursor_pos self.display.set_pixel(x, y, self.cursor_color) def draw(self): self.display.draw(self.hat) def draw_cursor(self): x, y = self.cursor_pos self.hat.set_pixel(x, y, self.cursor_color.rgb())
def test_plan_move(): s = SenseHat() s.clear() s.stick.direction_up = forward s.stick.direction_down = back s.stick.direction_left = left s.stick.direction_right = right mode = 0 # plan spf = 1 while not escaped: #print('pos',pos, 'dir',dir) if mode==0: display_plan(s) elif mode==1: display_3d(s) time.sleep(spf) if mode==0: s.set_pixel(0, 7, green)
class Agent(): def __init__(self, board, colour, position): self.board = board self.position = position self.colour = colour self.sense = SenseHat() self.sense.low_light = True def get_position(self): return self.position def get_position_as_list(self): return list(self.position) def remove_pos(self): self.sense.set_pixel(self.position[0], self.position[1], (0, 0, 0)) def valid_move(self): return False def get_move(self): return None
def runCompass(): led_loop = [4, 5, 6, 7, 15, 23, 31, 39, 47, 55, 63, 62, 61, 60, 59, 58, 57, 56, 48, 40, 32, 24, 16, 8, 0, 1, 2, 3] sense = SenseHat() sense.set_rotation(0) sense.clear() prev_x = 0 prev_y = 0 led_degree_ratio = len(led_loop) / 360.0 elapsed = time.time() futureTime = time.time() + 60 #run the compass for 1 minute while elapsed < futureTime: elapsed = time.time() try: dir = sense.get_compass() dir_inverted = 360 - dir # So LED appears to follow North led_index = int(led_degree_ratio * dir_inverted) offset = led_loop[led_index] y = offset // 8 # row x = offset % 8 # column if x != prev_x or y != prev_y: sense.set_pixel(prev_x, prev_y, 0, 0, 0) sense.set_pixel(x, y, 0, 0, 255) prev_x = x prev_y = y except (KeyboardInterrupt): sense.clear() sys.exit(0) sense.clear()
class Screen: def __init__(self): self.sense = SenseHat() self.general_level = 0 self.wait_time = 4 self.cur_time = 0 self.clear() self.balance = 0 def clear(self): for i in range(SIZE): for j in range(SIZE): self.sense.set_pixel(i, j, BLACK) def clear_col(self, x): for i in range(0, 7): self.sense.set_pixel(x, i, BLACK) def plot_bar(self, x, height, colors=None): if colors is None: colors = BAR_COLORS self.clear_col(x) for i in range(height): self.sense.set_pixel(x, 7 - i, colors[7 - i]) def plot_balance(self): for i in range(SIZE): self.plot_bar(i, max(1, self.general_level), BAR_COLORS) def show_amount(self): self.show_message(str(self.balance), color=list(BAR_COLORS[min(7, 8 - self.general_level)])) def show_message(self, message, speed=0.1, color=[255, 255, 255]): self.sense.show_message(message, speed, color) self.plot_balance() """ Parses an input in the form: balance percentage """ def parse_input(self, line): self.cur_time = 0 # Split balance and percentage. [self.balance, percent] = [float(x) for x in line.split()] self.general_level = int(round(min(max(0, percent), 100) / 100.0 * SIZE)) self.draw_check() def draw_check(self): types = [BLACK, GREEN] pixels = [types[CHECK[i / SIZE][i % SIZE]] for i in range(SIZE * SIZE)] self.sense.set_pixels(pixels) def no_text(self): self.cur_time += SLEEP_TIME if self.cur_time > self.wait_time: self.cur_time = 0 self.show_amount()
def generate_chart(data, color, ripple, orientation, lowlight): info_chart = [] domain_min = data[0][0] domain_max = data[0][0] ad_min = data[0][1] ad_max = data[0][1] #calculate minimum, maximum, and interval values to scale graph appropriately for hour in data: if hour[0] > domain_max: domain_max = hour[0] elif hour[0] < domain_min: domain_min = hour[0] if hour[1] > ad_max: ad_max = hour[1] elif hour[1] < ad_min: ad_min = hour[1] domain_interval = (domain_max - domain_min) / 8 ad_interval = (ad_max - ad_min) / 8 #append scaled values to new list for hour in data: info_chart.append([int((hour[0] - domain_min) / domain_interval) if domain_interval > 0 \ else 0, int((hour[1] - ad_min) / ad_interval) if ad_interval > 0 else 0]) info_chart = list(reversed(info_chart[:8])) sense = SenseHat() sense.clear() sense.set_rotation(orientation) if lowlight: sense.low_light = True else: sense.low_light = False #set pixel values on rgb display for row in range(0, 8): if info_chart[row][0] > 0: for col in range(0, info_chart[row][0]): #if color not set, default to red for all values if color == 'traffic': sense.set_pixel(row, 7 - col, color_dict(info_chart[row][0])) if ripple: time.sleep(0.01) elif color == 'ads': sense.set_pixel(row, 7 - col, color_dict(info_chart[row][1])) if ripple: time.sleep(0.01) else: sense.set_pixel(row, 7 - col, (255, 0, 0)) if ripple: time.sleep(0.01)
class VideoLogger(object): # Kameraparameter definieren def __init__(self): delimiter=';' quotechar='"' quoting=csv.QUOTE_MINIMAL self.camera = PiCamera() self.camera.resolution = (1280, 720) self.camera.framerate = 30 self.sense = SenseHat() log_headings = ['Zeit','Fehler'] with open('video_log.csv', 'w') as file: writer = csv.writer(file, delimiter=delimiter, quotechar=quotechar, quoting=quoting) writer.writerow(log_headings) self.sense.set_pixel(6, 7, BLACK) self.sense.set_pixel(7, 7, BLACK) # Aufnahme als Datei schreiben def write_data_to_file(self, data, file_name, mode='a', delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL): with open(file_name, mode=mode) as file: writer = csv.writer(file, delimiter=delimiter, quotechar=quotechar, quoting=quoting) for row in data: writer.writerow(row) # Filmvorgang starten def start_filming(self): while True: self.camera.start_recording('/home/pi/pi-strato-flight/videos/video' + str(datetime.datetime.now()) + '.h264') self.sense.set_pixel(7, 7, GREEN) print('starting') self.camera.wait_recording(600) self.camera.stop_recording() self.sense.set_pixel(7, 7, BLACK) # Fehlerbehandlung definieren def log_exception(self, exception): print(str(exception)) self.sense.set_pixel(6, 7, RED) row = [] row.append([str(datetime.datetime.now()), str(exception)]) self.write_data_to_file(row, 'video_log.csv')
class MyDriver: def __init__(self, revpi_address: str, virtual_device: str): self.hat = SenseHat() self.px_connected = [(0, 0)] self.px_running = [(2, 0)] self.px_error = [(7, 0)] self.px_center = [(i, 4) for i in range(8)] self.px_left3 = [(i, 1) for i in range(8)] self.px_left2 = [(i, 2) for i in range(8)] self.px_left1 = [(i, 3) for i in range(8)] self.px_right1 = [(i, 5) for i in range(8)] self.px_right2 = [(i, 6) for i in range(8)] self.px_right3 = [(i, 7) for i in range(8)] self.mrk_pos = None # Connect to RevPiModIO self.rpi = RevPiNetIODriver( revpi_address, virtual_device, autorefresh=True, monitoring=True, replace_io_file=":network:", ) self.rpi.handlesignalend(self.stop) def _set_px(self, pixels: list, color: PixelColor): """Global function to set a pixel map.""" for pixel in pixels: self.hat.set_pixel(*pixel, color.value) def on_load_pos(self, name: str, value: int): if not self.rpi.io.program_running.value: return if self.rpi.io.forklift.value: status = True pos_px = None if self.rpi.io.more_left: status = False if value < 2000: pos_px = self.px_right1 elif value < 4000: pos_px = self.px_right2 else: pos_px = self.px_right3 if self.rpi.io.more_right: status = False print(value) if value < -4000: pos_px = self.px_left3 elif value < -2000: pos_px = self.px_left2 else: pos_px = self.px_left1 if self.mrk_pos != pos_px: # Switch off old pixel if self.mrk_pos: self._set_px(self.mrk_pos, PixelColor.BLACK) # Switch on new pixel if pos_px: self._set_px(pos_px, PixelColor.RED) self.mrk_pos = pos_px # Show center line self._set_px( self.px_center, PixelColor.GREEN if status else PixelColor.BLUE ) else: self._set_px(self.px_center, PixelColor.BLACK) if self.mrk_pos: self._set_px(self.mrk_pos, PixelColor.BLACK) def on_program_running(self, name, value): self._set_px(self.px_running, PixelColor.GREEN if value else PixelColor.YELLOW) def start(self): self.rpi.io.program_running.reg_event(self.on_program_running, prefire=True) self.rpi.io.load_pos.reg_event(self.on_load_pos, prefire=True) self.rpi.mainloop(blocking=False) while not self.rpi.exitsignal.wait(0.2): self._set_px( self.px_connected, PixelColor.RED if self.rpi.reconnecting else PixelColor.GREEN ) # Check for errors if self.rpi.ioerrors > 0: self.rpi.resetioerrors() self._set_px(self.px_error, PixelColor.RED) else: self._set_px(self.px_error, PixelColor.GREEN) self.hat.clear() self.rpi.disconnect() def stop(self): self.rpi.setdefaultvalues()
global y return matrix[y][x] == green or y == 7 def gravity(): global y y += 1 # Main ------------------------------ sense.stick.direction_any = drawAstronaut while not gameOver: matrix = genPipes(matrix) if checkCollision(matrix): gameOver = True for i in range(6): if (i % 2 == 0): matrix = movePipes(matrix) sense.set_pixels(flatten(matrix)) gravity() if checkCollision(matrix): gameOver = True break sense.set_pixel(x, y, yellow) sleep(0.5) score += 1 print("Score: " + str(score)) if score < 0: score = 0 sense.show_message("Score: " + str(score)) print("Score: " + str(score))
##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 elif event.direction == "left":
from sense_hat import SenseHat sense = SenseHat() #sense.set_pixel(0, 2, [0, 0, 255]) #sense.set_pixel(7, 4, [255, 0, 0]) sense.set_pixel(2, 2, [0, 0, 255]) sense.set_pixel(4, 2, [0, 0, 255]) sense.set_pixel(3, 4, [100, 0, 0]) sense.set_pixel(1, 5, [255, 0, 0]) sense.set_pixel(2, 6, [255, 0, 0]) sense.set_pixel(3, 6, [255, 0, 0]) sense.set_pixel(4, 6, [255, 0, 0]) sense.set_pixel(5, 5, [255, 0, 0])
import pygame import time import math pygame.init() pygame.display.set_mode((1, 1)) sense = SenseHat() white = (255, 255, 255) green = (0, 255, 0) yellow = (255, 255, 0) red = (255, 0, 0) sense.clear() sense.set_pixel(5, 5, white) sense.set_pixel(2, 5, green) sense.set_pixel(2, 3, yellow) sense.set_pixel(2, 1, red) y = 5 while True: for event in pygame.event.get(): if event.type == KEYDOWN: sense.set_pixel(5, y, 0, 0, 0) if event.key == K_DOWN and y < 5: y += 2 elif event.key == K_UP and y > 1: y -= 2 sense.set_pixel(5, y, 255, 255, 255)
class _SenseHat: def __init__(self, board_object, colour=""): self.board = board_object self.colour = colour self.sense = SenseHat() def magnetometer_on(self): self.sense.set_imu_config(True, False, False) # gyroscope only @property def temp_c(self): return (self.sense.get_temperature_from_humidity() + self.sense.get_temperature_from_pressure())/2 @property def pressure(self): return self.sense.pressure @property def humidity(self): return self.sense.humidity def led_all(self, colour): lcd = [] for i in range(0, 64): lcd.append(colour) self.sense.set_pixels(lcd) def led_1(self, colour): self.sense.set_pixel(0, 0, colour) self.sense.set_pixel(0, 1, colour) self.sense.set_pixel(1, 0, colour) self.sense.set_pixel(1, 1, colour) def led_2(self, colour): self.sense.set_pixel(2, 2, colour) self.sense.set_pixel(2, 3, colour) self.sense.set_pixel(3, 2, colour) self.sense.set_pixel(3, 3, colour) def led_3(self, colour): self.sense.set_pixel(4, 4, colour) self.sense.set_pixel(4, 5, colour) self.sense.set_pixel(5, 4, colour) self.sense.set_pixel(5, 5, colour) def led_4(self, colour): self.sense.set_pixel(6, 6, colour) self.sense.set_pixel(6, 7, colour) self.sense.set_pixel(7, 6, colour) self.sense.set_pixel(7, 7, colour) def clear(self): self.sense.clear()
from evdev import InputDevice, ecodes,list_devices from select import select from sense_hat import SenseHat devices = [InputDevice(fn) for fn in list_devices()] for dev in devices: if dev.name == "Raspberry Pi Sense HAT Joystick": js = dev sense = SenseHat() sense.clear() running = True px = 0 py = 0 sense.set_pixel(px, py, 255, 255, 255) while running: r, w, x = select([dev.fd], [], [],0.01) for fd in r: for event in dev.read(): if event.type == ecodes.EV_KEY and event.value == 1: sense.set_pixel(px, py, 0, 0, 0) # Black 0,0,0 means OFF if event.code == ecodes.KEY_UP and py > 0: print("up") py = py - 1 elif event.code == ecodes.KEY_LEFT and px > 0: print("left") px = px - 1 elif event.code == ecodes.KEY_RIGHT and px < 7:
sense.set_pixel(hmov[0], vmov[0], LED_COLOR) def moveUp(): global vmov sense.set_pixel(hmov[0], vmov[0], 0, 0, 0) vmov = vmov[-1:] + vmov[:-1] sense.set_pixel(hmov[0], vmov[0], LED_COLOR) def quit(): print('Exiting...') time.sleep(1) sense.clear() pygame.quit() sys.exit() sense.set_pixel(0, 0, 255, 0 , 0) atexit.register(goodbye, name='Emanuele') for event in eventIterator(): print(event) if event.type == QUIT: quit() elif event.type == KEYDOWN: if event.key == K_RETURN: print('ENTER') pygame.event.post(pygame.event.Event(QUIT)) if event.key == K_LEFT: print('LEFT') moveLeft() if event.key == K_RIGHT: print('RIGHT')
import random import time from sense_hat import SenseHat sense = SenseHat() while True: x = random.randint(0, 7) y = random.randint(0, 7) r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) sense.set_pixel(x, y, r, g, b) time.sleep(0.01) sense.clear()
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: count=0 #sense.show_message("*",scroll_speed=0.05) tmp_res = json.loads(getData("http://localhost:9090/cmd","select count(*) from collect")) now_count = str(tmp_res['Content']['content']) sense.show_message( now_count[2:-2] + " rows", scroll_speed=0.05) sense.load_image("logo8.png") sense.set_pixel(7, 6, 20*(count%10)+50, 110, 20*(count%10)+50) sense.set_pixel(7, 7, 20*(count%10)+50, 110, 20*(count%10)+50) sense.set_pixel(6, 6, 20*(count%10)+50, 110, 20*(count%10)+50) sense.set_pixel(6, 7, 20*(count%10)+50, 110, 20*(count%10)+50) humidity = sense.get_humidity() temp = sense.get_temperature() pressure = sense.get_pressure() orientation = sense.get_orientation_degrees() pitch = orientation['pitch'] roll = orientation['roll'] yaw = orientation['yaw'] acceleration = sense.get_accelerometer_raw() acc_x = acceleration['x'] acc_y = acceleration['y']
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)
class GusanoJ1: sense = 0 gusano = -1 running = True white = (0,0,0) red = (255,0,0) comida = Point(-1,-1) def __init__(self): self.sense = SenseHat() self.sense.clear() self.white = (255,255,255) point1 = Point(0,0) point2 = Point(0,1) point3 = Point(0,2) self.gusano = [point3,point2,point1] def run(self): x = 0 y = 2 print self.gusano self.paintGusano() stick=SenseStick() xAnt = x yAnt = y-1 while self.running: for event in stick: #Genera comida if self.comidaDisponible() == False: self.comida = self.generaComida() self.paintComida() if event.state == stick.STATE_PRESS: #sense.set_pixel(x, y, 0, 0, 0) # Black 0,0,0 means OFF update = False if event.key == stick.KEY_DOWN and y < 7: y = y + 1 update=True elif event.key == stick.KEY_UP and y > 0: y = y - 1 update=True elif event.key == stick.KEY_RIGHT and x < 7: x = x + 1 update=True elif event.key == stick.KEY_LEFT and x > 0: x = x - 1 update=True pointTemp = Point(x,y) print '----- Posicion' print pointTemp.x print pointTemp.y print '-----EndPosicion' if update == True and self.ifExistPoint(self.gusano,pointTemp) == False: print 'Evento------' self.sense.clear() #Puede Comer? if pointTemp.x == self.comida.x and pointTemp.y == self.comida.y: self.gusano = self.addGusano(self.gusano,pointTemp) self.limpiaComida() self.sense.clear() self.paintGusano() else: self.gusano = self.updateGusano(self.gusano,pointTemp) print '____________________________________________' #self.comiendo(pointTemp) self.paintGusano() time.sleep(0.15) def paintComida(self): colorComida = (0,254,0) self.sense.set_pixel(self.comida.x,self.comida.y,colorComida) def limpiaComida(self): colorComida = (0,0,0) self.sense.set_pixel(self.comida.x,self.comida.y,colorComida) self.comida=Point(-1,-1) def paintGusano(self): print 'Imprimiendo gusano %d' %len(self.gusano) #max = len(self.gusano)-1 for i in range(len(self.gusano)): color=self.white point = self.gusano[i] print '**************' print point.x print point.y print '**************' if i == 0: color=self.red else: color=self.white self.sense.set_pixel(point.x,point.y,color) def ifExistPoint(self,gusano,pointX): for i in range(len(gusano)): point = gusano[i] if point.x == pointX.x and point.y == pointX.y: return True return False def updateGusano(self,gusano,bloque): print 'Update Gusano' print bloque.x print bloque.y count = len(gusano)-1 lstNuevoGusano = range(len(gusano)) #Recorre el gusano antiguo y lo pone en el nuevo pero descartando #la ultima posicion while count > 0 : lstNuevoGusano[count] = gusano[count-1] count = count - 1 lstNuevoGusano[0] = bloque return lstNuevoGusano def addGusano(self,gusano,bloque): print 'Gusano Comiendo' print bloque print bloque.x print bloque.y print 'Inicia Comida' count = 0 lstNuevoGusanoNew = range(len(gusano)+1) max = len(gusano) i = 0 while i <= max: if i == 0: lstNuevoGusanoNew[i]=bloque else: lstNuevoGusanoNew[i]=gusano[count] count=count+1 i=i+1 return lstNuevoGusanoNew def comiendo(self,bloque): if bloque.x == self.comida.x and bloque.y == self.comida.y: self.gusano = self.addGusano(self.gusano,bloque) self.limpiaComida() self.sense.clear() self.paintGusano() def comidaDisponible(self): result=False if self.comida.x == -1 and self.comida.y == -1: result = False else: result=True return result def generaComida(self): bandera = True comindaX = Point(-1,-1) while bandera: comindaX = Point(randint(0,7),randint(0,7)) bandera = self.ifExistPoint(self.gusano,comindaX) return comindaX def clcCambioDireccion(self,coordenada,coordenadaAnt): result = coordenadaAnt - coordenada if result == 0: return coordenada elif result > 0: coordenada = coordenada+1 elif result < 0: coordenada = coordenada-1 return coordenada
running = True # start daywatch as seperate thread DayWatchThread = threading.Thread(target=DayWatch) DayWatchThread.start() setDay() pos = (x1 - x/2) +8*y/2 print(x,y,pos) # set starting position for red LED cursor if x == 0 and y != 0: y = y+1 new_y = y sh.set_pixel(x, y, 255, 0,0) sh.set_pixel(x1, y, 255, 0,0) while running: # get all key presses for event in pygame.event.get(): if event.type == KEYDOWN: pos = (x1 - x/2) +8*y/2 print('pos: '+ str(pos) + ' x: ' + str(x) + ' y: ' + str(y)) # cursor navigation if event.key == K_DOWN and y < 7: new_y = y + 1 elif event.key == K_UP and y > 0:
# hello.py from time import sleep from sense_hat import SenseHat sense = SenseHat() sense.set_rotation(0) sense.show_message("Hello, world!",scroll_speed=0.05, text_colour=[255,255,50], back_colour=[0,0,50]) sleep(2) sense.clear() sense.set_pixel(0,0,[255,0,0]) sense.set_pixel(0,1,[0,255,0]) sleep(2) sense.clear() t=sense.get_temperature() # celcius p=sense.get_pressure() # millibars h=sense.get_humidity() # percent msg = "Temp: {0}, Press: {1}, Humid: {2}".format(round(t,1),round(p),round(h)) sense.show_message(msg) # eof
sense.show_letter("F", text_colour=[255, 0, 0]) time.sleep(1) sense.show_letter("+", text_colour=[0, 255, 0]) time.sleep(1) sense.show_letter("M", text_colour=[0, 0, 255]) time.sleep(1) a = 0 while a < 3: a = a + 1 z = random.randint(0, 255) y = random.randint(0, 255) x = random.randint(0, 255) sense.show_message("Bunt", scroll_speed=0.05, text_colour=[z, y, x]) sense.set_pixel(1, 1, [255, 0, 0]) sense.set_pixel(6, 6, [0, 0, 255]) time.sleep(1) r = [255, 0, 0] g = [0, 255, 0] b = [0, 0, 255] image = [ r, g, g, r, r, g, g,
class AstroPiSnake(): UP = 0 DOWN = 1 RIGHT = 2 LEFT = 3 BACKCOL = [0, 0, 0] SNAKECOL = [0, 0, 155] APPLECOL = [0, 155, 0] def __init__(self): pygame.init() pygame.display.set_mode((640, 480)) self.ap = SenseHat() def startGame(self): self.ap.clear(self.BACKCOL) self.direction = self.UP self.length = 3 self.tail = [] self.tail.insert(0, [4, 4]) self.createApple() self.score = 0 playing = True while(playing): sleep(0.5) for event in pygame.event.get(): if event.type == KEYDOWN: self._handle_event(event) playing = self.move() self.ap.clear() def _handle_event(self, event): if event.key == pygame.K_DOWN: self.down() elif event.key == pygame.K_UP: self.up() elif event.key == pygame.K_LEFT: self.left() elif event.key == pygame.K_RIGHT: self.right() def createApple(self): badApple = True #try and fnd a location for the apple while(badApple): x = randint(0, 7) y = randint(0, 7) badApple = self.checkCollision(x, y) self.apple = [x, y] self.ap.set_pixel(x, y, self.APPLECOL) def checkCollision(self, x, y): #is this outside the screen if x > 7 or x < 0 or y > 7 or y < 0: return True else: #or in the snakes tail for segment in self.tail: if segment[0] == x and segment[1] == y: return True else: return False def addSegment(self, x, y): #create the new segment of the snake self.ap.set_pixel(x, y, self.SNAKECOL) self.tail.insert(0, [x, y]) #do I need to clear a segment if len(self.tail) > self.length: lastSegment = self.tail[-1] self.ap.set_pixel(lastSegment[0], lastSegment[1], self.BACKCOL) self.tail.pop() def move(self): #work out where the new segment of the snake will be newSegment = [self.tail[0][0], self.tail[0][1]] if self.direction == self.UP: newSegment[1] -= 1 elif self.direction == self.DOWN: newSegment[1] += 1 elif self.direction == self.LEFT: newSegment[0] -= 1 elif self.direction == self.RIGHT: newSegment[0] += 1 if self.checkCollision(newSegment[0], newSegment[1]): #game over snakehead = self.tail[0] for flashHead in range(0,5): self.ap.set_pixel(snakehead[0], snakehead[1], self.SNAKECOL) sleep(0.2) self.ap.set_pixel(snakehead[0], snakehead[1], self.BACKCOL) sleep(0.2) self.ap.show_message("Score = {}".format(self.score), text_colour = self.APPLECOL) else: self.addSegment(newSegment[0], newSegment[1]) #has the snake eaten the apple? if newSegment[0] == self.apple[0] and newSegment[1] == self.apple[1]: self.length += 1 self.score += 10 self.createApple() return True def up(self): if self.direction != self.DOWN: self.direction = self.UP def down(self): if self.direction != self.UP: self.direction = self.DOWN def left(self): if self.direction != self.RIGHT: self.direction = self.LEFT def right(self): if self.direction != self.LEFT: self.direction = self.RIGHT
from sense_hat import SenseHat sense = SenseHat() sense.set_pixel(2, 2, [0,0,255]) sense.set_pixel(4, 2, [0,0,255]) sense.set_pixel(3, 4, [100,0,0]) sense.set_pixel(1, 5, [255,0,0]) sense.set_pixel(2, 6, [255,0,0]) sense.set_pixel(3, 6, [255,0,0]) sense.set_pixel(4, 6, [255,0,0]) sense.set_pixel(5, 5, [255,0,0])
import time from sense_hat import SenseHat X = (255, 0, 0) O = (255, 255, 255) question_mark = [ O, O, O, X, X, O, O, O, O, O, X, O, O, X, O, O, O, O, O, O, O, X, O, O, O, O, O, O, X, O, O, O, O, O, O, X, O, O, O, O, O, O, O, X, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, X, O, O, O, O ] sense = SenseHat() sense.set_pixels(question_mark) sense.set_pixel(0, 0, 255, 0, 0) sense.set_pixel(0, 7, 0, 255, 0) sense.set_pixel(7, 0, 0, 0, 255) sense.set_pixel(7, 7, 255, 0, 255) while True: for r in [0, 90, 180, 270]: sense.set_rotation(r) time.sleep(0.3)
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)
from sense_hat import SenseHat sense = SenseHat() sense.clear() edge = [0, 1, 2, 3, 4, 5, 6, 7, 15, 23, 31, 39, 47, 55, 63, 62, 61, 60, 59, 58, 57, 56, 48, 40, 32, 24, 16, 8] length = len(edge) ratio = length / 360.0 while True: o = sense.get_orientation() pitch = o["pitch"] roll = o["roll"] yaw = o["yaw"] yaw_list_position = int(yaw * ratio) yaw_pixel_number = edge[yaw_list_position] y = yaw_pixel_number // 8 x = yaw_pixel_number % 8 sense.set_pixel(x, y, 255, 255, 255)
# The calibration program will produce the file RTIMULib.ini # Copy it into the same folder as your Python code led_loop = [4, 5, 6, 7, 15, 23, 31, 39, 47, 55, 63, 62, 61, 60, 59, 58, 57, 56, 48, 40, 32, 24, 16, 8, 0, 1, 2, 3] sense = SenseHat() sense.set_rotation(0) sense.clear() prev_x = 0 prev_y = 0 led_degree_ratio = len(led_loop) / 360.0 while True: dir = sense.get_compass() dir_inverted = 360 - dir # So LED appears to follow North led_index = int(led_degree_ratio * dir_inverted) offset = led_loop[led_index] y = offset // 8 # row x = offset % 8 # column if x != prev_x or y != prev_y: sense.set_pixel(prev_x, prev_y, 0, 0, 0) sense.set_pixel(x, y, 0, 0, 255) prev_x = x prev_y = y
speed = -1 else: speed = +1 def collision(x,gap): if x == 3: if y < gap -1 or y > gap +1: return True return False columns = Thread(target=draw_columns) columns.start() shake = Thread(target=get_shake) shake.start() while not game_over: sense.set_pixel(3,y,BLUE) sleep(0.1) sense.set_pixel(3,y,BLACK) y += speed if y > 7: y = 7 if y < 0: y = 0 shake.join() columns.join() sense.show_message("You Lose", text_colour=(255,0,0))
blue = (0, 0, 255) darkblue = (0, 0, 139) red = (255, 0, 0) yellow = (255, 255, 0) green = (0, 255, 0) darkyellow = (216, 216, 0) sense = SenseHat() sense.clear() for light in lights: print('{} => {}'.format(light.id, light.to_dict())) lightstatus = light.get('Status') print(lightstatus) if light.id == 'light1' and light.get('Status') == false: sense.set_pixel(7, 2, darkyellow) elif light.id == 'light1' and light.get('Status') == true: sense.set_pixel(7, 2, yellow) if light.id == 'light2' and light.get('Status') == false: sense.set_pixel(7, 4, darkyellow) elif light.id == 'light2' and light.get('Status') == true: sense.set_pixel(7, 4, yellow) if light.id == 'light3' and light.get('Status') == false: sense.set_pixel(3, 2, darkyellow) elif light.id == 'light3' and light.get('Status') == true: sense.set_pixel(3, 2, yellow) if light.id == 'light4' and light.get('Status') == false: sense.set_pixel(3, 4, darkyellow) elif light.id == 'light4' and light.get('Status') == true: sense.set_pixel(3, 4, yellow) for socket in sockets:
class MClock: def __init__(self, radius=200, segments=9, dim=0.8, sleep=5.0): self.segments = segments self.image = Image.new('RGB', (RADIUS * 2, RADIUS * 2)) self.img = ImageDraw.Draw(self.image) self.display_credits = False self.seconds = True self.hat = SenseHat() self.radius = RADIUS self.dim = dim self.sleep = sleep self.recalc(self.radius*2, self.radius*2) def set_segments(self, *args): self.segments = max(self.segments, 2) def toggle_text(self, *args): self.showtext = not self.showtext def toggle_seconds(self, *args): self.seconds = not self.seconds def show_credits(self, *args): self.hat.show_message(self.credits) def quit(self, *args): self.running = False credits = ("M Clock 2.0\n" "by Johnny Gill\n" "after tkinter by Guido van Rossum\n" "after a design by Rob Juda") creditid = None showtext = False def recalc(self, width, height): radius = min(width, height) // 2 self.radius = radius self.bigsize = radius * .975 self.litsize = radius * .67 def run(self): self.running = True while self.running: t = time.time() hh, mm, ss = time.localtime(t)[3:6] self.draw(hh, mm, ss) self.blit() time.sleep(self.sleep) def blit(self): """ Update the image on the sense hat Need to downsample from RADIUS to 8 Let's just pick a pixel at random and see how that works """ size = self.radius // 4 for x in range(8): for y in range(8): xpos = size * x ypos = size * y pix = self.pixel_picker(xpos, ypos, size, size) self.hat.set_pixel(x, y, pix) def pick_pixel(self, xpos, ypos, xx, yy): rr = gg =bb = 0 for x in range(xx): for y in range(yy): r, g, b = self.image.getpixel((xpos + x, ypos + y)) rr += r gg += g bb += b count = xx * yy pix = (rr // count, gg // count, bb // count) return pix def weighted_pick_pixel(self, xpos, ypos, xx, yy): rr = gg =bb = 0 weight = 0 for x in range(xx): for y in range(yy): # Use Euclidean distance from centre as weight this_weight = (abs(x - xx/2)) ** 2 this_weight += (abs(y - yy/2)) ** 2 this_weight = this_weight ** 0.5 weight += this_weight r, g, b = self.image.getpixel((xpos + x, ypos + y)) rr += this_weight * r gg += this_weight * g bb += this_weight * b count = weight / self.dim pix = (int(rr // count), int(gg // count), int(bb // count)) return pix pixel_picker = weighted_pick_pixel def xpick_pixel(self, xpos, ypos, xx, yy): pickx = random.randint(0, xx-1) picky = random.randint(0, xx-1) pix = self.image.getpixel((xpos + pickx, ypos + picky)) return pix def get_angles(self, hh, mm, ss): # Set bigd, litd to angles in degrees for big, little hands # 12 => 90, 3 => 0, etc. secd = (90 - (ss * 60) / 10) % 360 bigd = (90 - (mm*60 + ss) / 10) % 360 litd = (90 - (hh*3600 + mm*60 + ss) / 120) % 360 return secd, bigd, litd def draw(self, hh, mm, ss, colors=(0, 1, 2)): radius = self.radius bigsize = self.bigsize litsize = self.litsize # Delete old items #self.hat.clear() secd, bigd, litd = self.get_angles(hh, mm, ss) # Set bigr, litr to the same values in radians bigr = radians(bigd) litr = radians(litd) # Draw the background colored arcs self.drawbg(bigd, litd, secd, colors) # Draw the hands self.draw_hands(bigr, litr) def draw_hands(self, bigr, litr, colour=(0,0,0), scale=1.0): # Draw the hands radius = self.radius bigsize = self.bigsize * scale litsize = self.litsize * scale img = self.img r, g, b = colour xcolour = (255-r, 255-g, 255-b) xcolour = (255, 0, 0) b = img.line([radius, radius, radius + int(bigsize*math.cos(bigr)), radius - int(bigsize*math.sin(bigr))], width=12, fill=xcolour) l = img.line([radius, radius, radius + int(bigsize*math.cos(litr)), radius - int(bigsize*math.sin(litr))], width=12, fill=colour) def drawbg(self, bigd, litd, secd, colors=(0, 1, 2)): # This is tricky. We have to simulate a white background with # three transparent discs in front of it; one disc is # stationary and the other two are attached to the big and # little hands, respectively. Each disc has 9 pie segments in # sucessive shades of pigment applied to it, ranging from # fully transparent to only allowing one of the three colors # Cyan, Magenta, Yellow through. if not self.seconds: secd = 90 img = self.img N = self.segments table = [] for angle, colorindex in [(bigd - 180/N, 0), (litd - 180/N, 1), (secd - 180/N, 2)]: angle %= 360 for i in range(N): color = 255 if colorindex in colors: color = (N-1-i)*color//(N-1) table.append((angle, color, colorindex)) angle += 360/N if angle >= 360: angle -= 360 table.append((0, color, colorindex)) table.sort() table.append((360, None)) radius = self.radius fill = [0, 0, 0] i = 0 for angle, color, colorindex in table[:-1]: fill[colorindex] = color if table[i+1][0] > angle: extent = table[i+1][0] - angle if extent < 1.: # XXX Work around a bug in Tk for very small angles # I think this bug is also present in appuifw extent = 1. #print([0, 0, 2 * radius, 2 * radius]) #print(type(2 * radius)) #print(fill) img.pieslice([0, 0, 2 * radius, 2 * radius], int(angle), int(extent+angle), fill=tuple(fill)) i+=1
by=4 diffV=1 X=[255,100,0] S=[0,0,0] field=[S]*64 while(True): orien = sense.get_orientation_degrees() pdiff=orien['pitch']-base_pitch rdiff=orien['roll']-base_roll print '{} {} {}'.format(orien['pitch'],base_pitch,pdiff) print '{} {} {}'.format(orien['roll'],base_roll,rdiff) #print '{} {}'.format(orien['yaw'],base_yaw) print'######################################' if(pdiff> diffV): if(bx>0): bx-=1 elif(pdiff < -diffV): if(bx<7): bx+=1 if(rdiff >diffV): if(by<7): by+=1 elif(rdiff < -diffV): if(by >0): by-=1 for i in range(0,63): field[i]=S sense.set_pixels(field) sense.set_pixel(bx,by,X) sleep(1)
sense.set_pixels(ironDesign) if block == lapis: mc.postToChat("Lapis-Lazuli") global lights lights = True if lights == True: sense.clear() x = randint(0, 7) y = randint(0, 7) r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) pixel = (r, g, b) sense.set_pixel(x, y, pixel) time.sleep(0.01) if choice == 4: print("To modify color please check code") message = raw_input() #Color Here sense.show_message(message,text_colour=[0,255,0]) if choice == 5: humidity = sense.get_humidity() print("Humidity: %s %%rH" % humidity) elif choice == 6: pressure = sense.get_pressure() print("Pressure: %s Millibars" % pressure)
x_sens = 1 y_sens = 1 rx = 0 ry = 0 ry_sens = 1 def afficheRaquette(): sense.set_pixel(rx, ry, 242, 62, 104) sense.set_pixel(rx, ry_sens, 242, 62, 104) sense.set_pixel(rx, ry_sens + 1, 242, 62, 104) sense.set_pixel(x, y, 66, 134, 244) while True: sense.clear(0, 0, 0) afficheRaquette() sense.set_pixel(x, y, 66, 134, 244) time.sleep(0.2) x = x + x_sens y = y + y_sens if x == 7: x_sens = -1 if y == 0: y_sens = 1
sense= SenseHat() sense.clear() #take in inputs number1 operation number2 print 'Welcome to MathFun!' number1=raw_input("Enter a number: ") operation=raw_input("Enter + or -: ") number2=raw_input("Enter another number: ") output=0 oper=0 if(str(operation) == str("+")): output=int(number1)+int(number2) oper=1 if(str(operation)==str("-")): output=int(number1)-int(number2) oper=2 Red=[255,0,0] #set row 1 for i in range(0,int(number1)): sense.set_pixel(0,i,Red) #set row 2 if(oper==1): sense.set_pixel(1,0,[23,235,87]) else: sense.set_pixel(1,0,[84,94,23]) for i in range(0,int(number2)): sense.set_pixel(2,i,Red) #setOutput sense.set_pixel(3,0,[23,23,235]) for i in range(0,int(output)): sense.set_pixel(4,i,Red)
blue = (0, 0, 50) yellow = (0, 50, 0) while True: acceleration = sense.get_accelerometer_raw() x = round(acceleration['x'], 3) y = round(acceleration['y'], 3) b1 = int(round(x * 255, 0)) b2 = int(round(y * 255, 0)) blue = (255, 255, 255) for x in range(0, 8): for y in range(0, 8): sense.set_pixel(x, y, (0, 0, 255)) time.sleep(0.050) # print(x) # print(y) sense.clear() for x in range(0, 255): for y in range(0, 255): sense.set_pixel(0, 0, (x, 0, y)) time.sleep(0.001) sense.clear() # sense.show_message("x".format(x), text_colour=yellow, back_colour=blue, scroll_speed=0.01)
#!/usr/bin/python import sys import time import random from sense_hat import SenseHat sense = SenseHat() x = int(sys.argv[1]) y = int(sys.argv[2]) r = int(sys.argv[3]) g = int(sys.argv[4]) b = int(sys.argv[5]) print x print y print r print g print b sense.set_pixel(x,y,[r,g,b])