Example #1
0
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 playGame(self):
        microbit.display.scroll("WALK TO PICK UP ITEMS.")

        pickup_amount = 4

        while self.game_running:

            self.startLevel(pickup_amount)
            level_start_time = microbit.running_time()  # Store the time when the user starts a level.

            # Execute a traditional game loop.
            while not self.isGameOver():
                self.getInput()
                self.update()
                self.draw()

                if self.isGameOver():
                    current_time = microbit.running_time()  # Get the time at gameover.
                    seconds_elapsed = (current_time - level_start_time) / 1000  # Convert milliseconds to seconds.

                    # Display the time it took to complete the level, cut off any decimal places from the print-out.
                    microbit.display.scroll("TIME:" + str(int(seconds_elapsed)) + " SECONDS.")

                    pickup_amount += 1

                sleep(100)
Example #3
0
    def playGame(self):
        microbit.display.scroll("WALK TO PICK UP ITEMS.")

        pickup_amount = 4

        while self.game_running:

            self.startLevel(pickup_amount)
            level_start_time = microbit.running_time()

            while not self.isGameOver():
                self.getInput()
                self.update()
                self.draw()

                if self.isGameOver():
                    current_time = microbit.running_time()
                    seconds_elapsed = (current_time - level_start_time) / 1000

                    microbit.display.scroll("TIME:" +
                                            str(int(seconds_elapsed)) +
                                            " SECONDS.")

                    pickup_amount += 1

                sleep(100)
Example #4
0
def get_distance():
    np[7] = (0, 0, bright)
    np.show()

    timeout = False
    start = microbit.running_time()
    rising_edge = start
    falling_edge = start

    sonar.write_digital(0)
    microbit.sleep(1000)
    sonar.write_digital(1)  # Send 10us pulse to trigger
    microbit.sleep(0.01)
    sonar.write_digital(0)

    while sonar.read_digital() == 0 and not timeout:
        rising_edge = microbit.running_time()
    while sonar.read_digital() == 1 and not timeout:
        falling_edge = microbit.running_time()

    if timeout:
        distance = 0
        np[7] = (bright, 0, 0)
    else:
        pulse_width = falling_edge - rising_edge
        distance = pulse_width * 17150
        np[7] = (0, bright, 0)
    np.show()
    return int(distance)
