ArduinoM0 Button Example


In this example we'll use a button to turn on the LED on PIN 8.
The Arduino board M0 operates on 3.3V. The maximum voltage that the I/O pins can tolerate is 3.3V. The application of a voltage exceeding 3.3V may damage the board.


  • Arduino Board
  • momentary button or switch
  • 10K ohm resistor
  • 220 ohm resistor
  • breadboard
  • a bunch of wires


The button used in this sketch has four pins. Connect a pin of the button to 3.3V, another pin, that nearest, to a resistor of 10kΩ connected to GND of the board. Also connect another pin of the button to the digital Pin 2.
Finally connect the anode of the LED (usually the longer pin) in series to a resistor of 220Ω and connect it to pin 8 of board, as shown in figure.

When unpressed, there isn't connection between the two legs of it, so the pin is connected to ground through the pull-down resistor and we read a LOW value.
When the button is closed (pressed), it makes a connection between its two legs, connecting the pin to 5 volts and we read a HIGH value.

You can also wire this circuit the opposite way, with a pullup resistor keeping the input HIGH, and going LOW when the button is pressed.
If so, the behavior of the sketch will be reversed, with the LED normally on and turning off when you press the button.

If you disconnect the digital I/O pin from everything, the LED may blink erratically. This is because the input is "floating" - that is, it will randomly return either HIGH or LOW. That's why you need a pull-up or pull-down resistor in the circuit.

In the picture is shown the circuit realized using an Arduino M0 Pro.


// these two costants are used to define used PINs
const int buttonPin = 2;// the number of the button pin
const int ledPin =  8;// the number of the LED pin

int buttonState = 0;// variable used for reading the button status

void setup() {
// initialize the LED pin as an output
pinMode(ledPin, OUTPUT);      
// initialize the pushbutton pin as an input
pinMode(buttonPin, INPUT);     

void loop() {
// read the state of the pushbutton value
buttonState = digitalRead(buttonPin);

// check if the pushbutton is pressed and change turn on/off LED
if (buttonState == HIGH) {     
// turn LED on
digitalWrite(ledPin, HIGH);  
else {
// turn LED off
digitalWrite(ledPin, LOW);