關鍵字:Micro2440, Mini2440, Beep, 蜂鳴器
Micro2440/Mini2440 Linux 默認內核已包含蜂鳴器支持(見《Micro2440用戶手冊 -2010-6-9.pdf》P346),可直接通過文件 ioctl 操作蜂鳴器。若 ls /dev/pwm 存在,表示設備已就緒。
以下代碼參考上述手冊,修正了手冊中 PWM_IOCTL_STOP 定義錯誤(手冊定義為 2,實際內核代碼為 0)。
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <stdlib.h>
#define PWM_IOCTL_SET_FREQ 1
#define PWM_IOCTL_STOP 0 /* 修正:手冊誤寫為 2 */
static int fd = -1; /* 蜂鳴器文件句柄 */
/* 關閉蜂鳴器 */
static void close_buzzer(void) {
if (fd >= 0) {
ioctl(fd, PWM_IOCTL_STOP);
close(fd);
fd = -1;
}
}
/* 打開蜂鳴器 */
static void open_buzzer(void) {
fd = open("/dev/pwm", 0);
if (fd < 0) {
perror("open pwm_buzzer device");
exit(1);
}
atexit(close_buzzer); /* 程序退出時自動關閉 */
}
/* 設置頻率 */
static void set_buzzer_freq(int freq) {
int ret = ioctl(fd, PWM_IOCTL_SET_FREQ, freq);
if (ret < 0) {
perror("set the frequency of the buzzer");
exit(1);
}
}
/* 停止蜂鳴 */
static void stop_buzzer(void) {
int ret = ioctl(fd, PWM_IOCTL_STOP);
if (ret < 0) {
perror("stop the buzzer error");
exit(-1);
}
}
/* 蜂鳴控制函數
* freq: 頻率(Hz)
* t1: 每次蜂鳴持續毫秒數
* t2: 蜂鳴次數
* 建議: ./testBeep 3000 2000 3 (正常提示)
* ./testBeep 3000 500 20 (失敗告警)
*/
static void Beep(int freq, int t1, int t2) {
printf("freq=%d, each_ms=%d, ntimes=%d\n", freq, t1, t2);
open_buzzer();
for (int i = 0; i < t2; ++i) {
set_buzzer_freq(freq);
usleep(t1 * 100); /* 經驗值系數 */
stop_buzzer();
usleep(t1 * 100);
}
close_buzzer();
}
/* 主程序:解析命令行參數 */
int main(int argc, char **argv) {
int freq = 10000;
int each_ms = 500;
int times = 5;
if (argc >= 2) {
freq = atoi(argv[1]);
if (freq < 1000 || freq > 20000) freq = 10000;
}
if (argc >= 3) {
each_ms = atoi(argv[2]);
if (each_ms < 100 || each_ms > 5000) each_ms = 500;
}
if (argc >= 4) {
times = atoi(argv[3]);
if (times < 1 || times > 30) times = 5;
}
Beep(freq, each_ms, times);
return 0;
}
arm-linux-gcc testBeep.c -o testBeep
摘自 EasyVCR 的專欄