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))
Example #2
0
def test_sleep():
    # check that sleep works ok with speech because they both use low-level timers
    # (this is really a test of the audio module)
    print('Testing sleep with speech')
    microbit.sleep(1)
    speech.say('hello world')
    microbit.sleep(1)
Example #3
0
def main():
    x = 0
    y = 0
    tick = 0
    while True:
        tick += 1
        if tick == 4:
            # walk around, with collision detection
            tick = 0
            if ac.get_x() > 200 and get_maze(x + 1, y) == 0:
                x += 1
            elif ac.get_x() < -200 and get_maze(x - 1, y) == 0:
                x -= 1
            elif ac.get_y() > 200 and get_maze(x, y + 1) == 0:
                y += 1
            elif ac.get_y() < -200 and get_maze(x, y - 1) == 0:
                y -= 1
            x = min(15, max(0, x))
            y = min(15, max(0, y))

        # draw the maze
        draw(x, y, tick)


        microbit.sleep(50)
    def move(self):
        #work out where the new segment of the snake will be
        newSegment = [self.tail[0][0], self.tail[0][1]]
        if self.direction == self.UP:
            newSegment[1] -= 1
        elif self.direction == self.DOWN:
            newSegment[1] += 1
        elif self.direction == self.LEFT:
            newSegment[0] -= 1
        elif self.direction == self.RIGHT:
            newSegment[0] += 1

        if self.checkCollision(newSegment[0], newSegment[1]):
            #game over
            snakehead = self.tail[0]
            for flashHead in range(0,5):
                microbit.display.set_pixel(snakehead[0], snakehead[1], self.SNAKEBRIGHTNESS)
                microbit.sleep(200)
                microbit.display.set_pixel(snakehead[0], snakehead[1], 0)
                microbit.sleep(200)
            
            return False
            
        else:
            self.addSegment(newSegment[0], newSegment[1])

            #has the snake eaten the apple?
            if newSegment[0] == self.apple[0] and newSegment[1] == self.apple[1]:
                self.length += 1
                self.score += 10
                self.createApple()

            return True
Example #5
0
def detect_motion():
    x = microbit.io.P0.get_digital_value()
    y = x
    while x == y:
        x = y
        y = microbit.io.P0.get_digital_value()
        microbit.sleep(10)
Example #6
0
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
Example #7
0
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 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 #9
0
    def startGame(self):
        microbit.display.clear()
        self.ox=0
        
       
        self.score = 0
        
        self.bstates0=self.getbuttons()
        
        
        
        playing = True
        
        samples = 0
        self.ctr=0
        self.move=0
        while(playing):
            #keep looping around, if the button is pressed, move the snake immediately, 
            #otherwise move it when the sample time is reached
            self.ctr+=1
            
            
            
            microbit.sleep(self.SAMPLETIME)
            self.updatebuttons()
            moved=0
            if self.bchange[0]==1:
                moved=1
                self.ox+=1
            elif self.bchange[1]==1:
                moved=1
                self.ox-=1

            samples = samples + 1
            if moved or samples >= self.samplespermove:
                self.move+=1
                if self.move%40 ==0:
                    self.samplespermove-=1
                if self.move %50 ==0:
                    self.w-=1
                if self.w<2:
                    self.w=2
                self.score+=10
                self.drawBoard()
                
                #check collision
                left,right=self.board[-1]
                x=2-self.ox
                if x<=left or x>=right:
                    break   
                self.moveBoard()
                samples = 0
            self.drawPlayer()
            #if self.ox<0 and self.ctr>100:
               # break
        #microbit.display.scroll(str(self.ox))
        
        microbit.display.scroll("Score = " + str(self.score), 100)
        microbit.display.clear()
Example #10
0
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 forever_four_buttons():
    while True:
        four_buttons()

        microbit.sleep(10)

        # fade all pixels by one brightness level
        fade_display()
Example #12
0
def animate(image, delay, *, stride=5, start=-5, wait=True, loop=False):
    # TODO: full impl.
    for frame in image:
        for y in range(frame.height()):
            for x in range(frame.width()):
                glow = frame.get_pixel(x, y)
                set_pixel(x, y, glow)
        _microbit.sleep(delay)