Example #5
0
def get_ident(wait=1000):
    max_ident = 0
    loading_display = microbit.Image(BLANK_IMAGE)
    wait /= 25

    configure_radio()
    for pixel in sorted(range(25), key=lambda x: random.random()):
        start = microbit.running_time()
        message = radio.receive_bytes()
        while message:
            try:
                sender, *_ = message
                max_ident = max(max_ident, sender)
            except ValueError:
                pass

            message = radio.receive_bytes()

        loading_display.set_pixel(pixel % 5, pixel // 5, 9)
        microbit.display.show(loading_display)
        end = microbit.running_time() - start
        if end < wait:
            microbit.sleep(wait - end)

    microbit.display.scroll("#{}".format(max_ident + 1))
    return max_ident + 1
def animate_sin(operation):
    brightness_max = 9
    half_brightness_max = brightness_max / 2
    two_pi = math.pi * 2

    origo_x, origo_y = 2, 2

    max_distance = hypot(origo_x, origo_y)
    double_max_distance = max_distance * 2
    offset = 0
    last_t = microbit.running_time()

    while True:
        for x in range(0, 5):
            dist_x = x - origo_x
            for y in range(0, 5):
                dist_y = y - origo_y

                distance = (math.fabs(hypot(dist_x, dist_y)) /
                            double_max_distance)
                distance = (distance + (offset / operation)) % 1

                sin = math.sin(distance * two_pi - math.pi)

                value = round(sin * half_brightness_max + half_brightness_max)

                microbit.display.set_pixel(x, y, value)

        t_now = microbit.running_time()
        delta_t = t_now - last_t
        offset += delta_t * 0.001
        last_t = t_now
        microbit.sleep(10)
Example #7
0
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()
Example #8
0
def test_timing():
    # test that speech takes the correct amount of time over many runs
    print('Testing timing of say function')
    for i in range(5):
        start = microbit.running_time()
        speech.say('hello world')
        microbit.sleep(1)
        stop = microbit.running_time()
        assert 800 < stop - start < 815
Example #9
0
def noise(length_ms):
    """Random noise"""

    end_time = round(microbit.running_time() + length_ms)

    while microbit.running_time() < end_time:
        microbit.pin0.write_digital(microbit.random(2))

    music.stop()
Example #10
0
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
Example #11
0
def test_timing():
    # test that speech takes the correct amount of time over many runs
    print('Testing timing of say function')
    for i in range(5):
        start = microbit.running_time()
        speech.say('hello world')
        microbit.sleep(1)
        stop = microbit.running_time()
        assert 800 < stop - start < 815
Example #12
0
def process_local_generated_events():
    if button_b.was_pressed():
        send_and_expect_response(RESET_MESSAGE)
    elif button_a.was_pressed():
        send_and_expect_response(ALERT_MESSAGE)
    elif status['status'] != ALERT_MESSAGE:
        if running_time() > status['last_reset'] + ALERT_DELAY:
            send_and_expect_response(ALERT_MESSAGE)
        if running_time() > status['last_heartbeat'] + HEARTBEAT_PERIOD:
            send_and_expect_response(HEARTBEAT_MESSAGE)
Example #13
0
    def play(self, pattern, kit=None):
        if kit:
            self.midiout.program_change(kit, ch=self.channel)
            # give MIDI instrument some time to load drumkit
            sleep(300)

        while True:
            last_tick = running_time()
            pattern.playstep(self.midiout, self.channel)
            timetowait = max(0, self.mpq - (running_time() - last_tick))
            if timetowait > 0:
                sleep(timetowait)
Example #14
0
def wait_for_change(timeout=500):
    t_start = microbit.running_time()
    while microbit.running_time() < t_start + timeout:
        if i2c_read(I2C_ADDR, 0x00)[0] & 1:  # Read status register
            button_state = i2c_read(I2C_ADDR, 0x03)[0]  # Read input states
            i2c_write(I2C_ADDR, 0x00, 0x00)  # Clear status register

            states = {}
            for x in range(6):
                states[x] = (button_state & (1 << x)) > 0

            return states
    return None
Example #15
0
def reset(msg):
    global position, last_proc, speed, map_position, obstacles, vspeed
    global max_obstacles, start_time
    obstacles = set()
    map_position = 0
    speed = 1.0
    vspeed = 0
    position = 2
    last_proc = microbit.running_time()
    microbit.display.scroll(msg)
    microbit.sleep(1000)
    max_obstacles = 5
    start_time = microbit.running_time()
Example #16
0
def sensors():
    global timer1, ___numberVar, ___booleanVar, ___stringVar, ___imageVar, ___numberList, ___booleanList, ___stringList, ___imageList
    microbit.display.scroll(str(microbit.button_a.is_pressed()))
    microbit.display.scroll(str(microbit.button_b.is_pressed()))
    microbit.display.scroll(
        str("up" == microbit.accelerometer.current_gesture()))
    microbit.display.scroll(
        str("down" == microbit.accelerometer.current_gesture()))
    microbit.display.scroll(
        str("face down" == microbit.accelerometer.current_gesture()))
    microbit.display.scroll(
        str("face up" == microbit.accelerometer.current_gesture()))
    microbit.display.scroll(
        str("shake" == microbit.accelerometer.current_gesture()))
    microbit.display.scroll(
        str("freefall" == microbit.accelerometer.current_gesture()))
    microbit.display.scroll(str(microbit.compass.heading()))
    microbit.display.scroll(str((microbit.running_time() - timer1)))
    timer1 = microbit.running_time()
    microbit.display.scroll(str(microbit.temperature()))
    microbit.display.scroll(str(microbit.pin0.is_touched()))
    microbit.display.scroll(str(microbit.pin1.is_touched()))
    microbit.display.scroll(str(microbit.pin2.is_touched()))
    microbit.display.scroll(str(microbit.pin0.read_analog()))
    microbit.display.scroll(str(microbit.pin1.read_analog()))
    microbit.display.scroll(str(microbit.pin2.read_analog()))
    microbit.display.scroll(str(microbit.pin3.read_analog()))
    microbit.display.scroll(str(microbit.pin4.read_analog()))
    microbit.display.scroll(str(microbit.pin10.read_analog()))
    microbit.display.scroll(str(microbit.pin0.read_digital()))
    microbit.display.scroll(str(microbit.pin1.read_digital()))
    microbit.display.scroll(str(microbit.pin2.read_digital()))
    microbit.display.scroll(str(microbit.pin3.read_digital()))
    microbit.display.scroll(str(microbit.pin4.read_digital()))
    microbit.display.scroll(str(microbit.pin5.read_digital()))
    microbit.display.scroll(str(microbit.pin6.read_digital()))
    microbit.display.scroll(str(microbit.pin7.read_digital()))
    microbit.display.scroll(str(microbit.pin8.read_digital()))
    microbit.display.scroll(str(microbit.pin9.read_digital()))
    microbit.display.scroll(str(microbit.pin10.read_digital()))
    microbit.display.scroll(str(microbit.pin11.read_digital()))
    microbit.display.scroll(str(microbit.pin12.read_digital()))
    microbit.display.scroll(str(microbit.pin13.read_digital()))
    microbit.display.scroll(str(microbit.pin14.read_digital()))
    microbit.display.scroll(str(microbit.pin15.read_digital()))
    microbit.display.scroll(str(microbit.pin16.read_digital()))
    microbit.display.scroll(str(microbit.pin19.read_digital()))
    microbit.display.scroll(str(microbit.pin20.read_digital()))
    microbit.display.scroll(str(microbit.accelerometer.get_x()))
    microbit.display.scroll(
        str(round(microbit.display.read_light_level() / 2.55)))
def Ultrasonic_ranging():
    Trig, Echo = pin12, pin13
    global Distance
    start_time = 0
    if (running_time() - start_time > 100):
        Trig.write_digital(0)
        Trig.write_digital(1)
        utime.sleep_us(2)
        Trig.write_digital(0)
        t1 = time_pulse_us(Echo, 1, 5000)
        t2 = t1 / 1000000
        print("\r" + ":{:5.2f}cm".format(t2 * 34300 / 2), end='')
        Distance = int(t2 * 34300 / 2)
        start_time = running_time()
Example #18
0
 def count_claps():
     t = running_time()
     lastr = 900
     claps = 0
     while running_time() - t < 1000:
         r = pin0.read_analog()
         if lastr > 500 and r < 100:
             t = running_time()
             sleep(100)
         elif lastr < 100 and r > 500:
             t = running_time()
             sleep(100)
             claps += 1
         lastr = r
     return claps
Example #19
0
def waitForACK(timer=2000, pooling_interval=10):
    """
	Waits for acknowledgement for given amount of time
	@param timer            : Maximum waiting time for the acknowledgement
	@param pooling_interval : Interval to check for acknowledgement
	@returns                : Received acknowledgement
							  NACK for timeout
	"""
    initial_time = running_time()
    while (running_time() - initial_time) < timer:
        response = radio.receive()
        if response is not None:
            return response
        sleep(pooling_interval)
    return NACK
Example #20
0
def fx(length_ms, pitch, delta_pitch, steps_count):
    """Produce sound effect shifting pitch by delta_pitch in steps_count steps"""
    end_time = round(microbit.running_time() + length_ms)

    step_length_ms = round(length_ms / steps_count)

    while microbit.running_time() < end_time:
        if pitch > 0:
            music.pitch(round(pitch))
        microbit.sleep(step_length_ms)

        pitch += delta_pitch
        steps_count -= 1

    music.stop()
Example #21
0
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)
Example #22
0
def game_over(dry_time):
    score = str(int((microbit.running_time() - dry_time) / 1000))
    while True:
        display.show(Image.SAD)
        sleep(2000)
        display.scroll("Score: " + score)
    return
    def play(self, pattern, kit=None):
        # channel volume
        self.midiout.control_change(10, self.volume, ch=self.channel)
        self.activate_drumkit(kit)
        # give MIDI instrument some time to load drumkit
        sleep(300)

        try:
            while True:
                last_tick = running_time()
                pattern.playstep(self.midiout, self.channel)
                timetowait = max(0, self.mpt - (running_time() - last_tick))
                if timetowait > 0:
                    sleep(timetowait)
        finally:
            # all sound off
            self.midiout.control_change(120, 0)
