def main(): """Main function for the timer""" # set the number minutes that your talk is to last for. minutes = 1 # convert to the delay needed to turn off each LED delay = minutes_to_delay(minutes) start_up_screen() show_power_on() radio.on() while True: received_message = radio.receive() delay_from_remote = message_to_delay(received_message) if delay_from_remote >= 0: delay = delay_from_remote count_down(delay) get_ready_to_go_again() # Show number of mins display_minutes(delay_to_minutes(delay)) # To enter demo mode press button a for > 2 secs if button_b.is_pressed(): start = running_time() while button_b.is_pressed(): pass if running_time() - start > 2000: delay = minutes_to_delay(15 / 60) display.scroll('Talk 15 secs') if button_a.is_pressed(): delay = minutes_to_delay(get_talk_time(delay_to_minutes(delay))) start_up_screen() display_minutes(delay_to_minutes(delay)) if accelerometer.current_gesture() == 'shake': send_message = True while accelerometer.current_gesture() == 'shake': delay_from_remote = message_to_delay(received_message) if delay_from_remote >= 0: delay = delay_from_remote send_message = False if send_message: radio.send(SHAKY_ID + ' ' + 'start ' + str(delay)) count_down(delay) get_ready_to_go_again()
def main(): data_sent = 0 state = GET_DATA_NUM while True: # State 0 if state == GET_DATA_NUM: data_num = 1 attempt = 0 while True: cy, cx = divmod(data_num-1, 5) # Cursor x and y depending on the data_num display.set_pixel(cx, cy, 9) if button_a.is_pressed() and button_b.is_pressed(): state = READY_TO_SAMPLE # TODO: Change state to some other state data_sent = 0 sleep(500) break elif button_a.is_pressed(): if data_num > 1: display.set_pixel(cx, cy, 0) # Clear LED pixel if data_num > 1 data_num = data_num - 1 if (data_num > 1) else 1 elif button_b.is_pressed(): data_num = data_num + 1 if (data_num < MAX_FILES_NUM) else MAX_FILES_NUM sleep(200) # State 1 elif state == READY_TO_SAMPLE: while True: if button_a.is_pressed(): state = SAMPLE_DATA break elif button_b.is_pressed(): display.clear() cy, cx = divmod(data_num-data_sent-1, 5) setPixelTill(cx, cy, 9) else: display.show(Image.ARROW_W) sleep(200) # State 2 elif state == SAMPLE_DATA: countdown(3) display.show(Image.TARGET) with open("file_{}.csv".format(data_sent), "w") as data_file: data_file.write("x,y,z\n") initial_time = running_time() while (running_time()-initial_time) < SAMPLE_DURATION: t0 = running_time() data_file.write("{},{},{}\n".format(*accelerometer.get_values())) t_diff = running_time()-t0 sleep(0 if (SAMPLE_PERIOD-t_diff)<0 else SAMPLE_PERIOD-t_diff) data_sent += 1 if (data_num-data_sent)>0: state = READY_TO_SAMPLE else: state = EXIT # State 3 elif state == EXIT: display.show(Image.HAPPY) break
def start(self): while True: resp = self.comm.wait_for_command(0) if resp["command"] == "start_fight": while not resp["command"] == "end_fight": resp = self.comm.wait_for_command(0) if button_a.is_pressed() or button_b.is_pressed(): display.scroll("Finish fight...") if button_a.is_pressed() or button_b.is_pressed(): self.wake() break while self.health > 0: display.show(self.display_health())
def jogar(qtd_asteroides_tela: int) -> None: lista_jogo = iniciar_lista(qtd_asteroides_tela) isDificil = qtd_asteroides_tela < 3 imp_lista(lista_jogo, isDificil) t_ini = ticks_ms() while lista_jogo[0] != -1: piscar_asteroide(lista_jogo[0]) if(button_a.is_pressed() and not button_b.is_pressed() and lista_jogo[0] == 0) or\ (button_a.is_pressed() and button_b.is_pressed() and lista_jogo[0] == 2) or\ (not button_a.is_pressed() and button_b.is_pressed() and lista_jogo[0] == 4): atualizar_lista(lista_jogo) imp_lista(lista_jogo, isDificil) sleep_ms(80) display.scroll("{:.2f}".format((ticks_ms() - t_ini) / 1000)) display.show(Image.HAPPY)
def button_incdec(): get_state = lambda: int(button_b.is_pressed()) - int(button_a.is_pressed()) initial_state = get_state() if initial_state: while get_state(): pass return initial_state
def play_game(delay=100, accelerometer_sensitivity=1/300): """Enter game main event loop.""" x, y = 2, 2 # Pixel coordinates, starting in middle of display winner = None while winner is None: if button_a.is_pressed(): x = x + 1 play('A:1') if button_b.is_pressed(): x = x - 1 play('B:1') if x > 4: winner = 'A' elif x < 0: winner = 'B' else: # No winner - continue set_pixel(x, y) # Change row based on accelerometer angle delta = accelerometer.get_y() * accelerometer_sensitivity y = max(0, min(4, int(y + delta))) sleep(delay) return winner
def send_direction(): """ Send the direction which the probe is pointing to: direction_N, direction_NE, direction_E... """ display.show(Image.ARROW_N) while True: sleep(100) if button_b.is_pressed(): break # Back to the menu mode heading = compass.heading() if (heading > 337) or (heading <= 22): needle = "N" elif 22 < heading <= 67: needle = "NE" elif 67 < heading <= 112: needle = "E" elif 112 < heading <= 157: needle = "SE" elif 157 < heading <= 202: needle = "S" elif 202 < heading <= 247: needle = "SW" elif 257 < heading <= 292: needle = "W" elif 292 < heading <= 337: needle = "W" radio.send("dir_{}".format(needle))
def setup(self): while True: try: self.board.add_ship() x = 0 y = 0 doublepress = False while not doublepress: a_was_pressed = button_a.was_pressed() b_was_pressed = button_b.was_pressed() a_pressed = button_a.is_pressed() b_pressed = button_b.is_pressed() if a_pressed and b_pressed: self.board.rotate_ship() if a_was_pressed and b_was_pressed: doublepress = True elif a_pressed: x += 1 try: self.board.move_ship(x=x, y=y) except InvalidPositionError: x = 0 self.board.move_ship(x=x, y=y) elif b_pressed: y += 1 try: self.board.move_ship(x=x, y=y) except InvalidPositionError: y = 0 self.board.move_ship(x=x, y=y) except StopIteration: break
def scan(level, pause=500): # Mark reverse as global so we can update it from this method global reverse # Loop through the various rows of our square. As we're going diagonally we need to loop # 9 times. for i in range(0, 5): # Start looping over the pixel grid for x in range(0, 5): # if we press a button reverse the direction if button_a.is_pressed() or button_b.is_pressed(): reverse = False if reverse else True for y in range(0, i + 1): # If the pixel we're trying to set wouldn't be on the grid # then don't try and set it if x <= MAX_ROWS and y <= MAX_ROWS: x_coord = MAX_ROWS - x if reverse else x y_coord = MAX_ROWS - y if reverse else y display.set_pixel(x_coord, y_coord, level) i += 1 sleep(pause)
def pick_speed(speed): while not button_b.is_pressed(): add_text(4, 1, str(speed)) if button_a.is_pressed(): speed = speed - 1 if speed > 1 else 9 sleep(200) return speed
def scan(self): readings = [int(not pin.read_digital()) for pin in self.pins[:-2]] readings.append(int(button_a.is_pressed())) readings.append(int(button_b.is_pressed())) self.current_readings = [ int(self.current_readings[pin] or readings[pin]) for pin in range(0, len(readings)) ]
def start(): for i in range(5): sleep(500) if not (button_a.is_pressed() and button_b.is_pressed()): return location = random.choice(LOCATIONS) radio.send(location) play(location)
def position(sprite, board, send=False): blink(sprite, board) while not (button_a.is_pressed() and button_b.is_pressed()): sleep(100) # if button is pressed but not released yet, keep waiting if button_a.is_pressed() or button_b.is_pressed(): continue a = button_a.was_pressed() b = button_b.was_pressed() if a or b: sprite = move(sprite, b, a) blink(sprite, board) if send: radio.send("{}{}".format(*sprite[0])) return sprite
def gen(): recvd = audio.AudioFrame() empty = audio.AudioFrame() while True: if radio.receive_bytes_into(recvd) == 32: yield recvd else: yield empty if button_a.is_pressed() and button_b.is_pressed(): return
def update(self): # Clear old pixel # TODO we don't need to clear if no button is pressed display.set_pixel(self.x, self.y, 0) # Move left or right if button_a.is_pressed() and self.x > 1: self.x = self.x - 1 if button_b.is_pressed() and self.x < 3: self.x = self.x + 1 # Redraw display.set_pixel(self.x, self.y, 9)
def main(): display.show(Image.HAPPY) while True: if button_a.is_pressed(): x = accelerometer.get_x() y = accelerometer.get_y() mouse.move_relative(x // 10, y // 10) sleep(50) if button_b.is_pressed(): mouse.left_click() sleep(500)
def jogar(piscar: bool = False) -> None: lista_asteroides = iniciar_asteroides_jogo() imprimir_asteroides(lista_asteroides) t_ini = ticks_ms() if piscar: tempo_espera = 50 else: tempo_espera = 140 while lista_asteroides[0] != -1: if piscar: piscar_asteroide_atual(lista_asteroides[0]) if(button_a.is_pressed() and not button_b.is_pressed() and lista_asteroides[0] == 0) or\ (button_a.is_pressed() and button_b.is_pressed() and lista_asteroides[0] == 2) or\ (not button_a.is_pressed() and button_b.is_pressed() and lista_asteroides[0] == 4): atualizar_lista_asteroides(lista_asteroides) imprimir_asteroides(lista_asteroides) sleep_ms(tempo_espera) display.scroll("{:.2f}".format((ticks_ms() - t_ini) / 1000)) display.show(Image.HAPPY)
def add_ship(sprite, board): while True: sprite = position(sprite, board) if sum(board.get_pixel(x, y) for x, y in sprite) == 0: break for x, y in sprite: board.set_pixel(x, y, 8) display.show(board) sleep(500) # wait for release of the buttons (to avoid accidental placement) while button_a.is_pressed() and button_b.is_pressed(): sleep(100)
def main(): channel = 0 channel_set = False while not channel_set: sleep(100) if button_a.is_pressed() and button_b.is_pressed(): channel_set = True elif button_a.is_pressed(): channel = channel - 1 elif button_b.is_pressed(): channel = channel + 1 channel = channel % 10 display.show(str(channel), wait=False, loop=True) display.show(Image.HAPPY, wait=True) sleep(500) display.show(str(channel), wait=False, loop=True) radio.config(channel=channel) radio.on() while True: sleep(10) if button_a.is_pressed() and button_b.is_pressed(): radio.send('both') display.show('b', wait=False, loop=False) elif button_a.is_pressed(): radio.send('left') display.show('l', wait=False, loop=False) elif button_b.is_pressed(): radio.send('right') display.show('r', wait=False, loop=False) else: radio.send('stop') display.show(str(channel), wait=False, loop=True)
def scan(self): """ Read the pins and buttons and "or" the values into the current readings list :return: """ readings = [int(not pin.read_digital()) for pin in self.pins[:-2]] # read buttons readings.append(int(button_a.is_pressed())) readings.append(int(button_b.is_pressed())) # "or" in the values self.current_readings = [ int(self.current_readings[pin] or readings[pin]) for pin in range(0, len(readings)) ]
def play(self): self.setup() radio.on() while True: img = self.planner.draw() x = 0 y = 0 while not a_pressed and b_pressed: old = img[y][x] a_pressed = button_a.is_pressed() b_pressed = button_b.is_pressed() if a_pressed and not b_pressed: img[y][x] = old x += 1 elif b_pressed: img[y][x] = old y += 1 img[y][x] = 2 self.draw(img) self.transmit_shot(x, y) incoming = radio.receive() hit = bool(int(incoming[0])) win = bool(int(incoming[1])) if hit: self.planner.hit(x, y) else: self.planner.miss(x, y) if win: self.show_win() break img = self.planner.draw() self.draw(img) time.sleep(4) img = self.board.draw() self.draw(img) incoming = radio.receive() x = int(incoming[0]) y = int(incoming[1]) hit, win = self.board.hit(x, y) value = str(int(hit)) + str(int(win)) radio.transmit(value) if win: self.show_loss() break
def main(): state = READY while True: # Ready state if state == READY: while True: if button_a.is_pressed(): state = SAMPLE_DATA break elif button_b.is_pressed(): radio.on() radio.send("done") radio.off() else: display.show(Image.ARROW_W) sleep(100) # Sample Data state elif state == SAMPLE_DATA: data_sent = 0 # Reset data sent value countdown(3) # Show countdown on the Microbit LED display.show(Image.TARGET) radio.on() initial_time = running_time() while (running_time() - initial_time) < SAMPLE_DURATION: t0 = running_time() if data_sent == 0: # Turn off all Microbit LEDs display.clear() cx, cy = divmod( data_sent, 5) # Get current LED pixel coordinate of the BBC Microbit radio.send(str(accelerometer.get_values())) display.set_pixel(4 - cx, cy, 9) data_sent = 0 if data_sent >= 24 else data_sent + 1 # Increase and limit data_sent value within 0-24 range wait_t = SAMPLE_INTERVAL - (running_time() - t0 ) # Time till next sample if (wait_t > 0): sleep(wait_t) radio.send("done") radio.off() state = READY # Exit state elif state == EXIT: display.show(Image.HAPPY) return 0 sleep(100)
def get_button_presses(): """ returns how many times button_a is pressed until button_b is pressed """ # getting the count now resets the counter num = button_a.get_presses() # sleep until button_b is pressed ... while not button_b.is_pressed(): sleep(100) # get the count again to get the number of # button_a presses since the last call num = button_a.get_presses() # return the result ... return num
def setting_mode(threshold): while (button_a.is_pressed() or button_b.is_pressed()): display.show(Image.CLOCK12) sleep(300) display.show(Image.CLOCK3) sleep(300) display.show(Image.CLOCK6) sleep(300) display.show(Image.CLOCK9) sleep(300) display.clear() display.show(threshold) sleep(300) display.show(Image.ARROW_E) sleep(400) display.show(Image.ARROW_W) sleep(400) display.clear() last_click = running_time() while (running_time() < last_click + 5000): if button_b.was_pressed(): last_click = running_time() threshold = threshold + 1 display.show(Image.ARROW_N) sleep(300) display.show(threshold) sleep(300) display.clear() if button_a.was_pressed(): last_click = running_time() threshold = threshold - 1 display.show(Image.ARROW_S) sleep(300) display.show(threshold) sleep(300) display.clear() tfile = open("tstore", "w") tfile.write(str(threshold)) tfile.close() display.show(Image.YES) sleep(700) display.clear() return (threshold)
def main(): a_t = "Hello" b_t = "Goodbye" sb = ScrollBit() st = ScrollText(sb=sb) btn_act(st, a_t, Image.ARROW_W) while True: sb.clear() st.step() sb.show() if button_a.is_pressed(): btn_act(st, a_t, Image.ARROW_W) if button_b.is_pressed(): btn_act(st, b_t, Image.ARROW_E) sleep(50)
def next(self): # remove ship D.blit(self.SHIP, self.ship_x - 3, self.ship_y, 1) # update star positions cont = True for star in self.stars: if star.next(self.ship_x): cont = False for star in self.stars: if star.moved: star.draw() if A.is_pressed(): self.ship_x -= 2 elif B.is_pressed(): self.ship_x += 2 if self.ship_x < 6: self.ship_x = 6 if self.ship_x > 124: self.ship_x = 124 D.blit(self.SHIP, self.ship_x - 3, self.ship_y, 0) D.repaint(60) return cont
sunrise_threshold = daylight_threshold + (hysteresis / 2) sunset_threshold = daylight_threshold - (hysteresis / 2) # display the time when the left button is pressed if button_a.was_pressed(): display.show(get_time_string()) display.clear() print("Time:", get_time_string(show_seconds=True)) # debug output when the right button is pressed if button_b.was_pressed(): print("light avg", light_average) display.show(str(round(light_average))) sleep(300) display.clear() # go into setting mode if the right button is held down if button_b.is_pressed(): press_time = running_time() while (button_b.is_pressed()): display.show(Image.DIAMOND_SMALL) if (running_time() - press_time > 1500): daylight_threshold = setting_mode(daylight_threshold) display.clear() # read light levels periodically and update clock as needed if (running_time() > (last_update + update_interval) or last_update == 0): try: light_array[ctr] = read_light_sensor() except IndexError: light_array.append(read_light_sensor()) ctr += 1 if ctr >= 100:
from random import randint from OD01_bitmap import show_bitmap def mv_stmp(x1, y1, x2, y2, stmp): draw_stamp(x1, y1, stmp, 0, 0) draw_stamp(x2, y2, stmp, 1, 1) def init_star(i): return randint(0, 1), randint(0, 58), randint(1, 4) initialize() show_bitmap("888.bin") while not (A.is_pressed() or B.is_pressed()): pass clear_oled() starStamp = [ bytearray(b'\x00\x60\xa0\x40\x00'), bytearray(b'\x00\xc0\xe0\x60\x00') ] ship = bytearray(b'\x40\xf0\x78\xf0\x40') starX, starY, star, speed = [0] * 5, [0] * 5, [0] * 5, [0] * 5 for i in range(0, 5): star[i], starX[i], v = init_star(i) speed[i], starY[i] = v, -v shipX, score, shipX0 = 32, 0, 32 gameOver = False while not gameOver: for i in range(0, 5):
from microbit import button_a, button_b, display, sleep delay = 20 def fade(): for x in range(5): for y in range(5): brightness = display.get_pixel(x, y) if brightness > 0: display.set_pixel(x, y, brightness - 1) while True: for x in range(5): for y in range(5): fade() if button_a.is_pressed(): delay += 1 elif delay > 0 and button_b.is_pressed(): delay -= 1 display.set_pixel(x, y, 9) for _ in range(delay): sleep(1)
def quiz_m(teq): """ Function to handle multiple choice quiz Params: teq: dict """ # Init LED happy image display.show(Image.HAPPY) # This is an advanced topic as well however this little function # cleans out the unnecessary global objects or variables on what # we call the heap area in memory gc.collect() # Init score object score = 0 # Here we iterate through our quiz database with multiple # choice items for key in teq: display.show(Image.SURPRISED) print(key) say(str(key), speed=SPEED) display.show(Image.HAPPY) time.sleep(1) display.show(Image.SURPRISED) print('Press A for {0}.'.format(teq[key][0])) say('Press Ayyy for', speed=SPEED) say(str(teq[key][0]), speed=SPEED) display.show(Image.HAPPY) time.sleep(1) display.show(Image.SURPRISED) print('Touch the logo for {0}.'.format(teq[key][1])) say('Toch the logo for', speed=SPEED) say(str(teq[key][1]), speed=SPEED) display.show(Image.HAPPY) time.sleep(1) display.show(Image.SURPRISED) print('Press B for {0}.'.format(teq[key][2])) say('Press B for', speed=SPEED) say(str(teq[key][2]), speed=SPEED) display.show(Image.HAPPY) while True: if button_a.is_pressed(): response = 0 break elif pin_logo.is_touched(): response = 1 break elif button_b.is_pressed(): response = 2 break else: pass correct_answer = teq[key][3] display.show(Image.SURPRISED) print('You selected {0}.'.format(teq[key][response])) say('You selected', speed=SPEED) say(str(teq[key][response]), speed=SPEED) display.show(Image.HAPPY) time.sleep(1) if response == correct_answer: display.show(Image.SURPRISED) print('CORRECT!') say('CORRECT!', speed=SPEED) display.show(Image.HAPPY) score += 1 else: display.show(Image.SURPRISED) print('The correct answer is {0}.'.format( teq[key][correct_answer])) say('The correct answer is', speed=SPEED) say(str(teq[key][correct_answer]), speed=SPEED) display.show(Image.HAPPY) time.sleep(1) gc.collect() # Here we reply to the student their score display.show(Image.SURPRISED) print('You got {0} out of {1} correct!'.format(score, len(teq))) say('You got', speed=SPEED) say(str(score), speed=SPEED) say('out of', speed=SPEED) say(str(len(teq)), speed=SPEED) say('correct!', speed=SPEED) display.show(Image.HAPPY) time.sleep(1) # If student got a perfect score respond appropriately # or provide an encouring message to retry the quiz display.show(Image.SURPRISED) if score == len(teq): print('You got a perfect score!') say('You got a perfect score!', speed=SPEED) print('Well done!') say('Well done!', speed=SPEED) print('I am so proud of you!') say('I am so proud of you!', speed=SPEED) play(POWER_UP) else: print('You are doing a great job!') say('You are doing a great job!', speed=SPEED) print('I would LOVE for you to try again!') say('I would LOVE for you to try again!', speed=SPEED) # Display happy response at the end of the quiz display.show(Image.HAPPY) time.sleep(1) gc.collect()
simon = [] guess = [] # start up effects display.clear() audio.play(Sound.GIGGLE) sleep(1000) display.show(Image.FABULOUS) speech.say('Simon says', speed=150, pitch=50, throat=100, mouth=50) sleep(500) # wait for the user to press A + B display_flag = True while not (button_a.is_pressed() and button_b.is_pressed()): if display_flag: display.show(images[4]) else: display.clear() sleep(200) display_flag = not display_flag for i in range(4): music.pitch(notes[i]) display.show(images[i]) sleep(100) display.clear() sleep(400) music.stop()
YELLOW = b'Y' GREEN = b'G' TRIGGER = b'T' CLEAR = b'C' UNKNOWN = b'U' dim_value = 9 # value 1-9 for dimming the display NEUTRAL = Image('00000:09090:00000:99999:00000:') display.show(Image.GHOST / 9 * dim_value) while True: if uart.any(): data = uart.read() if RED in data: display.show(Image.SAD / 9 * dim_value) elif YELLOW in data: display.show(NEUTRAL / 9 * dim_value) elif GREEN in data: display.show(Image.HAPPY / 9 * dim_value) elif CLEAR in data: display.clear() elif UNKNOWN in data: display.show(Image("?") / 9 * dim_value) if button_b.is_pressed(): uart.write(TRIGGER) display.show([clk / 9 * dim_value for clk in Image.ALL_CLOCKS], delay=100) display.show(Image.CLOCK12 / 9 * dim_value)
def gen(): recvd = audio.AudioFrame() empty = audio.AudioFrame() while True: if radio.receive_bytes_into(recvd) == 32: yield recvd else: yield empty if button_a.is_pressed() and button_b.is_pressed(): return audio.play(gen()) while True: message = "Press button a to send 'sample.raw' or sawtooth wave. Press button b to play received waveform. Press both buttons to stop." display.scroll(message, delay=100, wait=False) message_end = running_time() + len(message) * 600 if button_a.is_pressed() and button_b.is_pressed(): break while True: sleep(50) if button_a.is_pressed(): send() break if button_b.is_pressed(): play() break if running_time() > message_end: break
radio.config(channel=90, queue=12) count = -1 def gen(): recvd = audio.AudioFrame() empty = audio.AudioFrame() while True: if radio.receive_bytes_into(recvd) == 32: yield recvd else: yield empty if button_a.is_pressed() and button_b.is_pressed(): return audio.play(gen()) while True: message = "Press button a to send 'sample.raw' or sawtooth wave. Press button b to play received waveform. Press both buttons to stop." display.scroll(message, delay=100, wait=False) message_end = running_time() + len(message)*600 if button_a.is_pressed() and button_b.is_pressed(): break while True: sleep(50) if button_a.is_pressed(): send() break if button_b.is_pressed(): play() break if running_time() > message_end: break
elif clicks == 4: #toggle tr acc tr ^= True elif clicks == 5: #reload sample program for i, d in enumerate(prog): memory[i] = d memRead(pc) elif clicks == 0: #no button clear data databyte = "00000000" dataWrite(databyte) else: display.set_pixel(row, col, (7 * (display.get_pixel(row, col) < 1))) dataRead() elif button_b.is_pressed(): longpress = 0 clicks = button_a.get_presses() clicks = 0 while button_b.is_pressed(): sleep(100) longpress = longpress + 1 if longpress > 5: #options if button down >0.5second clicks = button_a.get_presses() if clicks == 1: memWrite(pc) pc = min(pc + 1, 255) memRead(pc) elif clicks == 2: pc = max(0, pc - 1) memRead(pc)
def wait_unpressed(): while button_a.is_pressed() or button_b.is_pressed(): sleep(100)
def main(): display.show(Image.HAPPY) up_pressed, down_pressed, left_pressed, right_pressed = False, False, False, False while True: # Only send arrow commands when Button a is pressed if button_a.is_pressed(): # Hold down or release arrow keys based on accelerometer values x, y, z = accelerometer.get_values() if x > 300: if not right_pressed: keyboard.key_down("right") right_pressed = True else: if right_pressed: keyboard.key_up("right") right_pressed = False if x < -300: if not left_pressed: keyboard.key_down("left") left_pressed = True else: if left_pressed: keyboard.key_up("left") left_pressed = False if y < -300: if not up_pressed: keyboard.key_down("up") up_pressed = True else: if up_pressed: keyboard.key_up("up") up_pressed = False if y > 300: if not down_pressed: keyboard.key_down("down") down_pressed = True else: if down_pressed: keyboard.key_up("down") down_pressed = False # Display direction on matrix img = Image.CHESSBOARD if up_pressed: if left_pressed: img = Image.ARROW_NW elif right_pressed: img = Image.ARROW_NE else: img = Image.ARROW_N elif down_pressed: if left_pressed: img = Image.ARROW_SW elif right_pressed: img = Image.ARROW_SE else: img = Image.ARROW_S elif left_pressed: img = Image.ARROW_W elif right_pressed: img = Image.ARROW_E display.show(img, delay=50, wait=False) else: if up_pressed: keyboard.key_up("up") if down_pressed: keyboard.key_up("down") if left_pressed: keyboard.key_up("left") if right_pressed: keyboard.key_up("right") up_pressed, down_pressed, left_pressed, right_pressed = False, False, False, False display.show(Image.HAPPY) # Press keys when buttons are pressed if button_b.is_pressed(): keyboard.press("space") display.show("S") sleep(150)
from microbit import display, accelerometer, sleep, button_a, button_b from music import pitch, stop as stop_music def updown(): for p in range(10, 1000, 10): pitch(p, wait=False) sleep(10) for p in range(1000, 10, -10): pitch(p, wait=False) sleep(10) def accel(): while not button_a.is_pressed(): p = abs(accelerometer.get_z()) pitch(p, wait=False) sleep(10) while True: stop_music() display.show('?') if button_a.is_pressed(): updown() if button_b.is_pressed(): accel() sleep(10)
def init() : pass def hdr_ba() : dp.show( Image.HAPPY) def hdr_bb() : dp.clear() def loop() : dp.show( Image.SAD) if __name__ == "__main__" : init() while True : if ba.is_pressed() : hdr_ba() elif bb.is_pressed() : hdr_bb() else : loop()
def wait_for_button(): while not button_a.is_pressed() and not button_b.is_pressed(): sleep(100)