Clone this wiki locally
# Import the library: from bbio import * def setup(): """ This will be called once before the main loop. """ def loop(): """ This is the main loop of your program. It will be called repeatedly until ctrl-c is pressed, or stop() is called from within. """ # We then pass the two functions to run() to start the program: run(setup, main)
Unlike the Arduino environment it is not required that there be functions explicitly named setup() and loop(), however it is required that run() be passed one callable object to be called once, followed by a second callable object to be called repeatedly.
It is also possible to use PyBBIO without following the setup - loop model:
import bbio for i in range(100): bbio.toggle(bbio.USR3)
PyBBIO may also be used in the interactive Python interpreter, and will automatically run all initialization when imported, as well as all cleanup when the interpreter exits:
Let's thoroughly walk through a simple example of blinking a single led:
First, refer to the pinout here to find a digital pin. we'll use GPIO1_16, which is pin 15 on the P9 header. We'll then connect the anode of an LED to this pin, the cathode to one end of a 330 ohm resistor, and the other end of the resistor to ground, which is pin 1 on the P9 header.
There's only a few lines of code we need to add to the above template to get the LED blinking. First, to keep things straightforward, it's nice to set a variable for the LED instead of passing around GPIO1_16, e.g.:
LED = GPIO1_16
Then we'll want to set the LED pin as an output in our setup routine. This is done with the
To set the state of the LED we could use the
digitalWrite() function, but since all we're doing is toggling the state of the pin, we can just use the
And we'll also want to add a bit of a time delay into the loop using the
delay() function so we can actually see the LED blinking; it takes a delay in milliseconds as an argument.
When we put it all together:
from bbio import * LED = GPIO1_16 def setup(): pinMode(LED, OUTPUT) def loop(): toggle(LED) delay(500) run(setup, loop)
Then save and run it; you should see your LED blinking.
Be sure to look through the examples in