/********************************************************************************* * Copyright: (C) 2018 LingYun IoT System Studio * All rights reserved. * * Filename: led.c * Description: This file is used to control Passive buzzer or Active buzzer * * pi@raspberrypi:~ $ gpio readall show BCM and wPi pinmap * * VCC ---- 5V/3.3V * GND ---- GND * I/O ---- GPIO.18 ---- GPIO.1 * BCM wPi * * Version: 1.0.0(2018/10/14) * Author: Guo Wenxue * ChangeLog: 1, Release initial version on "2018/10/14 12:13:26" * ********************************************************************************/ #include #include #include #include #include #include #include #include #include #include "beep.h" //#define CONFIG_ACTV_BEEP /* Only passive buzzer can play tone */ #ifndef CONFIG_ACTV_BEEP #define CONFIG_PLAY_LITTLE_STAR //#define CONFIG_PLAY_TONE_TEST #endif void play_tone_freq(void); void play_little_star(void); int main(int argc, char *argv[]) { wiringPiSetup(); #ifdef CONFIG_PLAY_LITTLE_STAR while(1) { play_little_star(); sleep(3); } #elif (defined CONFIG_PLAY_TONE_TEST) while(1) { play_tone_freq(); sleep(3); } #else while(1) { #ifdef CONFIG_ACTV_BEEP turn_active_beep(ON); #else turn_passive_beep(ON, BEEP_FREQ); #endif sleep(1); #ifdef CONFIG_ACTV_BEEP turn_active_beep(OFF); #else turn_passive_beep(OFF, BEEP_FREQ); #endif sleep(1); } #endif return 0; } /*+-----------------------------+ *| Turn buzzer on or off API | *+-----------------------------+*/ int turn_passive_beep(int cmd, int freq) { int range; if(OFF == cmd) { pwmWrite(PWM_PIN, 0); pinMode(PWM_PIN, INPUT) ; } else { if(freq<2000 || freq>5000) { printf("Beep set invalid PWM frequency[%d]!\n", freq); return -1; } /* Set GPIO as PWM output mode */ pinMode(PWM_PIN, PWM_OUTPUT) ; /* Set PWM mode as ms mode */ pwmSetMode(PWM_MODE_MS); /* Set PWM clock: 19.2MHz/32=600KHz */ pwmSetClock(32); /* Set PWM frequency */ range=600000/freq; pwmSetRange(range); /* Set PWM duty 50% */ pwmWrite(PWM_PIN, range/2); } } /* Turn ON/OFF buzzer, Active Buzzer can not set frequency */ int turn_active_beep(int cmd) { /* Active buzzer VCC connect to: 5V: Both high and low level will be on 3.3V: Low level be on and High level be off So we use INPUT or OUTPUT to control the Beeper */ if(OFF == cmd) { pinMode(PWM_PIN, INPUT); } else { pinMode(PWM_PIN, OUTPUT); digitalWrite(PWM_PIN, LOW); } return 0; } /*+---------------------------------+ *| Play Tone OD,RE,MI....XI,DO1 | *+---------------------------------+*/ enum { UNUSED=0, DO, RE, MI, FA, SO, LA, XI, DO1, RI1, TONE_MAX, }; #define msleep(x) usleep( 1000*(x) ) static int tone_freq[TONE_MAX]={0, 2093, 2349, 2637, 2794, 3136, 3520, 3952, 4186, 4698 }; //static int tone_freq[TONE_MAX]={0, 2000, 2130, 2250, 2360, 2450, 2530, 2620, 2700, 2780}; static inline void play_tone(int tone, int delay) { if(toneRI1) return ; turn_passive_beep(ON, tone_freq[tone]); msleep(delay); turn_passive_beep(OFF, 0); } void play_tone_freq(void) { int i; for(i=DO; i