树莓派使用uart串口与串口设备通信


树莓派硬件版本:

二代B+


树莓派系统版本

root@raspberrypiroot@raspberrypi:~# lsb_release -a
No LSB modules are available.
Distributor ID:Raspbian
Description:Raspbian GNU/Linux 8.0 (jessie)
Release:8.0
Codename:jessie



修改文件:vim  /boot/cmdline.txt

改成下面这样
root@raspberrypi:~# cat /boot/cmdline.txt
dwc_otg.lpm_enable=0  console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait


重启树莓派:

root@raspberrypi:~# reboot



将树莓派的串口与其他串口设备连接起来

树莓派GND --> GND串口设备

树莓派TXD --> RXD串口设备

树莓派TXD --> RXD串口设备


使用pyserial
root@raspberrypi:~# apt-get install python-serial
一个字符内容"return "回显程序,加上"return "
波特率:9600
root@raspberrypi:~# vim python_serial.py
# -*- coding: utf-8 -*  
import serial  
import time  
# 打开串口  
ser = serial.Serial("/dev/ttyAMA0", 9600)  
def main():  
    while True:  
        # 获得接收缓冲区字符  
        count = ser.inWaiting()  
        if count != 0:  
            # 读取内容并回显  
            recv = ser.read(count)+"....return\n\n" 
            ser.write(recv)  
        # 清空接收缓冲区  
        ser.flushInput()  
        # 必要的软件延时  
        time.sleep(0.1)  
     
if __name__ == '__main__':  
    try:  
        main()  
    except KeyboardInterrupt:  
        if ser != None:  
            ser.close() 
运行程序:
root@raspberrypi:~# python python_serial.py


测试图

树莓派使用uart串口与串口设备通信_第1张图片


你可能感兴趣的:(使用,树莓派,UART)