Example #13
0
def play_intro(accelerometer_sensitivity=1/300):
    """Play animation of pixel moving side to side."""
    y = 2
    while not button_a.is_pressed():
        for x in [0, 1, 2, 3, 4, 3, 2, 1]:
            set_pixel(x, y)
            delta = accelerometer.get_y() * accelerometer_sensitivity
            y = max(0, min(4, int(y + delta)))
            sleep(100)
Example #14
0
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
Example #15
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 #16
0
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)
Example #17
0
def led_dance(delay):
    dots = [ [0]*5, [0]*5, [0]*5, [0]*5, [0]*5 ]
    while True:
        dots[microbit.random(5)][microbit.random(5)] = 8
        for i in range(5):
            for j in range(5):
                microbit.display.set_pixel(i, j, dots[i][j])
                dots[i][j] = max(dots[i][j] - 1, 0)
        microbit.sleep(delay)
Example #18
0
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()
Example #19
0
def led_dance(delay):
    dots = [ [0]*5, [0]*5, [0]*5, [0]*5, [0]*5 ]
    microbit.display.set_display_mode(1)
    while True:
        dots[microbit.random(5)][microbit.random(5)] = 128
        for i in range(5):
            for j in range(5):
                microbit.display.image.set_pixel(i, j, dots[i][j])
                dots[i][j] = int(dots[i][j]/2)
        microbit.sleep(delay)
Example #20
0
def sync():
    number = random.randrange(1, 10000)
    message = None

    while not message:
        radio.send(str(number))
        sleep(250)
        message = radio.receive()

    return number < int(message)
Example #21
0
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)
Example #22
0
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)
Example #23
0
def wait_for_shake():
    shaken = False
    last = get_accel_total()
    while not shaken:
        this = get_accel_total()
        diff = last - this
        if diff < 0: diff = diff * -1
        if diff > TOLERANCE:
            shaken = True
        last = this
        microbit.sleep(50)
Example #24
0
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 heartbeat(delay):
    
    while True:
        for i in range(10):
            set_point(2, 2, scale=(i + 1)/2)
            display_leds()
            microbit.sleep(delay)    
        if microbit.button_a.is_pressed():
            delay = max(0, delay - 10)
        if microbit.button_b.is_pressed():
            delay += 10
Example #26
0
def half_duty(pulse_width, on, off):
    microbit.pin0.set_analog_period_microseconds(2 * pulse_width)
    print(pulse_width, 2 * pulse_width, end='...')
    try:
        microbit.pin0.write_analog(int(511))
        microbit.sleep(on)
    finally:
        print('#', end='')
        microbit.pin0.write_analog(0)
        print('')
    microbit.sleep(off)
def waves(delay):
    
    offset = 0
    while True:
        for row in range(5):
            for column in range(5):
                leds[row][column] = int(
                    math.sin((row + offset) / 4 * math.pi) * 4 + 4)
        display_leds()
        microbit.sleep(delay)
        offset += 1
        print ('Offset: %i' % offset)
Example #28
0
def pulse_burst(pulse_width, on, off):
    microbit.pin0.set_analog_period_microseconds(PERIOD)
    pulse_value = rescale((0, PERIOD), (DUTY_0PC, DUTY_100PC), pulse_width)
    print(pulse_width, pulse_value, end='...')
    try:
        microbit.pin0.write_analog(int(pulse_value))
        microbit.sleep(on)
    finally:
        print('#', end='')
        microbit.pin0.write_analog(0)
        print('')
    microbit.sleep(off)
Example #29
0
def clock():
    while 1:
        for o in range_up_then_down(bot, top, 100):
            print(' ' * 50, o)
            for n in mn, md, mx, md:
                od = o
                if n == mn:
                    od = round(o * mn_factor)
                if n == md:
                    od = round(o * md_factor)
                pulse_burst(n, od, off)
                print()
                microbit.sleep(pause)
Example #30
0
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)
Example #31
0
#Project 1
#NAME(S): Gaby Ackermann Logan and Tara Donohue
#HOURS SPENT: 1
path = "/Users/gackermannlogan/Documents/Github/project-1-gaby-tara/Step/3"
import microbit as mb
import radio  # Needs to be imported separately

