def get_talk_time(minutes): """Setup talk time""" display.scroll('A -1, B +1') # clear press counters button_a.get_presses() button_b.get_presses() quit_flag = False while quit_flag is not True: minutes = minutes - button_a.get_presses() \ + button_b.get_presses() display_minutes(int(minutes)) # To exit press a for 2 seconds if button_a.is_pressed(): start = running_time() while button_a.is_pressed(): if running_time() - start > 2000: quit_flag = True display.scroll(str(int(minutes))) return minutes
def output(data): radio.send(str(data)) data = str(data) if len(data) == 1: display.show(data) else: display.scroll(data)
def gameStart(self): display.scroll("3... 2... 1... Launch...", delay=70) while True: astroidField.createAstroid() astroidField.drawAstroids() spaceShip.draw() if spaceShip.collide(): self.gameOver() break sleep(self.frameRate) astroidField.hideAstroids() spaceShip.hide() if button_a.was_pressed(): spaceShip.moveLeft() elif button_b.was_pressed(): spaceShip.moveRight() astroidField.moveAstroids() astroidField.clearPassedAstroids() self.increaseDifficulty()
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 sing(song=None): """ sing something simple """ song = choose(songs, song) if quiet: display.scroll(song) else: music.play(song)
def show_wave(name, frame, duration=1500): display.scroll(name + " wave", wait=False, delay=100) audio.play(repeated_frame(frame, duration), wait=False) for i in range(75): sleep(100) if button_a.is_pressed(): display.clear() audio.stop() break
def talk(text=None): """ talk to the world """ text = choose(sayings, text) gc.collect() if quiet: display.scroll(text) else: speech.say(text)
def say_something_simple(): """ ernie wise """ if random.random() < 0.6: display.scroll(choose(sayings)) else: if random.random() < 0.1: sing() else: talk()
def show_wave(name, frame, duration=1500): display.scroll(name + " wave", wait=False,delay=100) audio.play(repeated_frame(frame, duration),wait=False) for i in range(75): sleep(100) if button_a.is_pressed(): display.clear() audio.stop() break
def hdr_bb( cnt, limit) : if limit == cnt : cnt = 0 else : cnt = cnt + 1 uart.write( str( cnt)) dp.scroll( str( cnt), delay = 80) return cnt
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 setFreq(self, freq): # Constrain the frequency prescaleval = 25000000 prescaleval /= 4096 prescaleval /= freq prescaleval -= 1 prescale = int(prescaleval) # Math.Floor(prescaleval + 0.5) oldmode = self.i2cread(self, self.PCA9685_ADDRESS, self.MODE1) newmode = (oldmode & 0x7F) | 0x10 self.i2cwrite(self, self.PCA9685_ADDRESS, self.MODE1, newmode) self.i2cwrite(self, self.PCA9685_ADDRESS, self.PRESCALE, prescale) self.i2cwrite(self, self.PCA9685_ADDRESS, self.MODE1, oldmode) sleep(1000) self.i2cwrite(self, self.PCA9685_ADDRESS, self.MODE1, oldmode | 0xA1) display.scroll('initialised')
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 init_radio(radio_mode, chan_min): ''' Display starting messages. Set radio config before the loop. ''' # Display starting messages display.scroll('>>') print('\n >> Starting ... \n') # Start and configure the radio radio.on() radio.config(channel=chan_min) if radio_mode == 'ble': radio.ble() elif radio_mode == 'raw': radio.config(raw=1) chan = chan_min - 1 rate_nb = 0 return radio, chan, rate_nb
def get_message(): msg = receive() display.scroll(str(msg)) if msg == 'A': Motor.MotorRun(1, 255) Motor.MotorRun(3, 255) elif msg == 'B': Motor.MotorRun(1, -255) Motor.MotorRun(3, -255) elif msg == 'C': Motor.MotorRun(1, -255) Motor.MotorRun(3, 255) elif msg == 'D': Motor.MotorRun(1, 255) Motor.MotorRun(3, -255) elif msg == '0': Motor.MotorRun(1, 0) Motor.MotorRun(3, 0)
def play(location): display.show(Image.ALL_CLOCKS, delay=50, loop=True, wait=False) number = random.randrange(1, 10000) sleep(random.randrange(10, 500)) radio.send(str(number)) sleep(3000) numbers = [] while True: message = radio.receive() if not message: break numbers.append(int(message)) if number < min(numbers): location = "UNKNOWN" radio.off() display.show(Image.ARROW_E) seconds = 0 start_time = running_time() button_b.was_pressed() while seconds < 8 * 60: if accelerometer.was_gesture("shake"): minutes = seconds // 60 display.scroll("{0}:{1:02d}".format(minutes, seconds - minutes * 60)) if button_b.was_pressed(): display.scroll(location.upper()) sleep(10) seconds = (running_time() - start_time) // 1000 animation = [Image.SKULL, Image()] display.show(animation, delay=500, loop=True, wait=False) while True: sleep(10000) display.off()
def main(): """ entry point to the app """ # loop forever while True: # generate a random number to represent the number of leds to show ... num = random.randint(0, 10) # clear the display from the previous game ... display.clear() # a list to keep track of which leds have been used ... used = [] # loop 'num' times ... for i in range(num): # generate a random number to represent which led to show ... led = random.randint(0, NUM_LEDS - 1) # if the led has already been used, # generate another random number ... while led in used: led = random.randint(0, NUM_LEDS - 1) used.append(led) # get the coords for the led to show ... x, y = get_coords(led) # show the led ... display.set_pixel(x, y, 9) # get the answer from the user ... input_num = get_button_presses() # if the answer is correct, display WIN otherwise LOSE ... if num == input_num: display.scroll("WIN!") else: display.scroll("LOSE!")
def main(): """ entry point to the app """ # loop forever while True: # generate a random number to represent the number of leds to show ... num = random.randint(0, 10) # clear the display from the previous game ... display.clear() # a list to keep track of which leds have been used ... used = [] # loop 'num' times ... for i in range(num): # generate a random number to represent which led to show ... led = random.randint(0, NUM_LEDS-1) # if the led has already been used, # generate another random number ... while led in used: led = random.randint(0, NUM_LEDS-1) used.append(led) # get the coords for the led to show ... x, y = get_coords(led) # show the led ... display.set_pixel(x, y, 9) # get the answer from the user ... input_num = get_button_presses() # if the answer is correct, display WIN otherwise LOSE ... if num == input_num: display.scroll("WIN!") else: display.scroll("LOSE!")
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 EndScreen(win): global gameStarted gameStarted = False if(win): display.scroll("You win") else: display.scroll("You lose") display.scroll('Press a button to start ', wait=False, loop=True)
def gameOver(self): spaceShip.blowUpShip() sleep(300) display.scroll("Game Over") sleep(300) display.scroll("Score : " + str(self.score)) sleep(500) display.scroll("Marco Janssen (c)2021", delay=50)
continue if msg == 'RESET': org = create_genesis_org() print_org(org) write_string(org_to_string(org), FILE) collect() if ticks_ms() < last_reproduction + maturity * 1000: state = 'WAIT' elif state == 'WAIT': state = 'RECV' elif button_a.was_pressed(): display.scroll('G:{} C:{}'.format(org['gender'], org['color'])) elif button_b.was_pressed() and state == 'RECV': state = 'SEND' msg = 'SREQ|{}'.format(org_to_string(org)) radio.send(msg) if state == 'RECV': if msg is not None and msg[:4] == 'SREQ' and randint(1,3) == 1: new_org = org_from_repr(msg[5:]) if new_org['gender'] != org['gender']: print('Parent 1:') print_org(org) print('Parent 2:') print_org(new_org) radio.send('SRSP|{}'.format(org_to_string(org)))
radio.on() while True: if button_a.was_pressed(): radio.send('Forward') #Forward message elif button_a.is_pressed() and button_b.is_pressed(): radio.send("Stop") elif button_b.was_pressed(): radio.send('Back') #Back # Read any incoming messages. incoming = radio.receive() if incoming == 'Forward': # turn motor 1 on in forward for 1 second and turn it off #r.motor_on(r.MOTOR_2, r.FORWARD) display.scroll('F') #sleep(3000) r.motor_on(r.MOTOR_1, r.FORWARD, 100) #sleep(5000) #r.motor_off(r.MOTOR_1) #sleep(2000) #r.motor_on(r.MOTOR_1, r.REVERSE,100) if incoming == 'Stop': #r.motor_off(r.MOTOR_2) display.scroll('S') r.motor_off(r.MOTOR_1) if incoming == 'Back': #r.motor_off(r.MOTOR_2)
from random import randint from microbit import display, button_a, button_b display.scroll('Heads = A') display.scroll('Tails = B') random_number = randint(1, 2) while True: if button_a.is_pressed(): if random_number == 1: display.scroll('You WON!') break else: display.scroll('You Lost') break if button_b.is_pressed(): if random_number == 2: display.scroll('You WON!') break else: display.scroll('You Lost') break
for coord in snake[1:]: # draw snake, without new head xpos, ypos = coord # make current position set_px(xpos, ypos, 1) newpixel = get_px(newheadx, newheady) # if newpixel is 0, 1, or tail of snake tailJustMissed = ( newheadx, newheady) == snake[0] # if tail of snake, delete tail if tailJustMissed: newpixel = 0 if (((newheadx, newheady) == (foodX, foodY)) and newpixel == 1) or newpixel == 0: # didn't hit ourself snake.append((newheadx, newheady)) set_px(newheadx, newheady, 1) else: # did hit ourself end = True if newpixel == 0: # blank pixel to move to if not tailJustMissed: set_px(snake[0][0], snake[0][1], 0) del snake[0] elif (newheadx, newheady) == (foodX, foodY): # eaten the food foodEaten = True score += (10 - speed) # more points for faster game # higher the speed, slower the game foodTimeout -= 1 sleep(speed * 10) display.scroll("Score " + str(score))
from microbit import display, button_a, Image, accelerometer, sleep display.scroll('Hello World!') display.show(Image.HAPPY) sleep(1000) while True: if button_a.is_pressed(): display.show(Image.HOUSE) sleep(1000) if accelerometer.was_gesture('shake'): print('hey') display.show(Image.HAPPY) sleep(1000) display.clear()
Control the bit by tilting the micro:bit Avoid the obstacles Create your own terrain by editing the terrain list below: ''' import music from microbit import (accelerometer, display, sleep, Image, reset, ) display.scroll('Flappy Bit') bird = 2 terrain = [ (0, 0), (0, 0), (0, 0), (0, 0), (0, 2), (0, 0), (0, 0), (3, 0), (3, 0), (4, 0), (3, 0), (0, 0),
Avoid the obstacles Create your own terrain by editing the terrain list below: ''' import music from microbit import ( accelerometer, display, sleep, Image, reset, ) display.scroll('Flappy Bit') bird = 2 terrain = [ (0, 0), (0, 0), (0, 0), (0, 0), (0, 2), (0, 0), (0, 0), (3, 0), (3, 0), (4, 0), (3, 0), (0, 0),
square = audio.AudioFrame() HALF = len(square)//2 for i in range(HALF): square[i] = 8 square[i+HALF] = 248 show_wave("Square", square) sleep(1000) for i in range(len(frame)): frame[i] = 252-i*8 show_wave("Sawtooth", frame) del frame #Generate a waveform that goes from triangle to square wave, reasonably smoothly. frames = [ None ] * 32 for i in range(32): frames[i] = frame = audio.AudioFrame() for j in range(len(triangle)): frame[j] = (triangle[j]*(32-i) + square[j]*i)>>5 def repeated_frames(frames, count): for frame in frames: for i in range(count): yield frame display.scroll("Ascending wave", wait=False) audio.play(repeated_frames(frames, 60))
hitCount += 1 # increment score ballDirection *= -1 # change ball direction # Check if player won... if hitCount >= maxScore: # Bounce the ball back to the top one last time for i in range(3, -1, -1): display.set_pixel(ballX, i, 5) sleep(delay) display.set_pixel(ballX, i, 0) #display.clear() sleep(delay) display.scroll("You won!") display.show(Image.HAPPY) sleep(3000) gameOn = False continue # Case where paddle missed ball elif ballY >= 4 and padX != ballX: display.set_pixel(oldBallX, oldBallY, 0) display.set_pixel(ballX, ballY, 5) # turn-on LED at new ball location sleep(delay) display.set_pixel(ballX, ballY, 0) # turn-off LED at new ball location hitCount -= 1 # Decrement score # ballDirection *= -1 # Change ball direction (up) [this line cancels out line 158]
import random from microbit import display names = ['Mary', 'Yolanda', 'Damien', 'Alia', 'Kushal', 'Mei Xiu', 'Zoltan'] display.scroll(random.choice(names))
def task_3(): yield from wait_for_button_press(button_a) yield from scroll('The end') display.scroll('---')
from microbit import display display.scroll("Hello, World!") # Images from microbit import display, Image display.show(Image.HAPPY) boat = Image("00710:00755:00700:99999:09990") display.show(boat) # Animation display.show(reversed([str(x) for x in range(10)]), loop=False, delay=500) display.show(Image.ALL_CLOCKS, loop=True, delay=100) display.clear()
duration = 120000 # logging time in ms countdown = 120 if not button_a.is_pressed(): n = len(os.listdir()) - 1 # 1 indexed hc = 0.0 offset = 0.0 max_height = 0.0 bme = bme280.bme280() bme.set_qnh(bme.pressure()) if n > 5: display.scroll("Disk Full!", loop=True) # blocks display.scroll("calibrating ") for x in range(calibrate): hc = bme.altitude() offset += hc sleep(10) data = open("flt{}.csv".format(n), "w") data.write("time,altitude\n") offset = hc / calibrate delay = running_time() while True: td = running_time() - delay # will be zero
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
i.fill(2) i.blit(TEST, -100, -100, 50, 50, 1, 1) assert eq(i, Image('22:20:20:20:20:20:20')) def test_crop(): assert eq(TEST.crop(-1, -1, 2, 2), Image('00:04')) assert eq(TEST.crop(1, 1, 2, 2), Image('55:56')) assert eq(TEST.crop(4, 4, 3, 3), Image('400:000:000')) def test_shift(): assert eq(TEST, TEST.shift_left(0)) assert eq(TEST, TEST.shift_up(0)) for n in range(-6, 7): assert eq(TEST.shift_left(n), TEST.shift_right(-n)) assert eq(TEST.shift_up(n), TEST.shift_down(-n)) assert eq(TEST.shift_left(1), Image('44440:55540:56540:55540:44440')) assert eq(TEST.shift_down(1), Image('00000:44444:45554:45654:45554')) try: display.scroll("blit") test_blit() display.scroll("crop") test_crop() display.scroll("shift") test_shift() print("Image test: PASS") display.show(Image.HAPPY) except Exception as ae: display.show(Image.SAD) raise
def scroll(string, delay=150, loop=False, monospace=False): display.scroll(string, delay, wait=False, loop=loop, monospace=monospace) yield from sleep(delay * 5 * (len(string) + 1))
# microbit module let you control the board components and sensors from microbit import display # This text will scroll on the 5x5 matrix display display.scroll('Hello PyCon Italy')
tool = 0 peers = set() receives = 0 radio.on() while True: #if accelerometer.was_gesture('shake'): if button_a.was_pressed(): tool = random.randrange(3) #display.clear() #sleep(1000) #display.show(tool) display.clear() display.scroll('%s' % len(peers)) display.show(tools[tool]) sleep_time = random.randint(200, 500) print('sleep time: %s' % sleep_time) if receives >= 10: print('sending: %s %s' % (my_id, tool)) radio.send('%s %s' % (my_id, tool)) receives = 0 incoming = radio.receive() receives += 1 print(incoming)
plot(ballX, ballY, brightness[2]) # Turn-on LED (ball) at new position # Other cases where ball is either rising or falling else: # Debug code: print("ballX =" + str(ballX)) # View print() output using REPL plot(oldBallX, oldBallY, brightness[0]) # Turn-off LED at old position plot(ballX, ballY, brightness[2]) # Turn-on LED at new position # Make ball speed-up as it falls and slow-down as it rises. delay = 128 - 8 * ballX sleep(delay) if button_a.is_pressed(): display.scroll(hitCount) # Show current score # End of "while gameOn:" loop # =========================== display.scroll("Game Over,") if hitCount >= maxScore: display.scroll(" You won.") display.show(hapFace) else: display.scroll(" Micro:bit won.") display.show(sadFace) sleep(3000) reset() # Start a new game. # EOF
while not gameOver: for i in range(0, 5): shipX = shipX - 1 if (A.is_pressed() and shipX > 0) else shipX shipX = shipX + 1 if (B.is_pressed() and shipX < 58) else shipX mv_stmp(shipX0, 23, shipX, 23, ship) shipX0 = shipX x, y, v = starX[i], starY[i], speed[i] stmp = starStamp[star[i]] if y + v > 23: score += 1 draw_stamp(x, y, stmp, 0, 1) s, x, v = init_star(i) star[i] = s stmp = starStamp[s] starX[i] = x starY[i], speed[i], y = -v, v, -v if y == -v: y0 = 0 else: y0 = y y = y + v starY[i] = y mv_stmp(x, y0, x, y, stmp) if y > 19: if not ((x + 4 < shipX or shipX + 4 < x) or (y + 7 < 27 or 31 < y + 4)): show_bitmap("game_over") D.scroll("Score: " + str(score)) gameOver = True 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
from microbit import display length = float(input('Enter length: ')) width = float(input('Enter width: ')) square_footage = length * width print('Your room size is {0} square feet.'.format(square_footage)) display.scroll('Your room size is {0} square feet.'.format(square_footage))
from microbit import display display.scroll("Hello, World!")