Micro2440/Mini2440 linux下蜂鸣(Beep)c程序

关键字: Micro2440, Mini2440, Beep, 蜂鸣

Micro2440/Mini2440 linux缺省内核中已加入了蜂鸣器支持(见<<micro2440用户手册 -2010-6-9.pdf>>P346),因此可以直接通过文件ioctl的方式操作蜂鸣器。

(ls /dev/pwm 存在,则表明你的Micro2440/Mini2440已经有蜂鸣器功能。)

下面的代码参考了<<micro2440用户手册 -2010-6-9.pdf>>


#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <stdlib.h>

#define PWM_IOCTL_SET_FREQ 1
#define PWM_IOCTL_STOP 0          // 注意:<<micro2440用户手册 -2010-6-9.pdf>>中,
                                  //       PWM_IOCTL_STOP定义为2,有误;
                                  //       应该与蜂鸣器的内核代码一致,为0

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);
    }

    // any function exit call will stop the buzzer
    atexit(close_buzzer);
}

/** 以freq蜂鸣 */
static void set_buzzer_freq(int freq)
{
    // this IOCTL command is the key to set frequency
    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.\n");
        exit(-1);
    }
}

/** 
 * 蜂鸣函数。
 * \param freq 蜂鸣的频率
 * \param t1 每次蜂鸣持续的时间长度。单位毫秒
 * \param t2 蜂鸣的次数
 * \remark 经测试,./testBeep 3000 2000 3 作为正常情况的蜂鸣效果较好(3k频率蜂鸣3次,每次2秒)
 *                ./testBeep 3000 500 20 作为失败告警的蜂鸣效果较好(3k频率蜂鸣20次,每次0.5秒)
 */
static void Beep(int freq, int t1, int t2)
{
    printf("freq=%d,each_ms=%d,ntimes=%d\n", freq, t1, t2);
    open_buzzer();
    int i=0;
    for(i=0; i<t2;++i)
    {
        set_buzzer_freq(freq);
        usleep(t1*100);    //  *100 是经验值,没有为啥~
        stop_buzzer();
        usleep(t1*100);    //  *100 是经验值,没有为啥~
    }
    close_buzzer();
}

/** 测试程序main */
int main(int argc, char **argv)
{
    int freq;
    if(argc >=2)
    {
        freq = atoi(argv[1]);
        if ( freq < 1000 || freq > 20000 )
        {
            freq = 10000;
        }
    }

    int each_ms = 500;
    if(argc >=3)
    {
        each_ms = atoi(argv[2]);
        if ( each_ms < 100 || each_ms > 5000 )
        {
            each_ms = 500;
        }
    }

    int times = 0;
    if(argc >=4)
    {
        times = atoi(argv[3]);
        if ( times < 1 || times > 30 )
        {
            times = 5;
        }
    }

    Beep(freq, each_ms, times);

    return 0;
}

// EasyVCR@csdn, 2012.01.04


编译:arm-linux-gcc testBeep.c -o testBeep 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值