# Change the channel if other microbits are interfering. (Default=7)
radio.on()  # Turn on radio
radio.config(channel=6, length =100)

print('Program Started')
mb.display.show(mb.Image.HAPPY, delay=1000, clear=True)


# Wait for start message before beginning printing
incoming = ''
while not incoming == 'start':
    incoming = radio.receive()
print('start')

while True:
    incoming = radio.receive() # Read from radio

    if incoming is not None: # message was received
        mb.display.show(mb.Image.HEART, delay=100, clear=True, wait=False)
        tuple(incoming)
        print(incoming)

        mb.sleep(10)
Example #32
0
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)
Example #33
0
# -*- coding: utf-8 -*-
"""Read sensor data and broadcast it over radio.
"""

from microbit import display, sleep
import radio

from data import DATA_LENGTH, get_data, data2msg, PERIOD_MS

display.scroll("logger")

radio.config(length=DATA_LENGTH)
radio.on()

while True:
    radio.send(data2msg(get_data()))
    sleep(PERIOD_MS)
Example #34
0
    if button_b.was_pressed():
        radio.send('meh')

    # we store the incoming radio signals so that we can use them
    incoming = radio.receive()

    # if the message isn't blank or we're not receiving a signal
    if incoming is not None:
        
        # Then we look in the dictionary to see what image we should display,
        # the last bit creates the additional animation frames to make it fade
        flash = [image_dict[incoming]*(i/9) for i in range(9, -1, -1)]

        # We wait a small amount of time for dramatic effect, 
        # but we make it random
        sleep(random.randint(50, 350))

        # then we display the full animation on the display
        display.show(flash, delay=100, wait=False)

        # Randomly re-broadcast the flash message after a
        # slight delay. 1 in 10 chance
        if random.randint(0, 9) == 0:
        
            # this bit creates a random message to send back
            message = random.choice(list(image_dict))
            
            # We wait a little while 
            sleep(500)
            
            radio.send(message) # then send the message
Example #35
0
from microbit import sleep, pin12
import neopixel

np = neopixel.NeoPixel(pin12, 4)
while True:
    for i in range(4):
        np[i] = (255, 0, 0)
        np.show()
        sleep(100)
        np.clear()
Example #36
0
import microbit

brightness_up = [i for i in range(0, 9)]
brightness_down = [i for i in reversed(brightness_up)][:-1]
brightness = brightness_up + brightness_down

# E
IMAGE = ("11110:" "10000:" "11100:" "10000:" "11110")

while True:
    for intensivity in brightness:
        image = IMAGE.replace("1", str(intensivity))
        microbit.display.show(microbit.Image(image),
                              delay=0,
                              wait=False,
                              loop=False,
                              clear=False)
        microbit.sleep(100)
Example #37
0
#Step 1: Data Collection
#Mo Liu and Alyssa Attonito
#This section creates a program that allows the microbit to collect and store real-world pendulum data.

#cwd = os.getcwd()

import microbit, math, os, random

filename = "pendulum_data" + str(random.randint(1, 999)) + ".txt"

while not microbit.button_a.is_pressed():
    microbit.sleep(50)

#this function creates a file on the microbit and stores acceleration in x and y directions and time data.
with open(filename, "w") as file:
    start_time = (microbit.running_time()) / 1000
    while not microbit.button_b.is_pressed():
        acceleration_x = (microbit.accelerometer.get_x()) / 1000
        acceleration_y = (microbit.accelerometer.get_y()) / 1000
        microbit.display.show(microbit.Image.HAPPY)
        time = (microbit.running_time()) / 1000 - start_time
        values = str(acceleration_x) + "," + str(acceleration_y) + "," + str(
            time) + "\n"
        file.write(values)
        microbit.sleep(50)
        print(values)
file.close()
Example #38
0
 def preheated(self):
   i2c.write(self.addr,b'\\xfe')
   sleep(10)
   self.isPreheated=True
# Set initial position of pong game's "paddle"
padX = 16
padY = 3

# Display initial paddle
plot(padX, padY, brightness[4])

