设为首页 加入收藏

TOP

Micro2440/Mini2440 linux下蜂鸣(Beep)c程序
2014-11-24 00:36:38 来源: 作者: 【 】 浏览:43
Tags:Micro2440/Mini2440 linux Beep 程序

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

Micro2440/Mini2440 linux缺省内核中已加入了蜂鸣器支持(见<>P346),因此可以直接通过文件ioctl的方式操作蜂鸣器。

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

下面的代码参考了<>

#include
#include
#include
#include

#define PWM_IOCTL_SET_FREQ 1
#define PWM_IOCTL_STOP 0 // 注意:<>中,
// 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 {
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

摘自 EasyVCR的专栏

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇网络编程Server端 --- Linux版 下一篇图像(层)正常混合模式详解(下..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: