【RPi樹莓派使用指南】樹莓派串列埠通訊介紹
阿新 • • 發佈:2019-02-09
樹莓派的外部介面中含一路UART序列介面,利用該介面可以實現樹莓派與Arduino、GPRS模組、GPS等其他外部系統的對接。
由於這一路串列埠兼做Linux的控制檯輸出口,所以在使用前必須先將除錯輸出功能關閉,方法如下:
1. 去除Kernel的啟動資訊
在/boot/cmdline.txt中,去除parameterconsole=ttyAMA0,115200,並儲存;
2. 去除Kernel的除錯資訊
同樣在/boot/cmdline.txt中,去除 kgdboc=ttyAMA0,115200,並儲存;
3. 關閉登陸提示
在 /etc/inittab中去除T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
經過以上三步,就可以正常使用序列口了。
程式設計時可以使用C語言以檔案形式操作串列埠,也可以利用python的pySerial庫進行程式設計。
這裡以C語言為例,貼出示例程式碼:
#include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <string.h> intmain(intargc, char*argv[]) { intfd, len; fd = open("/dev/ttyAMA0", O_RDWR, S_IRUSR | S_IWUSR); chartemp; while(1) { len = read(fd, &temp, 1); write(fd, &temp, 1); if(len > 0) { printf("%c", temp); } else { usleep(10); } } close(fd); return0; }