Code
This project is designed for learning how to use button to control LED. We first need to read the state of
button, and then determine whether turn on LED according to the state of the button.
C Code 2.1.1 ButtonLED
First, observe the project result, then analyze the code.
1. Use cd command to enter 02.1.1_ButtonLED directory of C code.
cd ~/Freenove_Ultimate_Starter_Kit_for_Raspberry_Pi/Code/C_Code/02.1.1_ButtonLED
2. Use the following command to compile the code “ButtonLED.c” and generate executable file “ButtonLED”
gcc ButtonLED.c -o ButtonLED -lwiringPi
3. Then run the generated file “ButtonLED”.
sudo ./ButtonLED
Later, the terminal window continues to print out the characters “led off…”. Press the button, then LED is
turned on and then terminal window prints out the "led on…". Release the button, then LED is turned off and
then terminal window prints out the "led off…". You can press "Ctrl+C" to terminate the program.
The following is the program code:
#include <wiringPi.h>
#include <stdio.h>
#define ledPin 0 //define the ledPin
#define buttonPin 1 //define the buttonPin
int main(void)
{
if(wiringPiSetup() == -1){ //when initialization for wiring fails, print message to
screen
printf("setup wiringPi failed !");
return 1;
}
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
pullUpDnControl(buttonPin, PUD_UP); //pull up to high level
while(1){
if(digitalRead(buttonPin) == LOW){ //button has pressed down
digitalWrite(ledPin, HIGH); //led on
printf("led on...\n");
}
else { //button has released
digitalWrite(ledPin, LOW); //led off
printf("...led off\n");