# Set initial position of pong game's "ball"
ballX = 0
ballY = 6

# Display initial ball, blink ball 3 times
# to attract the player's attention
for i in range(0, 3):
    plot(ballX, ballY, brightness[2])
    sleep(delay)
    plot(ballX, ballY, brightness[0])
    sleep(delay)

ballY = randint(0, 6)
plot(ballX, ballY, brightness[2])
ballDirection = 1  # Falling  (-1 = Rising)
hitCount = 0
gameOn = True

while gameOn:

    # Modify game timing to adjust game "hardness/easiness"
    # sleep(delay)       # Makes game easy
    # sleep(delay//2)    # Not so easy
    # sleep(delay//4)    # Moderate
from microbit import display, Image, accelerometer, sleep

while True:
    if accelerometer.was_gesture("shake"):
        display.show(Image.ANGRY)
        sleep(2000)
    else:
        display.show(Image.HAPPY)
clear_oled()
stamp = create_stamp(Image.HEART)
arrow = create_stamp(Image.ARROW_S)
(x, y, ax, ay, score) = (0, 16, 32, 0, 0)
(x0, y0, ax0, ay0) = (x, y, ax, ay)
while True:
    reading = accelerometer.get_x()
    x = x + 1 if (reading > 20 and x < 58) else x
    x = x - 1 if (reading < -20 and x > 0) else x
    reading = accelerometer.get_y()
    y = y + 1 if (reading > 20 and y < 23) else y
    y = y - 1 if (reading < -20 and y > 0) else y
    if x0 != x or y0 != y:
        move_stamp(x0, y0, x, y, stamp)
        (x0, y0) = (x, y)
    (ay, ax) = (ay + 1, ax) if ay < 31 else (0, randint(0, 58))
    move_stamp(ax0, ay0, ax, ay, arrow)
    (ax0, ay0) = (ax, ay)
    if x == 58:
        x = 0
        score = score + 1
        add_text(2, 3, "Score: " + str(score))
        sleep(1000)
        clear_oled()
    if not ((ax + 5 < x or x + 5 < ax) or (ay + 7 < y + 1 or y + 7 < ay + 1)):
        add_text(2, 1, "GAME OVER")
        add_text(2, 3, "Score: " + str(score))
        sleep(4000)
        clear_oled()
        (score, ay, x) = (0, 0, 0)
Example #42
0
def randomize_image():
    for i in IMAGES:
        if random.random() < 0.3:
            microbit.display.show(i)
            microbit.sleep(50)
Example #43
0
STP_CHC_L = 1023
STP_CHC_H = 3071
STP_CHD_L = 3071
STP_CHD_H = 1023

# Inicialització
i2c.write(PCA9685_ADDRESS, bytearray([MODE1, RESET]))  # Reset
# PWM a 0
i2c.write(PCA9685_ADDRESS, bytearray([ALL_LED_ON_L, on & 0xFF]))
i2c.write(PCA9685_ADDRESS, bytearray([ALL_LED_ON_H, on >> 8]))
i2c.write(PCA9685_ADDRESS, bytearray([ALL_LED_OFF_L, off & 0xFF]))
i2c.write(PCA9685_ADDRESS, bytearray([ALL_LED_OFF_H, off >> 8]))

i2c.write(PCA9685_ADDRESS, bytearray([MODE2, OUTDRV]))
i2c.write(PCA9685_ADDRESS, bytearray([MODE1, ALLCALL]))
sleep(5)  # wait for oscillator
i2c.write(PCA9685_ADDRESS,
          bytearray([MODE1]))  # write register we want to read from first
mode1 = i2c.read(PCA9685_ADDRESS, 1)
mode1 = ustruct.unpack('<H', mode1)[0]
mode1 = mode1 & ~SLEEP  # wake up (reset sleep)
i2c.write(PCA9685_ADDRESS, bytearray([MODE1, mode1]))
sleep(5)  # wait for oscillator

