Пример #1
0
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
Пример #2
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
Пример #3
0
    def getAcceleration(self):
        x = accelerometer.get_x()
        y = accelerometer.get_y()
        z = accelerometer.get_z()

        acceleration = math.sqrt(x**2 + y**2 + z**2)

        return acceleration
Пример #4
0
def main():
    display.show(Image.HAPPY)

    while True:
        if button_a.is_pressed():
            y = accelerometer.get_y()
            mouse.scroll(y // 100)
            sleep(300)
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
    def getAcceleration(self):
        x = accelerometer.get_x()
        y = accelerometer.get_y()
        z = accelerometer.get_z()

        acceleration = math.sqrt(x ** 2 + y ** 2 + z ** 2)  # ** means make this a power of.

        return acceleration
Пример #7
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)
Пример #8
0
def main():
    display.show(Image.HAPPY)

    while True:
        if button_a.is_pressed():
            x = accelerometer.get_x()
            y = accelerometer.get_y()
            mouse.move_relative(x // 10, y // 10)
            sleep(50)

        if button_b.is_pressed():
            mouse.left_click()
            sleep(500)
Пример #9
0
def level():
    global row, col
    bright = 4
    for x in range(1, 5):
        display.set_pixel(x, 0, 0)
    for y in range(0, 5):
        display.set_pixel(0, y, 0)
    row = accelerometer.get_x()  #pitch 2 row
    row = min(max(1,
                  int(row / 200) + 2),
              4)  # roll sensitivity row/60=narrow 400=wide + tilt factor
    display.set_pixel(row, 0, bright)
    col = accelerometer.get_y()  # roll 4 bit cols
    col = min(
        max(3,
            int(col / 200) + 2),
        4)  #pitch sensitivity 200 horizontal 300 more vertical + tilt factor
    display.set_pixel(0, col, bright)
Пример #10
0
    def upright_check(self):

        upright = False

        for _ in range(3):

            reading = accelerometer.get_y()

            upright = reading > 800

            if upright:
                break

            self.maqueen.motor_stop(LEFT_MOTOR)
            self.maqueen.motor_stop(RIGHT_MOTOR)

            sleep(100)

        if not upright:
            self.state = STATE_REVERSE
Пример #11
0
    def update(self):
        # Move the droplet around the board based on the accelerometer
        x_reading = accelerometer.get_x()
        if x_reading > 20:
            delta_x = 1
        elif x_reading < -20:
            delta_x = -1
        else:
            delta_x = 0

        y_reading = accelerometer.get_y()
        if y_reading > 20:
            delta_y = 1
        elif y_reading < -20:
            delta_y = -1
        else:
            delta_y = 0

        # Move the tail along
        self.x[2] = self.x[1]
        self.x[1] = self.x[0]
        self.y[2] = self.y[1]
        self.y[1] = self.y[0]

        # Update x and y and check for boundaries
        self.x[0] = self.x[0] + delta_x
        if (self.x[0] > 4):
            self.x[0] = 4
        elif (self.x[0] < 0):
            self.x[0] = 0

        self.y[0] = self.y[0] + delta_y
        if (self.y[0] > 4):
            self.y[0] = 4
        elif (self.y[0] < 0):
            self.y[0] = 0
Пример #12
0
from microbit import display, Image, accelerometer, sleep
import radio
radio.on()
radio.config(channel=7)

while True:
    readingy = accelerometer.get_y()
    readingx = accelerometer.get_x()

    if readingy > 550:
        display.show(Image.ARROW_S)
        radio.send('b')
        sleep(100)

    elif readingy < -550:
        display.show(Image.ARROW_N)
        radio.send('f')
        sleep(100)

    elif readingx < -550:
        display.show(Image.ARROW_W)
        radio.send('l')
        sleep(100)

    elif readingx > 550:
        display.show(Image.ARROW_E)
        radio.send('r')
        sleep(100)

    else:
        display.show("-")
Пример #13
0
            x, tempx = tempx, x  #distance negotiated, using this mortars suggestion
            radio.send("READY")
            break
    radio.send(str(tempx))  #send distance suggestion
    display.show("zz", wait=False)
display.show("3 2 1 ")  #count down to start

while alive:  #this mortar is not yet hit
    h = radio.receive()
    angcount += 1
    if angcount >= 400:  #slow down angle checks without blocking execution
        angle, zangle = getangle()
        display.show("A")  # Alive
        sleep(500)
        display.set_pixel(0, 0, 8)
        a_deg = accelerometer.get_y(
        ) / 11.4  #get approximate angle for display purpose
        a_bin = bin(int(
            a_deg))  #Convert whole degrees to binary as string e.g. 3 = "0b11"
        for n, v in enumerate(a_bin[2:]):
            display.set_pixel(
                n, 3, v * 8)  #Visualize angle in binary notation (led on = 1)
        #display.show(accelerometer.get_y()/11.4, delay=450)
        sleep(200)
    velocity = 0
    vdelta = 1  #used for trimming velocity change while aiming
    while button_a.is_pressed(
    ):  #release button a when velocity is desired value
        velocity += 1 * vdelta
        display.show(velocity)
        sleep(370)
        if velocity == 5 or velocity == 1:  #time to change count direction
Пример #14
0
LEN_CUTOFF2 = len(CUTOFF_X2)

use_cutoff = 2

### SETTINGS END ###

from microbit import accelerometer, button_b, pin1, pin2, display, Image, sleep
import math
import utime
#import music

# variables
current_sec = float(utime.ticks_ms())/1000.  # some reference time in ms
# read in currect accel data
accel = math.sqrt(float(accelerometer.get_x())**2
                        + float(accelerometer.get_y())**2
                        + float(accelerometer.get_z())**2)

window_values = [0] * RAVG_AVG_WIN
amplitude_window_values = [0] * RAVG_AMP_WIN
stepspermin_window_values = [0] * RAVG_AMP_WIN
count = 0
count_amplitude = 0
accel_avg = 0.
#peak_resolution_accel = 50
peaks_sec = [current_sec, current_sec, current_sec]
peaks = [-1, -1, -1]
current_peak = 0
nr_peaks = 3
valleys_sec = [current_sec, current_sec, current_sec]
valleys = [2000, 2000, 2000]
Пример #15
0
plot = Kitronik128x64DisplayPlot()

graphYMax = 32
graphYMin = 12
graphYRange = graphYMax - graphYMin
variableMax = 2000
variableMin = -2000
variableRange = variableMax - variableMin

screenRatio = graphYRange / variableRange
x = 0
y = 0
length = 0

while True:
    yPlot = accelerometer.get_y()

    plot.display_as_text("      ", 0, 0)
    plot.display_as_text(yPlot, 0, 0)

    yPlotMapped = graphYMax - ((yPlot - variableMin) * screenRatio)
    yPlotMapped = round(yPlotMapped)

    if x == 0:
        previousYPlot = yPlotMapped

    if yPlotMapped < previousYPlot:
        y = yPlotMapped
        length = (previousYPlot - yPlotMapped)
    elif yPlotMapped > previousYPlot:
        y = previousYPlot
Пример #16
0
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

    display.clear()

    # Get accelerometer's x-axis and y-axis values so we can move
    # the paddle around using accelerometor's x,y coordinates
    xVal = accelerometer.get_x()
    yVal = accelerometer.get_y()

    # =======================
    #  Paddle Movement Code:
    # =======================

    # Save previous paddle "x,y" location.
    oldPadX = padX
    oldPadY = padY

    # Relative to the previous position of the lit pixel,
    # calculate x-axis change (if any) of the lit pixel.
    if xVal > gestureSensitivity:
        padX = oldPadX + 1
    elif xVal < -gestureSensitivity:
        padX = oldPadX - 1
Пример #17
0
def get_xy():
    yaccel = accelerometer.get_y() * accelerometer_sensitivity
    xaccel = accelerometer.get_x() * accelerometer_sensitivity
    return yaccel, xaccel
Пример #18
0
    (0, 1),
    (2, 0),
    (3, 0),
    (4, 0),
    (3, 0),
    (0, 0),
    (0, 1),
    (2, 0),
]

terrain_multiplier = 5
pos = 0

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
display.clear()
audio.play(Sound.SPRING)
sleep(500)
numbers = ('One', 'Two', 'Three')
for i in range(3, 0, -1):
    display.show(i)
    speech.say(numbers[i - 1], speed=500, pitch=50, throat=100, mouth=50)
    sleep(750)

set_volume(volume)

while score < max_score:
    shake = max(
        0,
        abs(accelerometer.get_x()) + abs(accelerometer.get_y()) +
        abs(accelerometer.get_z()) - 2048)
    level = min(
        max(0, level - drop_level + translate(shake, 0, 2048, 0, add_level)),
        max_level)
    pitch = round(translate(level, 0, max_level, 440, 880))
    plotBarGraph(level, max_level)
    if level == max_level:
        level = 0
        score += 1
        music.stop()
        sleep(50)
        display.show(Image.YES)
        music.play(music.BA_DING)
        sleep(450)
        continue
Пример #20
0
         soundPlay = False
         if button_a.was_pressed():
             display.show(flash, delay=100, wait=False)
             sleep(random.randint(50, 350))
             radio.send("end")
             break
         if pin0.is_touched():
             
             display.show(flash, delay=100, wait=False)
             sleep(random.randint(50, 350))
             soundPlay = True
         if soundPlay:
             choice = "1"
         else:
             choice = "0"
         radio.send(choice + "," + str(accelerometer.get_y()) + "," + str(direction))
         sleep(50)
         
 elif b is True:
     radio.send(slave)
     while True:
         direction = compass.heading()
         soundPlay = False
         if button_b.was_pressed():
             radio.send("end")
             break
         if pin0.is_touched():
             soundPlay = True
         if soundPlay:
             choice = "1"
         else:
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

    display.clear()

    # Get accelerometer's x-axis and y-axis values so we can move
    # the paddle around using accelerometor's x,y coordinates
    xVal = accelerometer.get_x()
    yVal = accelerometer.get_y()

    # =======================
    #  Paddle Movement Code:
    # =======================

    # Save previous paddle "x,y" location.
    oldPadX = padX
    oldPadY = padY

    # Relative to the previous position of the lit pixel,
    # calculate x-axis change (if any) of the lit pixel.
    if xVal > gestureSensitivity:
        padX = oldPadX + 1
    elif xVal < -gestureSensitivity:
        padX = oldPadX - 1
Пример #22
0
            self.x += 1

    def move_left(self):
        if not self.y == 0:
            self.y -= 1

    def move_right(self):
        if not self.y == 4:
            self.y += 1
            

screen = Screen()
pointer = Pointer()

while True:
    sleep(25)
    if accelerometer.get_x() < -200:
        pointer.move_left()
    if accelerometer.get_x() > 200:
        pointer.move_right()
    if accelerometer.get_y() < -200:
        pointer.move_up()
    if accelerometer.get_y() > 200:
        pointer.move_down()
    if button_a.was_pressed():
        screen.toggle(pointer.x, pointer.y)
    if button_b.was_pressed():
        screen.publish()
    screen.display(pointer)
    sleep(25)
def rotationRoll():
    return atan2(
            accelerometer.get_x(), 
            sqrt(accelerometer.get_y() ** 2 + accelerometer.get_z() ** 2)
            ) * (180 / pi)
Пример #24
0
def read_y():
    i2c.write(MMA8653_ADDR, bytes([MMA8653_OUT_Y_MSB]), repeat=True)
    result = i2c.read(MMA8653_ADDR, 1)
    # Unpack it as a signed char
    result = ustruct.unpack('b', result)[0]
    # Scale it to 0 to +/- 2000 and set orientation
    return result * 16 * -1


def read_z():
    i2c.write(MMA8653_ADDR, bytes([MMA8653_OUT_Z_MSB]), repeat=True)
    result = i2c.read(MMA8653_ADDR, 1)
    # Unpack it as a signed char
    result = ustruct.unpack('b', result)[0]
    # Scale it to 0 to +/- 2000
    return result * 16


check_device()
configure_device()

while True:
    x = read_x()
    y = read_y()
    z = read_z()
    print("[X:{}] [Y:{}] [Z:{}]".format(x, y, z))
    print("[X:{}] [Y:{}] [Z:{}]\n".format(
        accelerometer.get_x(), accelerometer.get_y(), accelerometer.get_z()))
    sleep(200)
def get_xy():
    yaccel = accelerometer.get_y() * accelerometer_sensitivity
    xaccel = accelerometer.get_x() * accelerometer_sensitivity
    return yaccel, xaccel
Пример #26
0
    (0, 1),
    (2, 0),
    (3, 0),
    (4, 0),
    (3, 0),
    (0, 0),
    (0, 1),
    (2, 0),
]

terrain_multiplier = 5
pos = 0

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
Пример #27
0
def getangle():
    """ Accelerometer y output for first quadrant range 0-1024 """
    """    ~11.378 steps/degree (1024 steps / 90 degrees )   """
    return math.radians(accelerometer.get_y() / 11.378), accelerometer.get_z(
    )  #translate y angle to radians, z for backward shooting check (z should always be negative or zero if shooting straight up)
Пример #28
0
        break

while True:

    while True:
        command = random.choice(commands)
        display.scroll(command[:2])

        start = running_time()
        diff = 0
        correct = False

        # Get current state for comparison
        start_bearing = compass.heading()
        start_x = accelerometer.get_x()
        start_y = accelerometer.get_y()
        while diff < WAIT_TIME:

            if command == "bop it":
                if button_a.is_pressed() and button_b.is_pressed():
                    correct = True
                    break
            elif command == "twist it":
                print(abs(compass.heading() - start_bearing))
                if abs(compass.heading() - start_bearing) >= 90:
                    correct = True
                    break
            elif command == "shake it":
                if accelerometer.current_gesture() == "shake":
                    correct = True
                    break
Пример #29
0
def read_y():
    i2c.write(MMA8653_ADDR, bytes([MMA8653_OUT_Y_MSB]), repeat=True)
    result = i2c.read(MMA8653_ADDR, 1)
    # Unpack it as a signed char
    result = ustruct.unpack('b', result)[0]
    # Scale it to 0 to +/- 2000 and set orientation
    return result * 16 * -1


def read_z():
    i2c.write(MMA8653_ADDR, bytes([MMA8653_OUT_Z_MSB]), repeat=True)
    result = i2c.read(MMA8653_ADDR, 1)
    # Unpack it as a signed char
    result = ustruct.unpack('b', result)[0]
    # Scale it to 0 to +/- 2000
    return result * 16


check_device()

while True:
    x = read_x()
    y = read_y()
    z = read_z()
    print("[X:{}] [Y:{}] [Z:{}]".format(x, y, z))
    print("[X:{}] [Y:{}] [Z:{}]\n".format(accelerometer.get_x(),
                                          accelerometer.get_y(),
                                          accelerometer.get_z()))
    sleep(200)