?????? fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY );
??????? 打開的串口設(shè)備有很多設(shè)置選項。本文中使用int setup_com(int fd)設(shè)置。在系統(tǒng)頭文件
c_cflag? : 控制選項
c_lflag? : 線選項
c_iflag? : 輸入選項
c_oflag? :輸出選項
c_cc??? :控制字符
c_ispeed :輸入數(shù)據(jù)波特率
c_ospeed :輸出數(shù)據(jù)波特率
??????? 如果要設(shè)置某個選項,那么就使用"|="運(yùn)算,如果關(guān)閉某個選項就使用"&="和"~"運(yùn)算。本文使用的各個選項的意義定義如下:
c_cflag: CLOCAL 本地模式,不改變端口的所有者
???????? CREAD? 表示使能數(shù)據(jù)接收器
???????? PARENB? 表示偶校驗
???????? PARODD 表示奇校驗
??????? CSTOPB? 使用兩個停止位
??????? CSIZE??? 對數(shù)據(jù)的bit使用掩碼
??????? CS8????? 數(shù)據(jù)寬度是8bit
??????? c_lflag:? ICANON 使能規(guī)范輸入,否則使用原始數(shù)據(jù)(本文使用)
??????? ECHO??? 回送(echo)輸入數(shù)據(jù)
??????? ECHOE?? 回送擦除字符
??????? ISIG????? 使能SIGINTR,SIGSUSP, SIGDSUSP和 SIGQUIT 信號
??????? c_iflag:? IXON???? 使能輸出軟件控制
???????? ?IXOFF??? 使能輸入軟件控制
???????? IXANY??? 允許任何字符再次開啟數(shù)據(jù)流
???????? INLCR??? 把字符NL(0A)映射到CR(0D)
???????? IGNCR??? 忽略字符CR(0D)
?????? ICRNL??? 把CR(0D)映射成字符NR(0A)
??? c_oflag: OPOST? 輸出后處理,如果不設(shè)置表示原始數(shù)據(jù)(本文使用原始數(shù)據(jù))
c_cc[VMIN]:? 最少可讀數(shù)據(jù)
c_cc[VTIME]: 等待數(shù)據(jù)時間(10秒的倍數(shù))
????? 根據(jù)以上設(shè)置的定義,串口端口設(shè)置函數(shù)setup_com()定義如下:
int setup_com(int fd){
??? struct termios options;
??? tcgetattr(fd, &options);
??? /* Set the baud rates to 38400...*/
??? cfsetispeed(&options, B38400);
??? cfsetospeed(&options, B38400);
??? /* Enable the receiver and set local mode...*/
??? options.c_cflag |= (CLOCAL | CREAD);
??? /* Set c_cflag options.*/
??? options.c_cflag |= PARENB;
??? options.c_cflag &= ~PARODD;
??? options.c_cflag &= ~CSTOPB;
??? options.c_cflag &= ~CSIZE;
??? options.c_cflag |= CS8;???
??? /* Set c_iflag input options */
??? options.c_iflag &=~(IXON | IXOFF | IXANY);
??? options.c_iflag &=~(INLCR | IGNCR | ICRNL);
??? options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
??? /* Set c_oflag output options */
??? options.c_oflag &= ~OPOST;??
??? /* Set the timeout options */
??? options.c_cc[VMIN]? = 0;
??? options.c_cc[VTIME] = 10;
??? tcsetattr(fd, TCSANOW, &options);
??? return 1;
}
??????? 兩個打包和拆包函數(shù)和SLIP協(xié)議定義的一樣,拆包函數(shù)和打包相反,這里不列舉了。
??????? 小結(jié)
?????? 本文描述的是一個非常簡單的串口上網(wǎng)程序,如果需要可靠的通信,增加吞吐量,可在用戶空間添加適當(dāng)?shù)木W(wǎng)絡(luò)控制協(xié)議,也可增加數(shù)據(jù)壓縮算法。
評論