PWM 控制蜂鸣器编程示例解释

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

#include //标准输入输出定义
#include //POSIX 终端控制定义
#include //Unix 标准函数定义
#include //标准函数库定义
#define PWM_IOCTL_SET_FREQ 1
#define PWM_IOCTL_STOP 0
#define ESC_KEY 0x1b //定义ESC_KEY 为ESC 按键的键值
static int getch(void) //定义函数在终端上获得输入,并把输入的量(int)返回
{
struct termios oldt,newt; //终端结构体struct termios
int ch;
if (!isatty(STDIN_FILENO)) { //判断串口是否与标准输入相连
fprintf(stderr, "this problem should be run at a terminal\n");
exit(1);
}
// save terminal setting
if(tcgetattr(STDIN_FILENO, &oldt) < 0) { //获取终端的设置参数
perror("save the terminal setting");
exit(1);
}
// set terminal as need
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO ); //控制终端编辑功能参数ICANON 表示使用标准输入模式;参数ECH0 表示显示输入字符
if(tcsetattr(STDIN_FILENO,TCSANOW, &newt) < 0) { //保存新的终端参数
perror("set terminal");
exit(1);
}
ch = getchar();
// restore termial setting
if(tcsetattr(STDIN_FILENO,TCSANOW,&oldt) < 0) { //恢复保存旧的终端参数
perror("restore the termial setting");
exit(1);
}
return ch;
}
static int fd = -1;
static void close_buzzer(void);
static void open_buzzer(void) //打开蜂鸣器
{
fd = open("/dev/pwm", 0); //打开pwm 设备驱动文件
if (fd < 0) {
perror("open pwm_buzzer device"); //打开错误,则终止进程。退出参数为1
exit(1);
}
// any function exit call will stop the buzzer
atexit(close_buzzer); //退出回调close_buzzer
}
static void close_buzzer(void) //关闭蜂鸣器
{
if (fd >= 0) {
ioctl(fd, PWM_IOCTL_STOP); //停止蜂鸣器
close(fd); //关闭设备驱动文件
fd = -1;
}
}
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); //退出,返回1
}
}
static void stop_buzzer(void)
{
int ret = ioctl(fd, PWM_IOCTL_STOP); //关闭蜂鸣器
if(ret < 0) { //如果无法关闭蜂鸣器
perror("stop the buzzer");
exit(1); //退出返回1
}
}
int main(int argc, char **argv)
{
int freq = 1000 ;
open_buzzer();//打开蜂鸣器
printf( "\nBUZZER TEST ( PWM Control )\n" );
printf( "Press +/- to increase/reduce the frequency of the BUZZER\n" ) ;
printf( "Press 'ESC' key to Exit this program\n\n" );
while( 1 )
{
int key;
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;
case ESC_KEY:
case EOF:
stop_buzzer();
exit(0);
default:
break;
}
}
}

相关文档
最新文档