Raspberry Pi Zero W:串口(UART)的配置和使用
開啟UART
據官方所言(https://www.raspberrypi.org/documentation/configuration/uart.md):樹莓派CPU內部有兩個串口,一個PL001 UART和一個Mini UART。Mini UART沒有時鐘源,必須由內核提供時鐘源,而內核頻率本身是變化的,導致Mini UART速率不穩,無法正常使用。RPI ZERO W與以往老版本RPI不同,沒有將PL011 UART分配GPIO中的UART(GPIO14和GPIO15),而是將其分配給了藍牙模塊。我們需要關閉藍牙對PL011 UART的使用,恢復GPIO串口對PL011 UART的使用。
查看映射關係:
<code>$ sudo ls -l /dev/<code>
serial0是GPIO中的UART,ttyAMA0是PL001 UART。可以看到並沒有serial0文件
修改cmdline.txt文件
<code>$ sudo nano /boot/cmdline.txt/<code>
原來cmdline.txt文件的內容如下:
dwc_otg.lpm_enable=0 console=serial0,115200 console=tty1 root=PARTUUID=a05c3c8f-02 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait quiet splash plymouth.ignore-serial-consoles
將有關console的內容全部刪掉,修改後的cmdline.txt文件內容如下:
dwc_otg.lpm_enable=0 root=PARTUUID=a05c3c8f-02 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait quiet splash plymouth.ignore-serial-consoles
(2)關閉板載藍牙
禁用藍牙功能
<code>$ sudo systemctl disable hciuart/<code>
<code>$ sudo nano /boot/config.txt/<code>
增加如下一行:
<code>dtoverlay=pi3-disable-bt/<code>
重啟樹莓派
<code>$ sudo shutdown -r now/<code>
再次查看映射關係,發現serial0成功映射到ttyAMA0
(3)禁用串口的控制檯功能
編輯config.txt文件,增加如下一行:
<code>enable_uart=1/<code>
也可以使用raspi-config自動操作:
<code>sudo raspi-config/<code>
選擇第五項
開啟硬件串口
(4)重啟樹莓派
$ sudo shutdown -r now
4.2 測試
(1)安裝並導入serial模塊
<code>$ sudo pip install pyserial
$ python
>>> import serial/<code>
如圖所示模塊導入成功:
開啟串口
<code>>>> ser = serial.Serial('/dev/ttyAMA0',19200)/<code>
使用串口助手發送“hello”
成功讀取到串口助手發來的數據
# 讀取5個字符
<code>>>> ser.read(5)/<code>
# 關閉串口
<code>>>> ser.close()/<code>
原文地址:
學習筆記-Raspberry Pi Zero W-4:串口(UART)的配置和使用
https://blog.csdn.net/RambleMY/article/details/81206090
閱讀更多 老歐教你玩轉單片機 的文章