必要的头文件#include <stdio.h> //必要的头文件 #include <termios.h> //POSIX终端控制定义 #include <unistd.h> #include <stdlib.h> #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)) { //判断串口是否与标准输入相连,isatty(fd)判断fd是否是终端设备
fprintf(stderr, "this problem should be run at a terminal\n"); exit(1); } // save terminal setting if(tcgetattr(STDIN_FILENO, &oldt) < 0) { //过去fd的终端属性,并把它放入oldt中断结构体中,以为后面恢复使用 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); //打开蜂鸣器的设备文件 if (fd < 0) { //打开失败 perror("open pwm_buzzer device"); exit(1); } // any function exit call will stop the buzzer atexit(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); } } static void stop_buzzer(void) { int ret = ioctl(fd, PWM_IOCTL_STOP); //关闭蜂鸣器 if(ret < 0) { //如果无法关闭蜂鸣器 perror("stop the buzzer"); exit(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; } } }