Example #24
0
def reset():
    display.clear()
    status.update({
        'showing_error': False,
        'last_reset': running_time(),
        'last_heartbeat': 0,
        'status': HEARTBEAT_MESSAGE,
    })
Example #25
0
def send():
    display.clear()
    radio.on()
    radio.config(channel=90, power=4)
    if "sample.raw" in os.listdir():
        gen = sample_generator("sample.raw")
    else:
        gen = sawtooth_generator()
    start = running_time()
    sent = 0
    for f in gen:
        # One frame every 4ms = 8kHz
        while sent > ((running_time() - start) >> 2) + 3:
            sleep(1)
        radio.send_bytes(f)
        sent += 1
    print(sent)
Example #26
0
def send():
    display.clear()
    radio.on()
    radio.config(channel=90, power=4)
    if "sample.raw" in os.listdir():
        gen = sample_generator("sample.raw")
    else:
        gen = sawtooth_generator()
    start = running_time()
    sent = 0
    for f in gen:
        # One frame every 4ms = 8kHz
        while sent > ((running_time() - start) >> 2) + 3:
            sleep(1)
        radio.send_bytes(f)
        sent += 1
    print(sent)
Example #27
0
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)
Example #28
0
    def wait_and_display_pwm(self, duty_cycle_value, on_time):
        start = microbit.running_time()
        width = round(on_time / 15)
        hits = range(0, width, round(DUTY_100PC / duty_cycle_value))
        points = [('#' if i in hits else '.') for i in range(width)]
        while True:
            microbit.sleep(1)
            duration = microbit.running_time() - start
            progress_left = 1 - (duration / on_time)
            points_left = int((width * progress_left)) + 1

            while points and len(points) > points_left:
                point = points.pop(0)
                print(point, end='', flush=True)

            if duration >= on_time:
                break
        print()