# Freqüència PWM in hertz
prescaleval = 25000000.0  # 25MHz
prescaleval /= 4096.0  # 12-bit
prescaleval /= float(freq_hz)
prescaleval -= 1.0
# print('Setting PWM frequency to {0} Hz'.format(freq_hz))
# print('Estimated pre-scale: {0}'.format(prescaleval))
Example #44
0
# By Nicholas H.Tollervey. Released to the public domain.
import radio
import random
from microbit import display, Image, button_a, button_b, 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()
display.show(flash, delay=100, wait=False)

# Event loop.
while True:
    # Button A sends a "flash" message.
    if button_a.was_pressed() or button_b.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, 10) < 4:
            sleep(random.randint(0, 10000))
            radio.send('flash')
Example #45
0
from microbit import *
import superbit
import microbit
display.show(Image.HAPPY)
superbit.servo270(superbit.S1, 120)
while True:
    if button_a.is_pressed():
        superbit.servo270(superbit.S1, 180)
        microbit.sleep(500)
        superbit.motor_control(superbit.M1, 255, 0)
        superbit.motor_control(superbit.M3, 255, 0)
        microbit.sleep(2000)
        superbit.motor_control(superbit.M1, 0, 0)
        superbit.motor_control(superbit.M3, 0, 0)
        superbit.servo270(superbit.S1, 60)
        microbit.sleep(500)
        superbit.servo270(superbit.S1, 120)
        microbit.sleep(500)
        superbit.motor_control(superbit.M1, -255, 0)
        superbit.motor_control(superbit.M3, -255, 0)
        microbit.sleep(2000)
        superbit.motor_control(superbit.M1, 0, 0)
        superbit.motor_control(superbit.M3, 0, 0)
Example #46
0
    microbit.sleep(2000)
    # Re-initialize again, next round
    goodie = position_goodie()
    tail = {}
    head = (2,2)
    length = 1
    direction = 0
    speed = 1000

# Get ready
random.seed()
restart("GET READY")

while True:
    # don't go too fast, but become faster as we get longer
    microbit.sleep(speed - length * 5)

    # direction change detection. Note that you can cancel a
    # turn if you hit the other button fast enough. But you
    # cannot turn the other way if you've pressed the wrong
    # button.
    if microbit.button_a.was_pressed(): turn_left()
    if microbit.button_b.was_pressed(): turn_right()

    # advance snake. We add the head's position to the tail,
    # then calculate the new position for the head.
    tail[head] = length
    head = new_head()

    # Detect wall hits. Output message and restart if we
    # hit the wall.
Example #47
0
def accel():
    while not button_a.is_pressed():
        p = abs(accelerometer.get_z())
        pitch(p, wait=False)
        sleep(10)
Example #48
0
while True:
    voice = tinybit.getVoicedata()
    if voice < 10:
        tinybit.car_stop()
        np.clear()
        tinybit.car_HeadRGB(0, 0, 0)
        display.show(level_0)
    elif voice >= 10 and voice < 40:
        display.show(level_1)
        tinybit.car_HeadRGB(0, 0, 50)
        np[0] = (255, 0, 0)
        np[1] = (255, 0, 0)
        np.show()
        tinybit.car_spinleft(50)
        sleep(delay)
        tinybit.car_spinright(50)
        sleep(delay)
    elif voice >= 40 and voice < 70:
        display.show(level_2)
        tinybit.car_HeadRGB(50, 50, 50)
        np[0] = (0, 255, 255)
        np[1] = (0, 255, 255)
        np.show()
        tinybit.car_spinleft(60)
        sleep(delay)
        tinybit.car_spinright(60)
        sleep(delay)
    elif voice >= 70 and voice < 110:
        display.show(level_3)
        tinybit.car_HeadRGB(0, 100, 0)
Example #49
0
    memory[progcount] = int(databyte, 2)
    dataWrite(bin00(progcount), 1)
    dataWrite(databyte, 3)


def memRead(progcount=pc):
    global databyte, memory
    databyte = bin00(memory[progcount])
    dataWrite(bin00(progcount), 1)
    dataWrite(databyte)


