1. 程式人生 > >linux蜂鳴器測試程式

linux蜂鳴器測試程式

必要的標頭檔案#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; } } }