更新時間:2021-01-07 17:29:04 來源:動力節點 瀏覽1419次
串行接口簡稱串口(通常指COM接口),是采用串行通信方式的擴展接口。串口是計算機一種常用的接口,具有連接線少,通訊簡單,得到廣泛的使用。串口的特點是通信線路簡單,只要一對傳輸線就可以實現雙向通信從而大大降低了成本,特別適用于遠距離通信,但傳送速度較慢。在Linux中,同樣存在著大量的串口,本文我們就來聊聊Linux下的串口。
一、串口需要的頭文件
1: #include /*標準輸入輸出定義*/
2: #include /*標準函數庫定義*/
3: #include /*Unix 標準函數定義*/
4: #include
5: #include
6: #include /*文件控制定義*/
7: #include /*POSIX 終端控制定義*/
8: #include /*錯誤號定義*/
二、打開關閉串口
對于串口設備文件的操作與其他文件操作基本相同。可以使用系統調用open(), close()打開或關閉串口。
在Linux下串口文件是在/dev下的,例如串口一為/dev/ttyS0,串口二為/dev/ttyS1。
open(),close()系統調用的原型
1: #include
2: #include
3: #include
4: int open(const char *path, int oflags);
5: int open(const char *path, int oflags, mode_t mode);
6: #include
7: int close(int fildes);
8: 實例:打開串口ttyS0。
9: int fd;
10: /*以讀寫方式打開串口*/
11: fd = open( "/dev/ttyS0", O_RDWR);
12: if (-1 == fd){
13: /* 不能打開串口一*/
14: perror("open serial port error");
15: }
三、設置串口
設置串口包括波特率設置、校驗位、停止位設置。在串口設置中主要是設置struct termios結構體成員的值。
struct termios結構如下
1: #include
2: struct termio
3: {
4: unsigned short c_iflag; /* input options輸入模式標志 */
5: unsigned short c_oflag; /* output options輸出模式標志 */
6: unsigned short c_cflag; /* control options控制模式標志*/
7: unsigned short c_lflag; /* local mode flags */
8: unsigned char c_line; /* line discipline */
9: unsigned char c_cc[NCC]; /* control characters */
10: };
實例:設置波特率
1: struct termios options;
2: /*
3: * 得到當前串口設置,保存在options中
4: */
5: tcgetattr(fd, &options);
6: /*
7: * 設置波特率為19200
8: */
9: cfsetispeed(&options, B19200);
10: cfsetospeed(&options, B19200);
11: /*
12: * 本地連接和接收使能
13: */
14: options.c_cflag |= (CLOCAL | CREAD);
15: /*
16: * 應用設置(立即應用)
17: */
18: tcsetattr(fd, TCSANOW, &options);
四、讀寫串口
讀寫串口和普通的文件操作相同,分別使用read()和write()。
原型:
1: #include
2: size_t read(int fields, void *buf, size_t nbytes);
3: size_t write(int fildes, const void *buf, size_t nbytes);
實例:寫串口
1: char buffer[] = “hello world”;
2: int length = 11;
3: int nByte;
4: nByte = write(fd, buffer, length);
以上就是Linux下的串口的一些基本的知識,串口有著許多的類型,串行接口按電氣標準及協議來分包括RS-232-C、RS-422、RS485等。RS-232-C、RS-422與RS-485標準只對接口的電氣特性做出規定,不涉及接插件、電纜或協議。想了解這些串口的特性可以觀看本站的Linux教程,帶你走進串口的世界。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習