#main program loop
while True:
    level()
    sleep(200)
    if (button_a.is_pressed()):
        longpress = 0
        clicks = button_b.get_presses()
        clicks = 0
        while button_a.is_pressed():
            sleep(100)  #wait until button released
            longpress = longpress + 1
        #clicks = button_a.get_presses()
        if longpress > 5:  #optons if button down >0.5second
            clicks = button_b.get_presses()
            if clicks == 1:  #run
                run()
                memRead(pc)
            elif clicks == 2:  #load mem.dat
                #i = 0
Example #50
0
def clear(addr):
    _exe(addr, b'ClearScreen')
    sleep(15)
Example #51
0
                    for a in args[2:]:
                        if a.find('.') >= 0:
                            d.append(float(a))
                        else:
                            d.append(int(a))
                    receiving[fromdev]['data'].append(d)
                    send_command(fromdev, CMD_DATA_VECTOR)
            elif cmd == CMD_DATA_END:
                if fromdev not in receiving:
                    error('bad incoming command "{}" - not receiving'.format(
                        msg))
                else:
                    r = receiving[fromdev]
                    save_data(fromdev, r)
                    size = len(r['data'])
                    info('received from {} {} {}'.format(
                        fromdev, r['data_type'], size))
                    send_command(fromdev, CMD_DATA_END)
                    del receiving[fromdev]
            elif cmd == CMD_DATA_RESET:
                if fromdev not in receiving:
                    error('bad incoming command "{}" - not receiving'.format(
                        msg))
                else:
                    info('reset {}'.format(fromdev))
                    del receiving[fromdev]
                    send_command(fromdev, CMD_DATA_RESET)
            else:
                error('bad command name "{}"'.format(cmd))
    m.sleep(RECV_TIMEOUT)
Example #52
0
def run():
    acc = 0  #Accumulator
    regB = 0  #register B
    regC = 0  #register C
    rpc = 0  #temp pc for loop
    global pc, memory, zf
    display.scroll('<')
    while True:
        sleep(500)
        memRead(pc)
        rpc = pc
        if tr:
            display.scroll('a:' + str(acc))
        # implemented 8080 operating codes
        if memory[rpc] == 0x00:  #0: #NOP
            pc = pc + 1
        if memory[rpc] == 0x07:  #7: #RLC rotate left <<
            acc = acc << 1
            pc = pc + 1
        if memory[rpc] == 0x0D:  #13: #DCR_C RegC -1
            regC = regC - 1
            zf = (regC == 0)
            pc = pc + 1
        if memory[rpc] == 0x0F:  #15: #RLR rotate right <<
            acc = acc >> 1
            pc = pc + 1
        if memory[rpc] == 0x32:  #50:   #STA
            memory[memory[pc + 1]] = acc
            pc = pc + 3
        if memory[rpc] == 0x3A:  #58:    #LDA
            acc = memory[memory[pc + 1]]
            pc = pc + 3
        if memory[rpc] == 0x3C:  #60: #INR_A
            acc = acc + 1
            zf = (acc == 0)
            pc = pc + 1
        if memory[rpc] == 0x3D:  #61: #DCR_A
            acc = acc - 1
            zf = (acc == 0)
            pc = pc + 1
        if memory[rpc] == 0x47:  #71 : #MOV_B,A
            regB = acc
            pc = pc + 1
        if memory[rpc] == 0x4F:  #71 : #MOV_C,A
            regC = acc
            pc = pc + 1
        if memory[rpc] == 0x76:  # HLT
            break
        if memory[rpc] == 0x80:  #128:  #ADD
            acc = acc + regB
            pc = pc + 1
        if memory[rpc] == 0xA0:  #61: #ANA_B
            acc = acc & regB
            zf = (acc == 0)
            pc = pc + 1
        if memory[rpc] == 0xA8:  #61: #XRA_B
            acc = acc ^ regB
            zf = (acc == 0)
            pc = pc + 1
        if memory[rpc] == 0xAF:  #61: #XRA_A
            acc = acc ^ acc
            zf = (acc == 0)
            pc = pc + 1
        if memory[rpc] == 0xB0:  #61: #ORA_B
            acc = acc | regB
            zf = (acc == 0)
            pc = pc + 1
        if memory[rpc] == 0xC3:  #195:   #JMP
            pc = memory[pc + 1]
        if memory[rpc] == 0xC2:  #194:   #JNZ
            if zf == False:
                pc = memory[pc + 1]
            else:
                pc = pc + 3
        if button_a.is_pressed():
            break
    display.scroll('>')
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()

    display.show(Image.CONFUSED)
    bme.set_qnh(bme.pressure())
    for x in range(calibrate):
        hc = bme.altitude()
        offset += hc
        sleep(10)

    fn = "flt{}.csv".format(n)
    data = open(fn, "w")
    data.write("time,altitude\n")
    offset = hc / calibrate
    x = 0
    y = 0
    delay = running_time()
    display.clear()

    while True:
        td = running_time() - delay # will be zero

        if not td % 500:
            h = bme.altitude() + offset # compensate for ground error
