Skip to main content

LED switch

In this example, you will use a pushbutton to control the LED. When you press the button, the LED turns on. When you release it, the LED turns off. The input signal will change as you press the button. Thus, you can set LED states according to input states.

What you need​

  • SwiftIO Micro (or SwiftIO board)
  • Breadboard
  • Button
  • Jumper wires


  1. Plug the button into the breadboard.
  2. Connect one leg on one side to the pin 3V3.
  3. Connect one leg on the other side to pin D0.
circuit diagram

Example code​

Open the project LEDSwitch in the folder MadExamples/Examples/SimpleIO if you downloaded the examples.

// Read the input signal controlled by a button to turn on and off the LED.

// Import the library to enable the relevant classes and functions.
import SwiftIO
import MadBoard

public struct LEDSwitch {
public static func main() {
// Initialize the red onboard LED.
let red = DigitalOut(Id.RED)

// Initialize a digital input pin D0 that the button is connected to.
let button = DigitalIn(Id.D0)

// Allow the button to control the LED all the time.
while true {
// Check the state of button. If it is pressed, the value will be true and then turn off the LED.
// Modify the code according to your button if necessary.
if {
} else {

Code analysis​

if {
} else {

First, you'll need to check the button state. The method .read() reads the value from the digital input pin. The return value is a boolean value, either true (1) or false (0).

Then use if-else statement to decide the LED state according to the value. If the value is true, the button has been pressed, so turn on the LED. Otherwise, turn off the LED.

If you have experience with Arduino, you may notice there's no pull-down resistor on the button. That's because our boards already have built-in pull resistors. Reference the Mode in DigitalIn class for more information.


DigitalOut - set whether the pin outputs a high or low voltage.

DigitalIn - read the input value from a digital pin.

MadBoard - find the corresponding pin id of your board.