Buttons

Create a new sketch and upload the following code to read the button presses in the Serial Console

Open up the Serial console at 9600 baud and press the reset button on the back of the microbit to restart the software

You will see the welcome message and then try pressing some buttons!

Take note: Button A is to the right of the LEDs on the Sino:bit, while button B is to the left.

    const int buttonA = 5;     // the number of the pushbutton pin
const int buttonB = 11;     // the number of the pushbutton pin

void setup() {  
  Serial.begin(9600);
  Serial.println("microbit is ready!");
  
  pinMode(buttonA, INPUT);  
  pinMode(buttonB, INPUT);   
}

void loop(){
  if (! digitalRead(buttonA)) {
    Serial.println("Button A pressed");
  }
  if (! digitalRead(buttonB)) {
    Serial.println("Button B pressed");
  }
  delay(10);
}
  

If you include sinobit.h, you can use constants it defines for the buttons:

#include <sinobit.h>

void setup() {  
  Serial.begin(9600);
  Serial.println("microbit is ready!");
  
  pinMode(SINOBIT_BUTTON_A, INPUT);  
  pinMode(SINOBIT_BUTTON_B, INPUT);   
}

void loop(){
  if (! digitalRead(SINOBIT_BUTTON_A)) {
    Serial.println("Button A pressed");
  }
  if (! digitalRead(SINOBIT_BUTTON_B)) {
    Serial.println("Button B pressed");
  }
  delay(10);
}

NOTE:

The button signals are what we call "active low" meaning that the button input is low (i.e. false) when the button is pressed and high (i.e. true) when it isn't.

Last updated on 2017-12-06 at 04.34.11 PM Published on 2017-12-06 at 04.57.43 PM