Get tutorials Raspberry Pi Super Kit V2.0 for RaspberryPi

Lesson 2 Controlling an LED by a Button


In this lesson, we will learn how to turn an LED on or off by a button.


- 1* Raspberry Pi

- 1* Breadboard

- 1* LED

- 1* Button

- 1* Resistor (220Ω)

- Jumper wires





Buttons are a common component used to control electronic devices. They are usually used as switches to connect or disconnect circuits. Although buttons come in a variety of sizes and shapes, the one used here is a6mmmini-button as shown in the following pictures. Pins pointed out by the arrows of same color are meant to be connected.

When the button is pressed, the pins pointed by the blue arrow will connect to the pins pointed by the red arrow (see the above figure), thus closing the circuit, as shown in the following diagrams.

Generally, the button can be connected directly to the LED in a circuit to turn on or off the LED, which is comparatively simple. However, sometimes the LED will brighten automatically without any button pressed, which is caused by various kinds of external interference. In order to avoid this interference, a pull-down resistor is used – usually connect a 1K–10KΩ resistor between the button and GND. It can be connected to GND to consume the interference when the button is off.

Use a normally open button as the input of Raspberry Pi. When the button is pressed, the GPIO connected to the button will turn into low level (0V). We can detect the state of the GPIO connected to the button through programming. That is, if the GPIO turns into low level, it means the button is pressed. You can run the corresponding code when the button is pressed, and then the LED will light up.

Experimental Procedures

Step 1: Build the circuit


For C language users:

Step 2: Change directory

cd /home/pi/Sunfounder_SuperKit_C_code_for_RaspberryPi/02_BtnAndLed/

Step 3: Compile

gcc BtnAndLed.c –o BtnAndLed –lwiringPi

Step 4: Run

       sudo ./BtnAndLed

For Python users:

Step 2: Change directory

cd /home/pi/Sunfounder_SuperKit_ Python_code_for_RaspberryPi/

Step 3: Run

          sudo python

Now, press the button, and the LED will light up; press the button again,and the LED will go out. At the same time, the state of the LED will be printed on the screen.



Through this experiment, you have learnt how to control the GPIOs of the Raspberry Pi by programming. 

C Code

* Filename    : BtnAndLed.c
* Description : Controlling an led by button.
* Author      : Robot
* E-mail      :
* website     :
* Date        : 2014/08/27
#include <wiringPi.h>
#include <stdio.h>

#define LedPin    0
#define ButtonPin 1

int main(void)
	if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
		printf("setup wiringPi failed !");
		return 1; 
	pinMode(LedPin, OUTPUT); 
	pinMode(ButtonPin, INPUT);

	pullUpDnControl(ButtonPin, PUD_UP);  //pull up to 3.3V,make GPIO1 a stable level
		digitalWrite(LedPin, HIGH);
		if(digitalRead(ButtonPin) == 0){ //indicate that button has pressed down
			digitalWrite(LedPin, LOW);   //led on

	return 0;


#!/usr/bin/env python
import RPi.GPIO as GPIO
import time

LedPin = 11    # pin11 --- led
BtnPin = 12    # pin12 --- button

Led_status = 1

def setup():
	GPIO.setmode(GPIO.BOARD)       # Numbers GPIOs by physical location
	GPIO.setup(LedPin, GPIO.OUT)   # Set LedPin's mode is output
	GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)    # Set BtnPin's mode is input, and pull up to high level(3.3V)
	GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led

def swLed(ev=None):
	global Led_status
	Led_status = not Led_status
	GPIO.output(LedPin, Led_status)  # switch led status(on-->off; off-->on)
	if Led_status == 1:
		print 'led off...'
		print '...led on'

def loop():
	GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=swLed, bouncetime=200) # wait for falling and set bouncetime to prevent the callback function from being called multiple times when the button is pressed
	while True:
		time.sleep(1)   # Don't do anything

def destroy():
	GPIO.output(LedPin, GPIO.HIGH)     # led off
	GPIO.cleanup()                     # Release resource

if __name__ == '__main__':     # Program start from here
	except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.


Copyright © 2012 - 2016 SunFounder. All Rights Reserved.

Previous chapter: Lesson 1 Blinking LED

Next chapter: Lesson 3 Flowing LED Lights

Apr 01 2017 at 10:20 am

© Developed by CommerceLab