首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Micro2440/Mini2440 Linux 下蜂鳴器 (Beep) 控制 C 程序詳解

     編輯:關於C語言

關鍵字: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 的專欄

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved