Linux 下串口編程入門

來源:互聯網
上載者:User

串口簡介

串列口是電腦一種常用的介面,具有連接線少,通訊簡單,得到廣泛的使用。常用的串口是 RS-232-C 介面(又稱 EIA RS-232-C)它是在 1970 年由美國電子工業協會(EIA)聯合貝爾系統、 數據機廠家及電腦終端生產廠家共同制定的用於串列通訊的標準。它的全名是"資料終端設備(DTE)和資料通訊裝置(DCE)之間串列位元據交換介面技術標準"該標準規定採用一個 25 個腳的 DB25 連接器,對連接器的每個引腳的訊號內容加以規定,還對各種訊號的電平加以規定。傳輸距離在碼元畸變小於 4% 的情況下,傳輸電纜長度應為 50 英尺。

Linux 作業系統從一開始就對串列口提供了很好的支援,本文就 Linux 下的串列口通訊編程進行簡單的介紹,如果要非常深入瞭解,建議看看本文所參考的 《Serial Programming Guide for POSIX Operating Systems》

電腦串口的引腳說明

序號 訊號名稱 符號 流向 功能
2 發送資料 TXD DTE→DCE DTE發送串列資料
3 接收資料 RXD DTE←DCE DTE 接收串列資料
4 請求發送 RTS DTE→DCE DTE 請求 DCE 將線路切換到發送方式
5 允許發送 CTS DTE←DCE DCE 告訴 DTE 線路已接通可以發送資料
6 資料裝置準備好 DSR DTE←DCE DCE 準備好
7 訊號地        訊號公用地
8 偵測載波 DCD DTE←DCE 表示 DCE 接收到遠程載波
20 資料終端準備好 DTR DTE→DCE DTE 準備好
22 響鈴指示 RI DTE←DCE 表示 DCE 與線路接通,出現響鈴

回頁首

串口操作

串口操作需要的標頭檔

#include     <stdio.h>      /*標準輸入輸出定義*/#include     <stdlib.h>     /*標準函數庫定義*/#include     <unistd.h>     /*Unix 標準函數定義*/#include     <sys/types.h>  #include     <sys/stat.h>   #include     <fcntl.h>      /*檔案控制定義*/#include     <termios.h>    /*PPSIX 終端控制定義*/#include     <errno.h>      /*錯誤號碼定義*/

回頁首

開啟串口

在 Linux 下串口檔案是位於 /dev 下的

串口一 為 /dev/ttyS0

串口二 為 /dev/ttyS1

開啟串口是通過使用標準的檔案開啟函數操作:

int fd;/*以讀寫方式開啟串口*/fd = open( "/dev/ttyS0", O_RDWR);if (-1 == fd){ /* 不能開啟串口一*/ perror(" 提示錯誤!");}

回頁首

設定串口

最基本的設定串口包括傳輸速率設定,效驗位和停止位設定。

串口的設定主要是設定 struct termios 結構體的各成員值。

struct termio{unsigned short  c_iflag;/* 輸入模式標誌 */unsigned short  c_oflag;/* 輸出模式標誌 */unsigned short  c_cflag;/* 控制模式標誌*/unsigned short  c_lflag;/* local mode flags */unsigned char  c_line;    /* line discipline */unsigned char  c_cc[NCC];    /* control characters */};

設定這個結構體很複雜,我這裡就只說說常見的一些設定:

傳輸速率設定

下面是修改傳輸速率的代碼:

struct  termios Opt;tcgetattr(fd, &Opt);cfsetispeed(&Opt,B19200);     /*設定為19200Bps*/cfsetospeed(&Opt,B19200);tcsetattr(fd,TCANOW,&Opt);

設定傳輸速率的例子函數:

/***@brief  設定串口通訊速率*@param  fd     類型 int  開啟串口的檔案控制代碼*@param  speed  類型 int  串口速度*@return  void*/int speed_arr[] = { B38400, B19200, B9600, B4800, B2400, B1200, B300,          B38400, B19200, B9600, B4800, B2400, B1200, B300, };int name_arr[] = {38400,  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 < sizeof(speed_arr) / sizeof(int);  i++) {     if  (speed == name_arr[i]) {           tcflush(fd, TCIOFLUSH);           cfsetispeed(&Opt, speed_arr[i]);        cfsetospeed(&Opt, speed_arr[i]);         status = tcsetattr(fd1, TCSANOW, &Opt);        if  (status != 0) {                perror("tcsetattr fd1");          return;           }          tcflush(fd,TCIOFLUSH);       }    }}

