Programming the micro:bit with MicroPython
Putting It All Together
This article demonstrates only a handful of the methods available in the microbit module, but even this limited toolbox can be used to put the micro:bit board to a wide range of practical and creative uses. If you happen to have a camera that can be triggered with a shutter release cable, you can wire the cable to the micro:bit and use the MicroPython script in Listing 5 to turn micro:bit into a programmable intervalometer [5].
Listing 5
Intervalometer Script
01 from microbit import * 02 a = 0 03 b = 0 04 while True: 05 if button_a.is_pressed(): 06 a = a + button_a.get_presses() 07 display.scroll(str(a)) 08 if button_b.is_pressed(): 09 b = b + button_b.get_presses() 10 display.scroll(str(b)) 11 gesture = accelerometer.current_gesture() 12 if gesture == "shake": 13 while (a > 0): 14 display.scroll(str(a)) 15 display.show(Image.ASLEEP) 16 pin8.write_digital(1) 17 sleep(500) 18 pin8.write_digital(0) 19 sleep(b*1000) 20 display.clear() 21 a = a - 1 22 else: 23 display.scroll("All done!")
While the script is running, use button A to specify the number of shots and button B to define an interval between shots in seconds. Shaking the board triggers a shooting session, and when the operation is complete, the LED array displays the All done! message. As you can see, the script uses many of the methods described in this article. The button_a.get_presses()
and button_b.get_presses()
routines are used to count button presses, and the accelerometer.current_gesture()
method detects the shake gesture. The display.show()
and display.scroll()
routines gives you visual feedback, and the pin8.write_digital()
method controls the GPIO pin 8 that triggers the shutter.
Final Word
Although the BBC micro:bit is designed as a learning tool for children, its versatility and simplicity make it a great platform for all sorts of creative projects. Better still, the dedicated microbit module lets you integrate micro:bit's functionality into your Python scripts with a minimum of effort. In this article, I have only covered micro:bit's basics, so make sure to read the BBC micro:bit MicroPython documentation [6] to get more out of this nifty board.
Infos
- BBC micro:bit: http://www.microbit.co.uk
- BBC micro:bit World: http://microbitworld.me
- Mu editor: http://codewith.mu
- Code in this article: ftp://ftp.linux-magazine.com/pub/listings/raspberry-pi-geek.com/19
- Intervalometer: https://en.wikipedia.org/wiki/Intervalometer
- BBC micro:bit MicroPython documentation: http://microbit-micropython.readthedocs.io/en/latest/index.html
« Previous 1 2 Next »
Buy this article as PDF
Pages: 6
(incl. VAT)