Example #29
0
def variable_requested(var):
    global next_var_requested_time
    requested = False
    now = running_time()
    if now > next_var_requested_time:
        requested = True
        next_var_requested_time = now + 20000
        print("Hub to Node -> Command: {}".format(var))
    return requested
Example #30
0
def variable_changed(var):
    global next_var_checked_time
    changed = False
    now = running_time()
    if now > next_var_checked_time:
        changed = True
        next_var_checked_time = now + 15000
        print("Hub to Node -> Command: {}".format(var))
    return changed
Example #31
0
    def wait_and_display_pwm(self, duty_cycle_value, on_time):
        start = microbit.running_time()
        width = round(on_time / 15)
        hits = range(0, width, round(DUTY_100PC / duty_cycle_value))
        points = [('#' if i in hits else '.') for i in range(width)]
        while True:
            microbit.sleep(1)
            duration = microbit.running_time() - start
            progress_left = 1 - (duration / on_time)
            points_left = int((width * progress_left)) + 1

            while points and len(points) > points_left:
                point = points.pop(0)
                print(point, end='', flush=True)

            if duration >= on_time:
                break
        print()
Example #32
0
def command_received(cmd):
    global next_cmd_time
    received = False
    now = running_time()
    if now > next_cmd_time:
        received = True
        next_cmd_time = now + 5000
        print("Hub to Node -> Command: {}".format(cmd))
    return received
