資源簡介
此例子經過驗證 不是轉載 Linux 串口 數據接收 發送

代碼片段和文件信息
/*receive.c??沒有線程*/
#include???????????/*標準輸入輸出定義*/
#include??????????/*標準函數庫定義*/
#include??????????/*Unix標準函數定義*/
#include???????/**/
#include????????/**/
#include???????????/*文件控制定義*/
#include?????????/*PPSIX終端控制定義*/
#include???????????/*錯誤號定義*/
#define??TRUE?0
#define??FALSE?-1
/***@brief??設置串口通信速率
*@param??fd?????類型int??打開串口的文件句柄
*@param??speed??類型int??串口速度
*@return??void*/
int?speed_arr[]?=?{B115200?B38400?B19200?B9600?B4800?B2400?B1200?B300
????B38400?B19200?B9600?B4800?B2400?B1200?B300?};
int?name_arr[]?=?{11520038400??19200??9600??4800??2400??1200??300
????38400??19200??9600?4800?2400?1200??300?};
?????
//設置波特率
void?set_speed(int?fd?int?speed)
{
??int???i;
??int???status;
??struct?termios???Opt;
??tcgetattr(fd?&Opt);
??for?(?i=?0;??i????{
??? if??(speed?==?name_arr[i])
??? {
??? ????tcflush(fd?TCIOFLUSH);??//清空串口的緩沖區?
???? cfsetispeed(&Opt?speed_arr[i]);
???? cfsetospeed(&Opt?speed_arr[i]);
???? status?=?tcsetattr(fd?TCSANOW?&Opt);
???? if??(status?!=?0)
????????????perror(“tcsetattr?fd1“);
????? return;
????? }
??? tcflush(fdTCIOFLUSH);//清空串口的緩沖區?
???}
}
/**
*@brief???設置串口數據位,停止位和效驗位
*@param??fd?????類型?int??打開的串口文件句柄*
*@param??databits?類型?int?數據位??取值為7?或者*
*@param??stopbits?類型?int?停止位??取值為1?或者*
*@param??parity??類型?int??效驗類型取值為NEOS
*/
//此類是封好的比較完整的類?可以直接使用?
static?int?set_Parity(int?fd?int?databits?int?stopbits?int?parity)
{
struct?termios?options;
if(tcgetattr(fd&options)!=0)?
{?
perror(“SetupSerial?1“);?????
return(FALSE);??
}
options.c_cflag?&=?~CSIZE;
switch?(databits)?/*設置數據位數*/
{???
case?7:
options.c_cflag?|=?CS7;?
break;
case?8:?????
options.c_cflag?|=?CS8;
break;???
default:????
fprintf(stderr“Unsupported?data?size\n“);?return?(FALSE);??
}
//設置校驗類型
switch?(parity)?
{???
case?‘n‘:
case?‘N‘:????
options.c_cflag?&=?~PARENB;???/*?Clear?parity?enable?*/
options.c_iflag?&=?~INPCK;?????/*?Enable?parity?checking?*/?
break;??
case?‘o‘:???
case?‘O‘:?????
options.c_cflag?|=?(PARODD?|?PARENB);?/*?設置為奇效驗*/??
options.c_iflag?|=?INPCK;?????????????/*?Disnable?parity?checking?*/?
break;??
case?‘e‘:??
case?‘E‘:???
options.c_cflag?|=?PARENB;?????/*?Enable?parity?*/????
options.c_cflag?&=?~PARODD;???/*?轉換為偶效驗*/?????
options.c_iflag?|=?INPCK;???????/*?Disnable?parity?checking?*/
break;
case?‘S‘:?
case?‘s‘:??/*as?no?parity*/???
???? options.c_cflag?&=?~PARENB;
options.c_cflag?&=?~CSTOPB;break;??
default:???
fprintf(stderr“Unsupported?parity\n“);????
return?(FALSE);??
}?
?
//設置停止位??
switch?(stopbits)
{???
case?1:
options.c_cflag?&=?~CSTOPB;
break;??
case?2:????
options.c_cflag?|=?CSTOPB;??
??? break;
default:????
? fprintf(stderr“Unsupported?stop
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件???????5907??2010-02-25?00:05??uart.c
-----------?---------??----------?-----??----
?????????????????5907????????????????????1
評論
共有 條評論