您的位置:首页 > 运维架构 > Linux

linux蜂鸣器测试程序

2012-04-06 22:10 288 查看
必要的头文件#include<stdio.h>//必要的头文件
#include<termios.h>//POSIX终端控制定义
#include<unistd.h>
#include<stdlib.h>

#definePWM_IOCTL_SET_FREQ		1
#definePWM_IOCTL_STOP			0
#define	ESC_KEY		0x1b//定义ESC_KEY为ESC按键的键值




staticintgetch(void)//从终端获得输入,并把输入转化为int返回
{
structtermiosoldt,newt;//终端结构体structtermios

	intch;
if(!isatty(STDIN_FILENO)){//判断串口是否与标准输入相连,isatty(fd)判断fd是否是终端设备

fprintf(stderr,"thisproblemshouldberunataterminal\n");
exit(1);
}
//saveterminalsetting
if(tcgetattr(STDIN_FILENO,&oldt)<0){//过去fd的终端属性,并把它放入oldt中断结构体中,以为后面恢复使用
perror("savetheterminalsetting");
exit(1);
}
//setterminalasneed
newt=oldt;
newt.c_lflag&=~(ICANON|ECHO);//控制终端编辑功能参数ICANON表示使用标准输入模式;参数ECH0表示进行回送
if(tcsetattr(STDIN_FILENO,TCSANOW,&newt)<0){//表示更改立即生效
perror("setterminal");
exit(1);
}
ch=getchar();//输入数据
//restoretermialsetting
if(tcsetattr(STDIN_FILENO,TCSANOW,&oldt)<0){//恢复原来的终端属性
perror("restorethetermialsetting");
exit(1);
}
returnch;
}

staticintfd=-1;
staticvoidclose_buzzer(void);//关闭蜂鸣器
staticvoidopen_buzzer(void)//打开蜂鸣器
{
fd=open("/dev/pwm",0);//打开蜂鸣器的设备文件
if(fd<0){//打开失败
perror("openpwm_buzzerdevice");
exit(1);
}
//anyfunctionexitcallwillstopthebuzzer
atexit(close_buzzer);//注册清除函数
}

staticvoidclose_buzzer(void)//关闭蜂鸣器
{
if(fd>=0){
ioctl(fd,PWM_IOCTL_STOP);//停止蜂鸣器
close(fd);//关闭设备驱动程序文件
fd=-1;
}
}

staticvoidset_buzzer_freq(intfreq)
{
//thisIOCTLcommandisthekeytosetfrequency
intret=ioctl(fd,PWM_IOCTL_SET_FREQ,freq);//设置蜂鸣器的频率
if(ret<0){//如果设置出错
perror("setthefrequencyofthebuzzer");
exit(1);
}
}
staticvoidstop_buzzer(void)
{
intret=ioctl(fd,PWM_IOCTL_STOP);//关闭蜂鸣器
if(ret<0){//如果无法关闭蜂鸣器
perror("stopthebuzzer");
exit(1);
}
}

intmain(intargc,char**argv)
{
intfreq=1000;

open_buzzer();//打开蜂鸣器
//打印提示信息
printf("\nBUZZERTEST(PWMControl)\n");
printf("Press+/-toincrease/reducethefrequencyoftheBUZZER\n");
printf("Press'ESC'keytoExitthisprogram\n\n");

while(1)
{
intkey;

set_buzzer_freq(freq);//设置蜂鸣器的频率
printf("\tFreq=%d\n",freq);

key=getch();//从键盘获取数据

switch(key){//输入数据判断
case'+':
if(freq<20000)
freq+=10;
break;

case'-':
if(freq>11)
freq-=10;
break;

caseESC_KEY:
caseEOF:
stop_buzzer();//停止蜂鸣器
exit(0);

default:
break;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: