Exercise: Rodeo

3.9. Exercise: Rodeo#

  1. Navigate to the MicroPython editor https://python.microbit.org/v/3. If you already have it open, then use that existing window or tab.

  2. Connect your micro:bit using the instructions on the previous page

  3. Enter the following code into the editor

from microbit import *
import utime


def ultrasound_measure():
    pin1.write_digital(1)
    utime.sleep_us(10)
    pin1.write_digital(0)

    timeout = utime.ticks_us()
    while True:
        pulseBegin = utime.ticks_us()
        if 1 == pin2.read_digital():
            break
        if (pulseBegin - timeout) > 5000:
            return -1

    while True:
        pulseEnd = utime.ticks_us()
        if 0 == pin2.read_digital():
            break
        if (pulseEnd - pulseBegin) > 5000:
            return -2

    x = pulseEnd - pulseBegin
    d = x / 58
    return int(d)


def motor_left(speed, direction):
    buf = bytearray(3)
    buf[0] = 0x00
    buf[1] = direction
    buf[2] = speed
    i2c.write(0x10, buf)


def motor_right(speed, direction):
    buf = bytearray(3)
    buf[0] = 0x02
    buf[1] = direction
    buf[2] = speed
    i2c.write(0x10, buf)


i2c.init()

while True:
    sleep(1000)
  1. Flash the code to your micro:bit.

If you get stuck ask a peer or your teacher for help!

Question 1

Extend the code so that:

  • the Maqueen does a square dance i.e. moves in a continuous clockwise square pattern

Solution
from microbit import *
import utime

def ultrasound_measure():
    pin1.write_digital(1)
    utime.sleep_us(10)
    pin1.write_digital(0)

    timeout = utime.ticks_us()
    while True:
        pulseBegin = utime.ticks_us()
        if 1 == pin2.read_digital():
            break
        if (pulseBegin-timeout) > 5000:
            return -1

    while True:
        pulseEnd = utime.ticks_us()
        if 0 == pin2.read_digital():
            break
        if (pulseEnd-pulseBegin) > 5000:
            return -2

    x = pulseEnd - pulseBegin
    d = x / 58
    return int(d)

def motor_left(speed, direction):
    buf = bytearray(3)
    buf[0] = 0x00
    buf[1] = direction
    buf[2] = speed
    i2c.write(0x10, buf)

def motor_right(speed, direction):
    buf = bytearray(3)
    buf[0] = 0x02
    buf[1] = direction
    buf[2] = speed
    i2c.write(0x10, buf)

i2c.init()

while True:
    motor_left(125, 0)
    motor_right(125, 0)
    sleep(1000)
    motor_left(255, 0)
    motor_right(255, 1)
    sleep(250)
Question 2

Extend the code so that:

  • the Maqueen acts like a charging bull. It should slowly rotate on the spot. When it detects an object within range it will charge at the object until the object moves out of the way.

Solution

Solution is locked