Basic micropi scripts


#1

*** Buttons and external LED ***
from microbit import *
while True:
if button_a.is_pressed():
display.clear()
display.show(Image.HAPPY)
pin2.write_digital(1) # turn pin0 (and the LED) on
sleep(3000)
display.clear()
display.show(Image.ANGRY)
pin2.write_digital(0) # turn pin0 (and the LED) off

*** Microbit ubpside down and right way up ***
from microbit import *

while True:
gesture = accelerometer.current_gesture()
if gesture == “face up”:
display.show(Image.HAPPY)
else:
display.show(Image.ANGRY)

*** Buttons!!! ***
from microbit import *

while True:
if button_a.is_pressed():
display.show(Image.HAPPY)
elif button_b.is_pressed():
break
else:
display.show(Image.SAD)

display.clear()

*** Motion sensor and button - little game thingy ***:
from microbit import *
import random
tilt_x = 3
tilt_y = 3
bright = 1
apple_x = random.randint(0, 4)
apple_y = random.randint(0, 4)
display.set_pixel(tilt_x, tilt_y, bright)
display.set_pixel(apple_x, apple_y, 3)
while True:
display.clear()
reading_x = accelerometer.get_x()
reading_y = accelerometer.get_y()
if reading_x > 20:
if tilt_x < 4:
tilt_x += 1
if reading_x < -20:
if tilt_x > 0:
tilt_x -= 1
if reading_y > 20:
if tilt_y < 4:
tilt_y += 1
if reading_y < -20:
if tilt_y > 0:
tilt_y -= 1
if tilt_x == apple_x:
if tilt_y == apple_y:
bright += 1
apple_x = random.randint(0, 4)
apple_y = random.randint(0, 4)
if bright == 10:
display.show(Image.HAPPY)
sleep(5000)
bright = 1
display.clear
if button_a.is_pressed():
bright = 1
tilt_x = 3
tilt_y = 3
display.clear
if button_b.is_pressed():
display.show(Image.SAD)
sleep(5000)
break
display.set_pixel(apple_x, apple_y, 9)
display.set_pixel(tilt_x, tilt_y, bright)
sleep(500)


#2

Thanks Tom,

are these written in python under Mu?

I have been having no end of difficulty trying to make even simple code run on the microbit - things like reading the state of a pin from an external sensor, writing PWM to a servo output etc. These things should be simple (they ARE on an arduino !) but they just don’t seem to work the way I expect on the microbit??.

For example - the syntax seems to be (and the editor accepts) :

pin3.set_analog_period_microseconds(1600)

Which should, by my reckoning, set that servo running at full speed*. Instead, it hunts and stops and starts almost randomly. Trying it with two at once and only one works at all !

There are tons of worked examples using the blocks editor, but that runs so slowly I’d rather avoid it entirely, micropython trumps it for sure.

(*) The MG 995 servos have a dead band about 10uS either side of 1500uS, and then respond fairly well up to about 80uS either side, anything over 80 is full speed. (1512uS creeps, 1540uS is approx half speed)