Lesson 3 Controlling an LED by a Button

Share for us

Introduction

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

Components

– 1*Raspberry Pi

– 1*Breadboard

– 1*Network cable (or USB wireless network adapter)

– 1*LED

– 1*Button

– 1*Resistor (220Ω)

– Jumper wires

Experimental Principle

Use a normally open button as an input of Raspberry Pi, when the button is pressed, the GPIO (General Purpose Input/Output) 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 according to this condition. In this experiment, we make the LED light up.

Experimental Procedures

Step 1: Connect the circuit as shown in the following diagram

Step 2: Edit and save the code with vim (see path/Rpi_BasicKit /03_BtnAndLed/BtnAndLed.c)

Step 3: Compile the code    

 gcc  8Led.c  -lwiringPi

Step 4: Run the program

 ./a.out

Press Enter, when you press the button, the LED will light up; when you release the button, the LED will go out.

Summary

Through this experiment, you have basically mastered the Input and Output programming operation of Raspberry Pi GPIOs. I hope you can make persistent efforts and continue to learn the next contents.

C Code

#include <wiringPi.h>
#include <stdio.h>#define LedPin 0
#define ButtonPin 1int main(void){if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screenprintf(“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
while(1){digitalWrite(LedPin, HIGH);
if(digitalRead(ButtonPin) == 0){//indicate that button has pressed down
digitalWrite(LedPin, LOW); //led on}}return 0;
}

Python Code

#!/usr/bin/env python import RPi.GPIO as GPIO 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…’ else: print ‘…led on’ def loop(): GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=swLed) # wait for falling while True: pass # Don’t do anything def destroy(): GPIO.output(LedPin, GPIO.HIGH) # led off GPIO.cleanup() # Release resource if __name__ == ‘__main__’: # Program start from here setup() try: loop() except KeyboardInterrupt: # When ‘Ctrl+C’ is pressed, the child program destroy() will be executed. destroy()