The code is exactly the same to using button to control LED logically. You can try to use the PNP transistor
to achieve the function of his circuit once again.
Project 6.2 Alertor
Next, we will use a passive buzzer to make an alarm.
Component list and the circuit part is the similar to last section. In the Doorbell circuit only the active buzzer
needs to be replaced with a passive buzzer.
Code
In this project, the buzzer alarm is controlled by the button. Press the button, then buzzer sounds. If you
release the button, the buzzer will stop sounding. In the logic, it is the same to using button to control LED.
In the control method, passive buzzer requires PWM of certain frequency to sound.
C Code 6.2.1 Alertor
First observe the project result, and then analyze the code.
1. Use cd command to enter 06.2.1_Alertor directory of C code.
cd ~/Freenove_Ultimate_Starter_Kit_for_Raspberry_Pi/Code/C_Code/06.2.1_Alertor
2. Use following command to compile “Alertor.c” and generate executable file “Alertor”. “-lm” and “-lpthread”
compiler options are needed to add here.
gcc Alertor.c -o Alertor -lwiringPi -lm -lpthread
3. Then run the generated file “Alertor”.
sudo ./Alertor
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>
#include <softTone.h>
#include <math.h>
#define buzzeRPin 0 //define the buzzeRPin
#define buttonPin 1 //define the buttonPin
void alertor(int pin){
int x;
double sinVal, toneVal;
for(x=0;x<360;x++){ // The frequency is based on the sine curve.
sinVal = sin(x * (M_PI / 180));
toneVal = 2000 + sinVal * 500;
softToneWrite(pin,toneVal);