Example #33
0
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)
Example #34
0
def should_move_ball():
    now = mb.running_time()
    previous = state["ball_update"]
    delta = now - previous

    if state["ball_pos"] and delta > TIME_INCREMENT:
        state["ball_update"] = now
        return True
    else:
        return False
Example #35
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()
Example #36
0
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])
Example #37
0
 def wait(self):
     # """Wait for something to happen."""
     while True:
         if self.check_death():
             break
         self.check_gesture()
         self.check_button()
         current = microbit.running_time()
         delta = current - self.last_time
         if delta > INTERVAL:
             self.last_time = current
             self.tick()
            # Note: The Microbit uses different indexing for LEDs
            microbit.display.set_pixel(column, row, leds[row][column])

#display_leds = display_leds_image_string
display_leds = display_leds_image_array
#display_leds = display_leds_set_pixel

def waves(delay):
    
    for offset in range(1000):
        for row in range(5):
            for column in range(5):
                x = (row + offset) % 8 / 4 * math.pi
                leds[row][column] = int(
                    math.sin(x) * 4 + 4)
        display_leds()
        microbit.sleep(delay)
        offset += 1
        #print ('Offset: %i' % offset)
        #print ('Offset: {}'.format(offset))
        if microbit.button_a.is_pressed():
            delay = max(0, delay - 10)
        if microbit.button_b.is_pressed():
            delay += 10

#waves(100)
t0 = microbit.running_time()
waves(0)
t1 = microbit.running_time()
print ('Ran for %i ms' % (t1 - t0))
Example #39
0
def sleep(millis):
    t = microbit.running_time()
    while microbit.running_time() < t + millis:
        check_input()
        yield
Example #40
0
    player_x = 2

    wall_y = -1
    hole = 0

    score = 0
    handled_this_wall = False

    wall_speed = wall_min_speed
    player_speed = player_min_speed

    wall_next = 0
    player_next = 0

    while True:
        t = m.running_time()
        player_update = t >= player_next
        wall_update = t >= wall_next
        if not (player_update or wall_update):
            next_event = min(wall_next, player_next)
            delta = next_event - t
            m.sleep(delta)
            continue

        if wall_update:
            # calculate new speeds
            speed = min(score, speed_max)
            wall_speed = wall_min_speed + int((wall_max_speed - wall_min_speed) * speed / speed_max)
            player_speed = player_min_speed + int((player_max_speed - player_min_speed) * speed / speed_max)

            wall_next = t + wall_speed
Example #41
0
def sleep(msecs):
    t = microbit.running_time()
    while microbit.running_time() < t + msecs:
        yield
Example #42
0
    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
exposure = 4.0 # seconds

frame_wait_ms = int(1000*exposure/number_of_columns)


# image that contains window of the banner
image = microbit.Image(5, 5)

# current banner ptr
banner_ptr = 0

banner_ptr_end = len(banner)

# main loop
while True:
    start_frame_ms = microbit.running_time()

    #  display current banner window
    ptr = banner_ptr

    for y in range(5):
        for x in range(5):
            image.set_pixel(y, 4-x, banner[ptr])
            ptr += 1

        # wrap around
        if ptr >= banner_ptr_end:
            ptr = 0

    # display the image
    microbit.display.show(image)
Example #44
0
ALL_SPOTS = frozenset(
    {(x, y) for x in range(0, MAX_X) for y in range(0, MAX_Y)})


while True:
    snake_x = 0
    snake_y = 0
    snake_tail = []

    # up = 0, right = 1, down = 2, left = 3
    direction = 1

    apple_x = snake_x
    apple_y = snake_y
    apple_time = microbit.running_time()

    score = -1

    microbit.display.clear()

    while True:
        a_was_pressed = microbit.button_a.was_pressed()
        b_was_pressed = microbit.button_b.was_pressed()

        if (snake_x, snake_y) == (apple_x, apple_y):
            score += 1
            spots = list(ALL_SPOTS - set(snake_tail) - {(snake_x, snake_y)})
            if spots:
                apple_x, apple_y = random.choice(spots)
                apple_time = microbit.running_time()