树莓派串口

来源:互联网 发布:北京工业大学软件 编辑:程序博客网 时间:2024/06/05 11:45

串口使用例程及说明:http://elinux.org/Serial_port_programming

http://elinux.org/RPi_Serial_Connection

Pyserial API https://pyserial.readthedocs.io/en/latest/pyserial_api.html

sudo apt-get install python-serial

 

python -m serial.tools.list_ports 此命令可以查看设备的文件节点。

 

class serial.Serial  

  

    __init__(port=None, baudrate=9600, bytesize=EIGHTBITS, parity=PARITY_NONE, stopbits=STOPBITS_ONE, timeout=None, xonxoff=False, rtscts=False, writeTimeout=None, dsrdtr=False, interCharTimeout=None)  

 

port:读或者写端口

baudrate:波特率

bytesize:字节大小

parity:校验位

stopbits:停止位

timeout:读超时设置

writeTimeout:写超时

xonxoff:软件流控

rtscts:硬件流控

dsrdtr:硬件流控

interCharTimeout:字符间隔超时

timeout 与read():

timeout = None一直等待,直到接受到数据

timeout = 0: 非阻塞

timeout = x: 等待时长

write() 默认阻塞, 除非write_timeout 被设置.

 

read(size=1):从串口读size个字节。返回读到的数据。如果指定超时,则可能在超时后返回较少的字节;如果没有指定超时,则会一直等到收完指定的字节数。

write(data):发送data,并返回发送字节数。如果bytesbytearray可用(python 2.6以上),则接受其作为参数;否则接受str作为参数。

异常:SerialTimeoutException——配置了写超时并发生超时时发生此异常。

inWaiting():返回接收缓存中的字节数

例程:

#!/usr/bin/env pythonimport serialimport timedef uart(port):rv_buf=""ch=''while True:ch=port.read();rv_buf+=chif ch=='' or ch=='\r':return rv_bufsend_buf=""port=serial.Serial("/dev/ttyUSB0",baudrate=115200,timeout=None)while True:send_buf=uart(port)port.write(send_buf)print(send_buf)

用串口接受数据,单路的简单接受我们已经调试成功了。但是在实际应用过程中,需要用到多路。因此目前的想法是通过select来实现。

首先简单学习一下python中的select

Pythonselect()方法直接调用操作系统的IO接口,它监控sockets,open files, and pipes(所有带fileno()方法的文件句柄)何时变成readablewriteable,或者通信错误。

 

Select的用法很简单,select( iwtd, owtd, ewtd[, timeout])前三个参数是‘等待对象’。这三个参数分别按顺序等待输入、输出和异常状态。允许空数组timeout参数接受浮点数表示的秒。如果省略 timeout将会阻塞直到至少一个文件描述符准备就绪。timeout0表示从不阻塞。这里在串口接收进程中是阻塞的操作,一直在阻塞,等待数据,防止数据丢失。

返回值是包含前三个参数里面已准备就绪的对象的3个列表.如果已经超时但是并没有对象准备就绪,那么返回3个空列表

#!/usr/bin/env pythonimport selectimport serialimport timeimport multiprocessing def uart(port):rv_buf=""ch=''while True:ch=port.read()rv_buf+=chif ch=='' or ch=='\r':return rv_bufdef uart_trans():send_buf0=""send_buf1=""i=0port0=serial.Serial("/dev/myuart0",baudrate=115200,timeout=0)port1=serial.Serial("/dev/ttyUSB1",baudrate=115200,timeout=0)fd0=file("/dev/myuart0","r+")fd1=file("/dev/ttyUSB1","r+")while True:rlist,wlist,elist=select.select([fd0,fd1],[],[],)for fd in rlist:if(fd==fd0):send_buf0=uart(port0)port0.write(send_buf0)if(fd==fd1):send_buf1=uart(port1)port1.write(send_buf1)if __name__ =="__main__":uart_trans()

测试源码:https://github.com/IJustLoveMyself/Raspberry-Pi/blob/master/test1/uart.py

https://github.com/IJustLoveMyself/Raspberry-Pi/blob/master/test1/select.py