筆者通過查閱相關資料,了解了BeagleBoneBlack開發板的UART接口特性,掌握的UART接口的基本使用方法,最后通過一個C語言的例程實現串口的自發自收。有了這個串口開發板就可和其他設備進行串口通信了,比如可以將單片機通過串口掛在開發板上。
第一步:硬件連接
1、用miniUSB線將 電腦與開發板相連,BeagleBoneBlack啟動之后,在瀏覽器里面輸入192.168.7.2,打開網頁之后就可以查看相關的串口信息。
注:
(1)BeagleBoneBlack開發板的P8,P9擴展接口上共引出了四個半的串口,其中UART1,UART2,UART4,UART5四個串口的發射和接收引腳全部引出,UART3只引出了發射引腳,所以共引出了四個串口;
(2)BeagleBoneBlack開發板的UART0引腳默認作為調試引腳使用,系統上電之后UART0作為默認的打印引腳使用;
(3)接下來的實驗將會以UART4為例說明串口的使用。
2、本實驗的硬件連接如下圖所示,將P9的11,13引腳直接連接,這樣就可以實現自發自收。
3、實物圖如下
第二步:手動打開串口
1、加載設備
(1)添加環境變量:export SLOTS=/sys/devices/bone_capemgr.8/slots
注:
1)功能說明:設置或顯示環境變量。
2)語法:export [-fnp][變量名稱]=[變量設置值]
3)補充說明:在shell中執行程序時,shell會提供一組環境變量。 export可新增,修改或刪除環境變量,供后續執行的程序使用。
4)作用范圍:export的有效期僅限於於該此登陸操作。
5)參 數:
-f 代表[變量名稱]中為函數名稱。
-n 刪除指定的變量。變量實際上並未刪除,只是不會輸出到后續指令的執行環境中。
-p 列出所有的shell賦予程序的環境變量。
6)一個變量創建時,它不會自動地為在它之后創建的shell進程所知。而命令export可以向后面的shell傳遞變量的值。當一個shell腳本調用並執行時,它不會自動得到原為腳本(調用者)里定義的變量的訪問權,除非這些變量已經被顯式地設置為可用。
7)export命令可以用於傳遞一個或多個變量的值到任何后繼腳本
(2)查看環境變量:cat $SLOTS
(3)加載UART4:echo BB-UART4 > $SLOTS
(4)查看設備:ls ttyO*,ttyO4就是添加的UART4設備
注:
1)*:匹配符。ttyO*可以過濾出所有ttyO開頭的文件
2、利用minicom打開串口
注:如果想知道minicom的參數配置和相關命令,可以輸入minicom –h,如下圖所示,
注:
(1) 由上圖可知道,剛才打開的minicom時配置參數的意義;
(2)-b 9600 設置波特率
(3)-o 不初始化模塊,且鎖定啟動狀態
(4)-D /dev/ttyO4 設置驅動名稱
3、回車之后就可以進入UART4了,這時候輸入任何字符在終端上都會顯示出來。
第三步:用C語言編程實現自發自收
1、代碼如下
1 #include<stdio.h> 2 #include<fcntl.h> 3 #include<unistd.h> 4 #include<termios.h> // using the termios.h library 5 6 int main() 7 { 8 int file, count; 9 if ((file = open("/dev/ttyO4", O_RDWR | O_NOCTTY | O_NDELAY))<0) 10 { 11 perror("UART: Failed to open the file. \n"); 12 return -1; 13 } 14 struct termios options; // the termios structure is vital 15 tcgetattr(file, &options); // sets the parameters associated with file 16 // Set up the communications options: 17 // 9600 baud, 8-bit, enable receiver, no modem control lines 18 options.c_cflag = B9600 | CS8 | CREAD | CLOCAL; 19 options.c_iflag = IGNPAR | ICRNL; // ignore partity errors, CR -> newline 20 tcflush(file, TCIFLUSH); // discard file information not transmitted 21 tcsetattr(file, TCSANOW, &options); // changes occur immmediately 22 unsigned char transmit[18] = "Hello BeagleBone!"; // the string to send 23 24 if ((count = write(file, &transmit,18))<0) 25 { // send the string 26 perror("Failed to write to the output\n"); 27 return -1; 28 } 29 30 usleep(100000); // give the Arduino a chance to respond 31 unsigned char receive[100]; // declare a buffer for receiving data 32 if ((count = read(file, (void*)receive, 100))<0) 33 { // receive the data 34 perror("Failed to read from the input\n"); 35 return -1; 36 } 37 if (count==0) 38 printf("There was no data available to read! \n"); 39 else 40 { 41 printf("The following was read in [%d]: %s\n",count,receive); 42 } 43 close(file); 44 return 0; 45 }
2、實驗現象