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