EasyManua.ls Logo

Freenove Ultimate Starter Kit - Page 92

Freenove Ultimate Starter Kit
286 pages
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
Chapter 6 Buzzer
92
www.freenove.com
support@freenove.com
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.cand generate executable fileDoorbell.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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#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");
}
}

Table of Contents