Main Content

Flash Raspberry Pi LED in Response to Input

This example shows how to flash the on-board LED when you press a button that is connected to a GPIO pin.

Warning

Excessive voltage and current can damage the Raspberry Pi® hardware. Observe the manufacturer’s precautions for handling the Raspberry Pi hardware and connecting it to other devices. For more information, see https://www.raspberrypi.com/documentation/.

Using a breadboard, set up the following circuit:

  • Connect one of the +3.3V pins on the GPIO header to a button.

  • Connect pin 23 on the GPIO header to a 220 or 330 Ohm resistor.

  • Connect the unconnected ends of the button and resistor to each other.

Note

Use showLEDs to show an illustration that identifies each pin.

Run the code and press the button. The button closes the circuit between the +3.3V pin and pin 23. When readDigitalPin detects the raised voltage, if buttonPressed becomes true, and writeLED toggles the LED on and off ten times.

for ii = 1:100
    buttonPressed = readDigitalPin(mypi,23)
    if buttonPressed
        for jj = 1:10
            writeLED(mypi,'led0',1)
            pause(0.05)
            writeLED(mypi,'led0',0)
            pause(0.05)
        end
    end
    pause(0.1)
end