def stop(self): display.show(Image.HAPPY) for i in range(5): self.np[i] = (0, 0, 0) self.np.show() self.motor_right.read_digital() self.motor_left.read_digital()
def launch(): global f, st n = len(listdir()) f = open("alt{}.csv".format(n - 2), "w") st = ticks_ms() d.show(Image.TRIANGLE) return 3
def find_clearing(self): display.show(Image.CONFUSED) direction = random.choice([True, False]) attempts = 0 while self.state == STATE_FIND_CLEARING: attempts += 1 if attempts > 30: direction = not direction attempts = 0 distance = self.maqueen.read_distance() if direction: self.maqueen.motor_run(LEFT_MOTOR, FORWARDS, 50) self.maqueen.motor_run(RIGHT_MOTOR, BACKWARDS, 50) else: self.maqueen.motor_run(LEFT_MOTOR, BACKWARDS, 50) self.maqueen.motor_run(RIGHT_MOTOR, FORWARDS, 50) sleep_for = 200 if attempts > 60 else 100 sleep(sleep_for) if distance > 50 and distance is not 0: self.state = STATE_MOVING self.upright_check()
def on_in_walk_region(stepspermin_avg): global walking_good, twalk_bad, twalk_badlast, \ notify_bad_walk, standing_still if stepspermin_avg <= 80: # not walking standing_still = True display.show(Image.ARROW_N) twalk_badlast = sec if walking_good: # we were walking good, now bad as not fast enough walking_good = False twalk_bad = sec elif sec - twalk_bad > NOTIFY_AFTER_X_SEC_BAD: # notify after X sec of standing still notify_bad_walk = True else: # not in toewalk and not standing still. All is good! display.show(Image.SQUARE_SMALL) # we might have been walking bad, unset if long enough walking good if not walking_good: #unset walking bad if last walking bad was X sec ago if sec - twalk_badlast > UNSET_BAD_AFTER_X_SEC_GOOD: walking_good = True notify_bad_walk = False
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 decode_direction(dirstring): """ Decode the dir_X and show the arrow """ needle = dirstring.split("dir_")[1] img = getattr(Image, "ARROW_{}".format(needle)) display.show(img)
def start(self): while self.health > 0: display.show(self.display_health()) if button_a.is_pressed(): self.attack() sleep(500) display.show(Player.DEAD)
def count_down(delay): """Count down and show progress""" on_image = Image('99999:99999:99999:99999:99999') display.show(on_image) for y_coord in range(5): for x_coord in range(5): wait = delay while wait >= 300: sleep(300) wait -= 300 if abandon_talk() is True: return # Flash the last row, so making it clear that # the talk is coming to an end if y_coord == 4: for i in range(x_coord, 5): brightness = display.get_pixel(i, y_coord) if brightness == 0: brightness = 9 else: brightness = 0 display.set_pixel(i, y_coord, brightness) sleep(wait) display.set_pixel(x_coord, y_coord, 0) start_up_screen() return
def motor_on(self, motor, direction, speed=100): """ Turn motor with the given direction and speed :param motor: KMotor.MOTOR1 or KMotor.Motor2 :param direction: KMotor.FORWARD or KMOTOR.REVERSE :param speed: 0 - 100 :return: """ # make sure the speed is within range if not 0 <= speed <= 100: # not display a "NO" and return display.show(Image.NO) return # speed needs to be scaled from 0-100 to 0-1023 speed = self._scale(speed) # Move Motor Forward if direction == KMotor.FORWARD: if motor == KMotor.MOTOR_1: pin8.write_analog(speed) pin12.write_digital(0) elif motor == KMotor.MOTOR_2: pin0.write_analog(speed) pin16.write_digital(0) # Move Motor In Reverse else: if motor == KMotor.MOTOR_1: pin12.write_analog(speed) pin8.write_digital(0) elif motor == KMotor.MOTOR_2: pin16.write_analog(speed) pin0.write_digital(0)
def __init__(self): self.km = KMotor() display.show(Image.HAPPY) self.dispatch = { 'fwd': self.go_forward, 'rev': self.go_reverse, 'left': self.go_left, 'right': self.go_right, 'spin_right': self.spin_right, 'spin_left': self.spin_left, 'stop': self.stop, } radio.on() while True: if not pin15.read_digital(): self.go_reverse() sleep(1000) self.go_right() sleep(1000) self.stop() cmd = radio.receive() if cmd is None: pass else: op = self.dispatch.get(cmd, None) if op: op()
def output(data): radio.send(str(data)) data = str(data) if len(data) == 1: display.show(data) else: display.scroll(data)
def start_server(): while True: client_connected = radio.receive() if client_connected == "SYN": display.show(Image.ARROW_NW) radio.send("ACK") return True
def take_damage(self, damage): if (random.randint(0, 10) / 10.0) <= self.hitProb: self.health -= (int(damage)) else: pass display.show(Player.SHIELD) sleep(500)
def deal_with_command(s): if s[0] != ID: return 0 if s[1] != ord(b'S') and s[1] != ord(b'R') and s[1] != ord(b'Q'): return 0 if s[1] == ord(b'S'): for i in range(4, 8, 1): speed[i - 4] = s[i] set_car_speed() st = struct.pack('4s4B6i', s[0:4], speed[0], speed[1], speed[2], speed[3], compass.get_x(), compass.get_y(), compass.get_z(), accelerometer.get_x(), accelerometer.get_y(), accelerometer.get_z()) uart.write(st) sleep(20) if s[1] == ord(b'R'): display.show(Image.SAD) uart.write('+++') for i in range(4, 8, 1): speed[i - 4] = 0 set_car_speed() sleep(1000) reset() return 1
def heartbeat(): status['last_heartbeat'] = running_time() throb_base = Image('90000:00000:00000:00000:00000') throb = [throb_base * (i / 9) for i in range(1, 9)] throb += [throb_base * (i / 9) for i in range(8, -1, -1)] display.show(throb, delay=100, wait=False, loop=False, clear=False)
def wake(self): self.comm.send_command("start_fight", 1) display.show(Image("00900:00900:00900:00000:00900")) sleep(500) for x in range(11): display.show(Image.ANGRY.shift_right(x - 5)) sleep(200)
def generate_question(self, grid, player): """ Method to generate a question Params: grid: object player: object Returns: bool """ self.__ask_random_question(questions) random_location = (x, y) = self.__generate_random_numbers(grid) if self.random_question and random_location == player.location: display.show(Image.SURPRISED) say('You found gold!', speed=self.SAY_SPEED) say('Answer the question correctly.', speed=self.SAY_SPEED) say(self.random_question, speed=self.SAY_SPEED) say('Press the aay button for {0}.'.format(self.answer_1), speed=self.SAY_SPEED) say('Press the lowgo for {0}.'.format(self.answer_2), speed=self.SAY_SPEED) say('Press the bee button for {0}.'.format(self.answer_3), speed=self.SAY_SPEED) display.show(Image.HAPPY) return True else: return False
def zombie(): # Become mass murdering zombie display.show(Image.ANGRY) music.play(music.NYAN, wait=False) for x in range(0, 5): for y in range(0, 5): radio.send('%d%d' % (x, y)) sleep(600)
def beat_box(sound): if sound: display.show(Image.HEART) sleep(10) display.clear() speech.pronounce(sound) else: sleep(gap)
def motor_stop(self, motor): buffer = bytearray([motor, FORWARDS, 0]) try: i2c.write(0x10, buffer) except OSError: display.show(Image.SAD)
def main(): display.show(Image.HAPPY) while True: if button_a.is_pressed(): y = accelerometer.get_y() mouse.scroll(y // 100) sleep(300)
def wait_start(): global uids, lid while True: if button_a.was_pressed(): di.show("F") uids = find_used_ids() gnid(uids) break
def start_countdown(count=3): """Play a countdown animation for the specified number of seconds.""" for i in range(count, 0, -1): display.show(str(i)) play('C:1') sleep(1000) play('A:3') display.clear()
def display(self, pointer): if self.blink: screen.toggle(pointer.x, pointer.y) display.show(self.image()) if self.blink: screen.toggle(pointer.x, pointer.y) self.blink = 0 else: self.blink = 1
def backward(self): display.show(Image.ARROW_S) self.np[1] = self.np[2] = self.np[3] = (LIGHT_LEVEL, 0, 0) self.np[0] = self.np[4] = (0, 0, 0) self.np.show() self.motor_right.set_analog_period(20) self.motor_left.set_analog_period(20) self.motor_right.write_analog(100) self.motor_left.write_analog(50)
def speak(to_say): global FACES words = to_say.split(" ") index = 0 for word in words: display.show(FACES[index]) speech.say(word) sleep(10) index = 1 - index
def anim(): while 1: with open('anim0.txt', 'r') as _f: for _ in range(60): content = _f.readline() display.show(Image(content.strip())) sleep(100) if button_a.was_pressed() or button_b.was_pressed(): return
def send_AT(mSend, mRec1, mRec2=b""): while True: uart.write(mSend) sleep(100) if uart.any(): s = uart.readall() if s == mRec1 or s == mRec2: break display.show(Image.HAPPY) sleep(200)
def transition(self, state, event, timers): if state == "off": if event == "shake": display.show(Image.SQUARE) timers.start("t1", 2000) return "on" elif state == "on": if event == "t1": display.show(Image.SQUARE_SMALL) return "off"
def menu_mode(): """ Principal menu mode """ while True: display.show(Image.HAPPY) radio.send("ready") if button_a.is_pressed(): send_direction()
def blink(sprite, board): images = [] for value in range(1, 10): image = board.copy() for x, y in sprite: image.set_pixel(x, y, value) images.append(image) images.extend(reversed(images)) display.show(images, delay=75, loop=True, wait=False)
def game_over(move): radio.send("gg") radio.off() images = [ICONS[move], Image(" ")] display.show(images, loop=True, wait=False) sleep(3000) display.show(Image.SAD) shutdown()
def transition(self, state, event, timers): if state == "off": if event == "t1": if display.read_light_level() > 100: display.show(Image.SQUARE) timers.start("t1", 1000) return "on" else: timers.start("t1", 1000) return "off"
def sync(): display.show(Image.ALL_CLOCKS, delay=100, loop=True, wait=False) n = random.randrange(1, 10000) radio.send(str(n)) message = None while not message: sleep(500) message = radio.receive() return n < int(message)
def add_new_move(): display.show("?") move = read_move() while not move: move = read_move() display.show(ICONS[move]) radio.send(move) sequence.append(move) sleep(2000)
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 receive_new_move(): wait_animation() move = radio.receive() while move not in ICONS: sleep(100) move = radio.receive() display.show(ICONS[move]) sequence.append(move) # other player lost the game if move == "gg": radio.off() shutdown()
def transmit(img): """The `microbit.display.show` function on steroids Image of size 10 x 10 will be divided into following fragments: +-------+-------+ | | | | 0 | 1 | | | | +-------+-------+ | | | | 2 | 3 | | | | +-------+-------+ 0 - local screen (also sent on BASE_CHANNEL + 0 for mirroring capability) 1 - screen on the BASE_CHANNEL + 1 2 - screen on the BASE_CHANNEL + 2 ... n - screen on the BASE_CHANNEL + n """ assert img.width() == img.height() assert img.height() % SCREEN_SIZE == 0 fragment_count = img.width() // SCREEN_SIZE for y in range(fragment_count): for x in range(fragment_count): # Extract a fragment from the original image frag = img.crop( x * SCREEN_SIZE, y * SCREEN_SIZE, SCREEN_SIZE, SCREEN_SIZE ) # switch the radio channel channel = BASE_CHANNEL + (y * fragment_count) + x radio.config(channel=channel, length=251) # Display the image locally if fragment == 0 if x == 0 and y == 0: display.show(img)
def attack(board): target = [(1, 1)] while True: target = position(target, board, send=True) if board.get_pixel(*target[0]) == 0: break radio.send("fire") sleep(500) message = radio.receive() if message == "gg": game_over(Image.HAPPY) value = 8 if message == "hit" else 2 board.set_pixel(target[0][0], target[0][1], value) display.show(board) sleep(2000)
def receive(): """Starts a receiver program""" radio.on() channel_idx = 0 while True: # Handle the display switching # A for prev channel, B for next channel channel_selector = button_incdec() if channel_selector != 0: # Switch the channel channel_idx = (channel_idx + channel_selector) % MAX_DISPLAY_IDX radio.config(channel=BASE_CHANNEL + channel_idx, length=251) radio.on() # Give the user some feedback display.show(str(channel_idx)) sleep(750) display.clear() msg = radio.receive() if msg: # TODO: validate that we have received a valid frame try: display.show(eval(msg)) except Exception as e: display.show(Image.SAD) print(repr(e))
def task_2(): yield from sleep(1000) display.show(Image.CLOCK2) yield from sleep(2000) display.show(Image.CLOCK4) yield from sleep(2000) display.show(Image.CLOCK6)
def defend(board): message = None while message != "fire": if message: x, y = (int(i) for i in message) blink([(x, y)], board) sleep(100) message = radio.receive() hit = board.get_pixel(x, y) == 8 board.set_pixel(x, y, 2) display.show(board) if hit: if "8" in repr(board): radio.send("hit") else: radio.send("gg") game_over(Image.SAD) else: radio.send("miss") sleep(2000)
def main(): #"""Run on start.""" game = Game() game.run() score_str = str(game.score) display.show("GAME OVER You Scored %s" % score_str) sleep(1) while 1: display.show("--- %s ---" % score_str) display.show(Image.HAPPY) sleep(1)
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 read_sequence(): display.show(Image("0:0:35753:0:0")) start = running_time() for i in range(len(sequence)): move = read_move() while not move: move = read_move() # check time if running_time() - start > (i + 1) * 5000: game_over("timeout") # is the move correct? if move == sequence[i]: display.show(ICONS[move]) sleep(500) display.show(Image("0:0:34543:0:0")) sleep(300) else: game_over(sequence[i])
def loop() : r_id, cmd = gr.recv() if r_id is None : return if cmd == 'finish' : dp.show( Image.HEART) return # END if int( r_id) != gr.get_id() : return # it's not my biz. if cmd == 'fire' : msleep( WAIT_MS) if gr.get_id() != MEMBERS : dp.show( Image.HAPPY) gr.send( cmd) else : # I am anchor :) dp.show( Image.HEART) gr.send( 'finish')
def hdr_ba() : dp.show( Image.HAPPY)
from microbit import display, Image # a few preloaded images are # available inside the Image class display.show(Image.PACMAN)
def game_over(image): display.show(image) radio.off() while True: sleep(10000) display.off()
while True: sleep(100) if -256 < accelerometer.get_y() < 450: bird = max(0, bird - 1) elif 568 < accelerometer.get_y() < 1024: bird = min(4, bird + 1) display.clear() display.set_pixel(0, bird, 9) pos_terrain = pos // terrain_multiplier lost_status = False for column, (top, bottom) in enumerate( terrain[pos_terrain:pos_terrain + 5]): for y in range(top): display.set_pixel(column, y, 4) if column == 0 and bird == y: lost_status = True for y in range(bottom): display.set_pixel(column, 4 - y, 4) if column == 0 and bird == (4 - y): lost_status = True if lost_status: display.show(Image.SAD) music.play(music.FUNERAL) reset() pos += 1 if pos_terrain > len(terrain): pos = 0
# A micro:bit Firefly. # By Nicholas H.Tollervey. Released to the public domain. import radio import random from microbit import display, Image, button_a, sleep # Create the "flash" animation frames. Can you work out how it's done? flash = [Image().invert()*(i/9) for i in range(9, -1, -1)] # The radio won't work unless it's switched on. radio.on() # Event loop. while True: # Button A sends a "flash" message. if button_a.was_pressed(): radio.send('flash') # a-ha # Read any incoming messages. incoming = radio.receive() if incoming == 'flash': # If there's an incoming "flash" message display # the firefly flash animation after a random short # pause. sleep(random.randint(50, 350)) display.show(flash, delay=100, wait=False) # Randomly re-broadcast the flash message after a # slight delay. if random.randint(0, 9) == 0: sleep(500) radio.send('flash') # a-ha
plot(16, padY, brightness[4]) # ===================== # Ball Movement Code: # ===================== # Save previous ball "x,y" location oldBallX = ballX oldBallY = ballY ballX = ballX + ballDirection # Case where paddle hit ball if ballX >= 16 and padY == ballY: display.show(hapFace) sleep(250) 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(15, -1, -1): plot(i, ballY, brightness[2]) sleep((128 - 8 * i) * 2) plot(i, ballY, brightness[0]) plot(16, padY, brightness[0]) # Turn-off paddle LED gameOn = False
def show(self): #"""Update the game screen.""" image = Image(self.sky + self.cannon_row) display.show(image)
assert os.listdir() == [ "test1.txt", "test2.txt" ] os.remove("test1.txt") os.remove("test2.txt") assert not os.listdir() def test_many_files(): for i in range(80): name = "%d.dat" % i write_data_to_file(name, i*3, 16, 4) verify_file(name, data_stream(i*3), 16, 4, 'b') for i in range(80): os.remove("%d.dat" % i) name = "_%d.dat" % i write_data_to_file(name, i*3, 16, 4) verify_file(name, data_stream(i*3), 16, 4, 'b') for i in range(80): os.remove("_%d.dat" % i) assert not os.listdir() display.clear() try: clear_files() test_small_files() test_many_files() test_text_file() print("File test: PASS") display.show(Image.HAPPY) except Exception as ae: display.show(Image.SAD) raise
def task_1(): display.show(Image.CLOCK1) yield from sleep(2000) display.show(Image.CLOCK3) yield from sleep(2000) display.show(Image.CLOCK5)
def loop() : dp.show( Image.SAD)
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 wait_animation(): images = [Image("0:0:00{0}00:0:0".format(i)) for i in range(2, 10)] images.extend(reversed(images)) display.show(images, delay=75, loop=True, wait=False)
deadzone_x = 200 deadzone_y = 200 flag = True def get_sensor_data(): x = accelerometer.get_x() y = accelerometer.get_y() z = accelerometer.get_z() a = button_a.was_pressed() b = button_b.was_pressed() print(x, y, z, a, b) return x, y while True: sleep(100) x, y = get_sensor_data() # Display direction output. if x < (0 - deadzone_x): display.show(Image.ARROW_W, wait=False) if x > deadzone_x: display.show(Image.ARROW_E, wait=False) if y < (0 - deadzone_y): display.show(Image.ARROW_N, wait=False) if y > deadzone_y: display.show(Image.ARROW_S, wait=False) if x > (0 - deadzone_x) and x < deadzone_x and y > (0 - deadzone_y) and y < deadzone_y: display.show(Image.HAPPY, wait=False)