Skip to content

Buttons, LEDS and Serial

This week I tried to do something more ambitious, but Fab Academy wouldn’t let me, as the assignment would not accept accept the use of a breadboard. So I made a small program that turns on LEDs and send serial communication trough the USB to my computer.

Setup

To program on RP2040, I first had to tell Arduino IDE how to talk with it. I first installed the board to Arduino IDE by clicking Tools -> Board -> Board Manager and installing the board from the device list on the left hand side. Search functionaly came handy for this.

If the board is not there, you could go to the preferences (CMD + , on MacOS), and adding and URL for the board in the Additional boards manager URLs: field. I added https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json to it, to include the correct RP2040 libraries to it.

Then before uploading the code, I needed to select the correct board from Tools -> Board -> Rasberry PI Pico/RP2040 -> Seeed XIAO RP2040, and the correct USB connection from Tools -> Port -> /dev/cu.usbmodem142301 or some other usb connection you might have active at the moment. Sometimes Arduino IDE might even recognize your board, and show its name in the list of ports.

The code

#define BUTTON_PIN 27
#define LED_PIN 26

bool led_state = false;
bool button_down = false;

void setup() {
  // put your setup code here, to run once:

  pinMode(BUTTON_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);

  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:

  if (digitalRead(BUTTON_PIN) == HIGH) {
    if (button_down == false) {
      button_down = true;
      led_state = !led_state;
      digitalWrite(LED_PIN, led_state ? HIGH : LOW);
      Serial.write("LED blinked\n");
    }
  } else {
    button_down = false;
  }

}

Defined pins for the LED and the button. That caused a bit of a problem, as the pins in the board do not match the pins that need to be written to the code. The Xiao RP2040 pinout shows the pins that are on the board, and also the pins on the chip. I needed to use the chips pins.

The variable button_down exists so that the loop does not check the pin state multiple times per button press. It is toggle on when it notices first press, and then does nothing to the LED until the button is released and button_down is set to LOW.

Serial communication happens with baud rate 9600. I did not study what baud rates should work with this device or with USB, I just used the one that I had used prviously, and it worked.

Here is a video of the finished product. I noticed a bug in this video; I had accidentally left digitalWrite(LED_PIN, HIGH) to the setup() when I tried to find out the correct pins. It caused the first button press to not do anything. I removed that line.