Code
In this project, buzzer is controlled by the button. When the button is pressed, the buzzer sounds. And when
the button is released, the buzzer stops sounding. In the logic, it is the same to using button to control LED.
C Code 6.1.1 Doorbell
First observe the project result, and then analyze the code.
1. Use cd command to enter 06.1.1_Doorbell directory of C code.
cd ~/Freenove_Ultimate_Starter_Kit_for_Raspberry_Pi/Code/C_Code/06.1.1_Doorbell
2. Use following command to compile “Doorbell.c” and generate executable file “Doorbell.c”.
gcc Doorbell.c -o Doorbell -lwiringPi
3. Then run the generated file “Doorbell”.
sudo ./Doorbell
After the program is executed, press the button, then buzzer sounds. And when the button is release, the
buzzer will stop sounding.
The following is the program code:
#include <wiringPi.h>
#include <stdio.h>
#define buzzeRPin 0 //define the buzzeRPin
#define buttonPin 1 //define the buttonPin
int main(void)
{
if(wiringPiSetup() == -1){ //when initialize wiring failed, print message to screen
printf("setup wiringPi failed !");
return 1;
}
pinMode(buzzeRPin, OUTPUT);
pinMode(buttonPin, INPUT);
pullUpDnControl(buttonPin, PUD_UP); //pull up to high level
while(1){
if(digitalRead(buttonPin) == LOW){ //button has pressed down
digitalWrite(buzzeRPin, HIGH); //buzzer on
printf("buzzer on...\n");
}
else { //button has released
digitalWrite(buzzeRPin, LOW); //buzzer off
printf("...buzzer off\n");
}
}