效驗位和停止位的設定:

無效驗 8位 Option.c_cflag &= ~PARENB;
Option.c_cflag &= ~CSTOPB;
Option.c_cflag &= ~CSIZE;
Option.c_cflag |= ~CS8;
奇效驗(Odd) 7位 Option.c_cflag |= ~PARENB;
Option.c_cflag &= ~PARODD;
Option.c_cflag &= ~CSTOPB;
Option.c_cflag &= ~CSIZE;
Option.c_cflag |= ~CS7;
偶效驗(Even) 7位 Option.c_cflag &= ~PARENB;
Option.c_cflag |= ~PARODD;
Option.c_cflag &= ~CSTOPB;
Option.c_cflag &= ~CSIZE;
Option.c_cflag |= ~CS7;
Space效驗 7位 Option.c_cflag &= ~PARENB;
Option.c_cflag &= ~CSTOPB;
Option.c_cflag &= &~CSIZE;
Option.c_cflag |= CS8;

設定效驗的函數:

/***@brief   設定串口資料位元,停止位和效驗位*@param  fd     類型  int  開啟的串口檔案控制代碼*@param  databits 類型  int 資料位元   取值 為 7 或者8*@param  stopbits 類型  int 停止位   取值為 1 或者2*@param  parity  類型  int  效驗類型 取值為N,E,O,,S*/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 bits\n");   return (FALSE); } /* Set input parity option */ if (parity != 'n')   options.c_iflag |= INPCK; tcflush(fd,TCIFLUSH);options.c_cc[VTIME] = 150; /* 設定逾時15 seconds*/   options.c_cc[VMIN] = 0; /* Update the options and do it NOW */if (tcsetattr(fd,TCSANOW,&options) != 0)   { perror("SetupSerial 3");   return (FALSE);  } return (TRUE);  }

需要注意的是:

如果不是開發終端之類的,只是串口傳輸資料,而不需要串口來處理,那麼使用原始模式(Raw Mode)方式來通訊,設定方式如下:

options.c_lflag  &= ~(ICANON | ECHO | ECHOE | ISIG);  /*Input*/options.c_oflag  &= ~OPOST;   /*Output*/

回頁首

讀寫串口

設定好串口之後,讀寫串口就很容易了,把串口當作檔案讀寫就是。

  • 發送資料

    char  buffer[1024];int    Length;int    nByte;nByte = write(fd, buffer ,Length)
  • 讀取串口資料

    使用檔案操作read函數讀取,如果設定為原始模式(Raw Mode)傳輸資料,那麼read函數返回的字元數是實際串口收到的字元數。

    可以使用操作檔案的函數來實現非同步讀取,如fcntl,或者select等來操作。

    char  buff[1024];int    Len;int  readByte = read(fd,buff,Len);

回頁首

關閉串口

關閉串口就是關閉檔案。

close(fd);

回頁首

例子

下面是一個簡單的讀取串口資料的例子,使用了上面定義的一些函數和標頭檔

/**********************************************************************代碼說明:使用串口二測試的,發送的資料是字元,但是沒有發送字串結束符號,所以接收到後,後面加上了結束符號。我測試使用的是單片機發送資料到第二個串口,測試通過。**********************************************************************/#define FALSE  -1#define TRUE   0/*********************************************************************/int OpenDev(char *Dev){intfd = open( Dev, O_RDWR );         //| O_NOCTTY | O_NDELAYif (-1 == fd){ perror("Can't Open Serial Port");return -1;}elsereturn fd;}int main(int argc, char **argv){int fd;int nread;char buff[512];char *dev  = "/dev/ttyS1"; //串口二fd = OpenDev(dev);set_speed(fd,19200);if (set_Parity(fd,8,1,'N') == FALSE)  {printf("Set Parity Error\n");exit (0);}while (1) //迴圈讀取資料{   while((nread = read(fd, buff, 512))>0){ printf("\nLen %d\n",nread); buff[nread+1] = '\0';   printf( "\n%s", buff);   }}//close(fd);  // exit (0);}

參考資料

  • Serial Programming Guide for POSIX Operating Systems

  • Linux 的原始碼
  • 代碼下載: 代碼

關於作者

左錦,就職南沙資訊科技園,喜愛 Linux,Java 還有藍天白雲青山綠水。通過 zuo170@163.com和他聯絡。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.