今天又看了看mini2440开发板用户手册上应用开发里的一些例程,就自己花了点时间把其中的测试按键和PWM 控制蜂鸣器这两个程序综合了一下,写一个按键控制蜂鸣器的程序。
实现效果如下:
代码如下:
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include time.h>
- #include
- #define PWM_IOCTL_STOP 2
- #define PWM_IOCTL_SET_FREQ 1
- static int fd = -1; //定义蜂鸣器的文件标示符
- static void close_buzzer(void); //关蜂鸣器
- static void open_buzzer(void)//开蜂鸣器
- {
- fd = open("/dev/pwm", 0); //打开蜂鸣器设备
- if (fd < 0) {
- perror("open pwm_buzzer device");
- exit(1);
- }
- // any function exit call will stop the buzzer
- atexit(close_buzzer); //注册蜂鸣器关闭程序
- }
- static void close_buzzer(void)
- {
- if (fd >= 0) {
- ioctl(fd, PWM_IOCTL_STOP); //关闭蜂鸣器控制I/O
- close(fd);//关闭设备文件
- fd = -1;
- }
- }
- static void set_buzzer_freq(int freq) //由于蜂鸣器是无源的,因此需要PWM控制
- {
- // this IOCTL command is the key to set frequency
- int ret = ioctl(fd, PWM_IOCTL_SET_FREQ, freq); //设置蜂鸣器的pwm
- if(ret < 0) {
- perror("set the frequency of the buzzer");
- exit(1);
- }
- }
- static void stop_buzzer(void)
- {
- int ret = ioctl(fd, PWM_IOCTL_STOP); //关闭蜂鸣器控制I/O
- if(ret < 0) {
- perror("stop the buzzer");
- exit(1);
- }
- }
- //主函数
- int main(int argc, char *argv[])
- {
- int buttons_fd; //蜂鸣器设备文件标示符
- int freq=1000; //定蜂鸣器发声频率为1000
- char buttons[6] = {'0', '0', '0', '0', '0', '0'}; //初始六个按键初值
- buttons_fd = open("/dev/buttons", 0); //打开按键设备
- if (buttons_fd < 0) {
- perror("open device buttons");
- exit(1);
- }
- open_buzzer(); //打开蜂鸣器控制I/O
- for (;;) { //函数启动后不断读取按键值,直到有按键按下并释放才会退出
- char current_buttons[6];
- int i;
- //读取按键设备,判断是否有按键按下
- if (read(buttons_fd, current_buttons, sizeof current_buttons) != sizeof current_buttons) {
- perror("read buttons:");
- exit(1);
- }
- for (i = 0; i < sizeof buttons / sizeof buttons[0]; i++) {
- //如果按键按下,蜂鸣器发声
- if(buttons[i]!='0') {
- set_buzzer_freq(freq);
- printf("The key is down.t");
- printf( "The buzzer is on.tFreq = %dn", freq );
- }
- //按键释放,蜂鸣器停止,函数退出
- else
- {
- stop_buzzer();
- printf("The key is up.tThe buzzer is off.n");
- exit(0);
- }
- }
- }
- close(buttons_fd);
- return 0;
- }
复制代码
0
|
|
|
|