Adding More Buttons
If buttons A and B are not enough for your project, you can connect extra buttons to the micro:bit quite simply.
This page shows a simple setup and program to read button presses. Most buttons are based on two pins and can be connected up as you see in the circuit on this page. The same principle can be extended to a lot of toggle, rocker and DIP switches as well as the switches built into some rotary encoders.
One pin of the button should be connected to 3V. The other pin should be connected, via a 10K Ohm resistor, to GND. You read the signal from the button from the button pin that is connected to GND. This will give a 1 when the button is pressed and a 0 when it is not.
The resistor is needed for us to get a clear reading from the button and 10K is the most commonly used value for this kind of circuit.
Here is a simple program that puts an image on the matrix whilst the button is being held down.
- Buttons on your game controllers work like this. The games include code that repeatedly checks whether or not the buttons are being pressed, just like we are doing in our forever loop. This is fine for some things, but not good if you want to do something when the button is pressed and released, you need to work a little harder. For this, make a variable called buttonState and set it to equal the reading from the button. Create another called lastState and make it 0 outside of the loop. A button is considered pressed if buttonState is 1 and lastState is 0. After this if statement, lastState needs to be made equal to buttonState, ready for the next repetition.
- Think about what you want your extra buttons to do. You can use extra buttons as modifiers, like shift or CTRL keys on the keyboard. You could write your program so that a button A press is treated differently if one of your other buttons is pressed at the same time.
- You can connect enough buttons to give you a simple piano-like keyboard that you could use to play different notes on a buzzer or headphone hack.