Example #54
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
            if wall_y < 5:
                # erase old wall
                use_wall_y = max(wall_y, 0)
                for wall_x in range(5):
                    if wall_x != hole:
                        s(wall_x, use_wall_y, 0)
Example #55
0
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 sleep, pin12
import neopixel

np = neopixel.NeoPixel(pin12, 4)
a = [0, 1, 2, 3]
b = [1, 2, 3, 0]
c = [2, 3, 0, 1]
d = [3, 0, 1, 2]
s = [a, b, c, d]
while True:
    for i in range(4):
        np[s[i][0]] = (255, 0, 0)
        np[s[i][1]] = (0, 255, 0)
        np[s[i][2]] = (0, 0, 255)
        np[s[i][3]] = (255, 255, 0)
        np.show()
        sleep(500)
Example #57
0
#Ultrasonic code
from machine import time_pulse_us
import microbit as m

trig = m.pin12
echo = m.pin13

trig.write_digital(0)
echo.read_digital()

while True:
    trig.write_digital(1)
    trig.write_digital(0)
    us = time_pulse_us(echo, 1)
    if us == (-1) or us == (-2):
        print(us)
        print('timeout')
        trig.write_digital(0)
        echo.read_digital()
        m.sleep(1000)
    else:
        t_echo = (us / 1000000)
        dist_cm = (t_echo / 2) * 34300
        print(int(dist_cm))
    m.sleep(100)
Example #58
0
import microbit
while True:
    print(microbit.accelerometer.get_values())
    microbit.sleep(250)
Example #59
0
        self._humidity = h
        self._altitude = 44330.0 * (1.0 - pow(self._pressure / self._qnh,
                                              (1.0 / 5.255)))


if __name__ == "__main__":
    b = bme280()
    while True:
        # Lets use the buttons
        ba = 0  # Button A. Appears HA requires int or float over serial
        bb = 0  # Button B
        if microbit.button_a.is_pressed():
            microbit.display.scroll("A")
            ba = 1
        elif microbit.button_b.is_pressed():
            microbit.display.scroll("B")
            bb = 1

        # Now use the sensors
        t, p, h, a = b.all()
        rounding_digits = 1
        t = round(t, rounding_digits)
        p = round(p, rounding_digits)
        h = round(h, rounding_digits)
        # a = round(a, rounding_digits)
        data_string = """ "T": {t}, "P": {p}, "H": {h}, "ba": {ba}, "bb": {bb}  """.format(
            t=t, p=p, h=h, a=a, ba=ba, bb=bb)  # "A": {a},
        print(""" {""" + data_string + """ } """)
        sleep_sec = 1
        microbit.sleep(sleep_sec * 1000)
Example #60
0
 # off
 if value == 0x00:
     buildingbit.car_HeadRGB(0, 0, 0)
 # up
 elif value == 0x80:
     buildingbit.car_back(speed, speed, 0)
 # down
 elif value == 0x90:
     buildingbit.car_run(speed, speed, 0)
 # light
 elif value == 0x40:
     buildingbit.car_HeadRGB(255, 255, 255)
 # buzzer
 elif value == 0xa0:
     music.pitch(698)
     sleep(400)
     music.stop()
 # +
 elif value == 0x30:
     speed = speed + 40
     if speed > 255:
         speed = 255
         music.pitch(500)
         sleep(300)
         music.stop()
     else:
         music.pitch(226)
         sleep(300)
         music.stop()
 # number 0
 elif value == 0xb0: