Richard Kuo
/
NTOUEE-mbed-PWM_siren
mbed PWM output to play siren
Diff: main.cpp
- Revision:
- 0:ed48c1d4c02f
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Fri Oct 21 07:35:16 2016 +0000 @@ -0,0 +1,60 @@ +//NuMaker-PFM-NUC472 PWM0 output Siren to a speaker +#include "mbed.h" + +#define Ambulance_Siren_Low 650 +#define Ambulance_Siren_High 900 +#define Ambulance_Siren_L_period 400 // 0.4 sec +#define Ambulance_Siren_H_period 600 // 0.6 sec + +#define PoliceCar_Siren_Low 650 +#define PoliceCar_Siren_High 1450 +#define PoliceCar_Siren_L_duration 230 // 0.23 sec +#define PoliceCar_Siren_H_duration 100 // 0.1 sec + +PwmOut pwm0(PF_9); // PWM0 pin + +void Ambulance_Siren(uint32_t siren_no) +{ + int i; + for (i=0; i<siren_no; i++) { + pwm0.period_us(1000000/Ambulance_Siren_Low); + pwm0.pulsewidth_us(1000000/Ambulance_Siren_Low/2); // set duty cycle to 50% + Thread::wait(Ambulance_Siren_L_period); + pwm0.period_us(1000000/Ambulance_Siren_High); + pwm0.pulsewidth_us(1000000/Ambulance_Siren_High/2); // set duty cycle to 50% + Thread::wait(Ambulance_Siren_H_period); + } + pwm0.pulsewidth_us(0); +} + +void PoliceCar_Siren(uint32_t siren_no) +{ + int i, j; + int siren_freq; + + for (i=0; i<siren_no; i++) { + siren_freq = PoliceCar_Siren_Low; + for (j=0; j<(PoliceCar_Siren_L_duration); j++) { + pwm0.period_us(1000000/siren_freq); + pwm0.pulsewidth_us(1000000/siren_freq/2); // set duty cycle to 50% + Thread::wait(1); + siren_freq = siren_freq + (PoliceCar_Siren_High - PoliceCar_Siren_Low)/230; + } + siren_freq = PoliceCar_Siren_High; + for (j=0; j<PoliceCar_Siren_L_duration; j++) { + pwm0.period_us(1000000/siren_freq); + pwm0.pulsewidth_us(1000000/siren_freq/2); // set duty cycle to 50% + Thread::wait(1); + siren_freq = siren_freq - (PoliceCar_Siren_High - PoliceCar_Siren_Low)/100; + } + } + pwm0.pulsewidth_us(0); +} + +int main() +{ + while(1) { + Ambulance_Siren(5); + PoliceCar_Siren(5); + } +}