转:Python通过pyserial控制串口操作

https://blog.csdn.net/lovelyaiq/article/details/48101487

你想通过串行端口读写数据,典型场景就是和一些硬件设备打交道(比如一个机器人或传感器)。尽管你可以通过使用Python内置的I/O模块来完成这个任务,但对于串行通信最好的选择是使用 pySerial包 。 这个包的使用非常简单,先安装pySerial,使用类似下面这样的代码就能很容易的打开一个串行端口:

一、用python操作串口,首先需要下载相关模块:

pyserial (http://pyserial.wiki.sourceforge.net/pySerial)

pywin32 (http://sourceforge.net/projects/pywin32/)

import serial
    ser = serial . Serial(‘/dev/tty.usbmodem641‘, # Device name varies
                          baudrate = 9600,
                          bytesize = 8,
                          parity = ‘N‘,
                          stopbits = 1)

设备名对于不同的设备和操作系统是不一样的。 比如,在Windows系统上,你可以使用0,1等表示的一个设备来打开通信端”COM0”和”COM1”。 一旦端口打开,那就可以使用read() , readline() 和 write() 函数读写数据了。

二,十六进制显示

十六进制显示的实质是把接收到的字符转换成其对应的ASCII码,然后将ASCII码值再转换成十六进制数显示出来,这样就可以显示特殊字符了。在这里定义了一个函数,如hexShow(argv),代码如下:

[python] view plain copy

import serial

def hexShow(argv):  
    result = ‘‘  
    hLen = len(argv)  
    for i in xrange(hLen):  
        hvol = ord(argv[i])  
        hhex = ‘%02x‘%hvol  
        result += hhex+‘ ‘  
    print ‘hexShow:‘,result  
 
t = serial.Serial(‘com12‘,9600)  
print t.portstr  
strInput = raw_input(‘enter some words:‘)  
n = t.write(strInput)  
print n  
str = t.read(n)  
print str  
hexShow(str)

3,十六进制发送

十六进制发送实质是发送十六进制格式的字符串,如‘\xaa‘,‘\x0b‘。重点在于怎么样把一个字符串转换成十六进制的格式,有两个误区:

1)‘\x‘+‘aa‘是不可以,涉及到转义符反斜杠

2)‘\\x‘+‘aa‘和r‘\x‘+‘aa‘也不可以,这样的打印结果虽然是\xaa,但赋给变量的值却是‘\\xaa‘

这里用到decode函数,

[python] view plain copy

list=‘aabbccddee‘  
hexer=list.decode("hex")  
print  hexer

需要注意一点,如果字符串list的长度为奇数,则decode会报错,可以按照实际情况,用字符串的切片操作,在字符串的开头或结尾加一个‘0‘

假如在串口助手以十六进制发送字符串"abc",那么你在python中则这样操作“self.l_serial.write(”\x61\x62\x63") ”

当然,还有另外一个方法:

[python] view plain copy

strSerial = "abc"  
strHex = binascii.b2a_hex(strSerial)  
#print strHex  
strhex = strHex.decode("hex")  
#print strhex  
self.l_serial.write(strhex);

Short introduction
Open port 0 at "9600,8,N,1", no timeout
[text] view plain copy

>>> import serial  
    >>> ser = serial.Serial(0)  # open first serial port  
    >>> print ser.portstr       # check which port was really used  
    >>> ser.write("hello")      # write a string  
    >>> ser.close()             # close port

Open named port at "19200,8,N,1", 1s timeout
[text] view plain copy

>>> ser = serial.Serial(‘/dev/ttyS1‘, 19200, timeout=1)  
    >>> x = ser.read()          # read one byte  
    >>> s = ser.read(10)        # read up to ten bytes (timeout)  
    >>> line = ser.readline()   # read a ‘\n‘ terminated line  
    >>> ser.close()

Open second port at "38400,8,E,1", non blocking HW handshaking
[text] view plain copy

>>> ser = serial.Serial(1, 38400, timeout=0,  
    ...                     parity=serial.PARITY_EVEN, rtscts=1)  
    >>> s = ser.read(100)       # read up to one hundred bytes  
    ...                         # or as much is in the buffer

Get a Serial instance and configure/open it later

>>> ser = serial.Serial()
>>> ser.baudrate = 19200
>>> ser.port = 0
>>> ser
Serial<id=0xa81c10, open=False>(port=‘COM1‘, baudrate=19200, bytesize=8, parity=‘N‘, stopbits=1, timeout=None, xonxoff=0, rtscts=0)
>>> ser.open()
>>> ser.isOpen()
True
>>> ser.close()
>>> ser.isOpen()
False

Parameters for the Serial class
[text] view plain copy

ser = serial.Serial(  
    port=None,              # number of device, numbering starts at  
    # zero. if everything fails, the user  
    # can specify a device string, note  
    # that this isn‘t portable anymore  
    # if no port is specified an unconfigured  
    # an closed serial port object is created  
    baudrate=9600,          # baud rate  
    bytesize=EIGHTBITS,     # number of databits  
    parity=PARITY_NONE,     # enable parity checking  
    stopbits=STOPBITS_ONE,  # number of stopbits  
    timeout=None,           # set a timeout value, None for waiting forever  
    xonxoff=0,              # enable software flow control  
    rtscts=0,               # enable RTS/CTS flow control  
    interCharTimeout=None   # Inter-character timeout, None to disable  
    )

The port is immediately opened on object creation, if a port is given. It is not opened if port is None.
Options for read timeout:
[text] view plain copy

timeout=None            # wait forever  
    timeout=0               # non-blocking mode (return immediately on read)  
    timeout=x               # set timeout to x seconds (float allowed)

Methods of Serial instances
[text] view plain copy

open()                  # open port  
    close()                 # close port immediately  
    setBaudrate(baudrate)   # change baud rate on an open port  
    inWaiting()             # return the number of chars in the receive buffer  
    read(size=1)            # read "size" characters  
    write(s)                # write the string s to the port  
    flushInput()            # flush input buffer, discarding all it‘s contents  
    flushOutput()           # flush output buffer, abort output  
    sendBreak()             # send break condition  
    setRTS(level=1)         # set RTS line to specified logic level  
    setDTR(level=1)         # set DTR line to specified logic level  
    getCTS()                # return the state of the CTS line  
    getDSR()                # return the state of the DSR line  
    getRI()                 # return the state of the RI line  
    getCD()                 # return the state of the CD line

Attributes of Serial instances
Read Only:
[text] view plain copy

portstr                 # device name  
    BAUDRATES               # list of valid baudrates  
    BYTESIZES               # list of valid byte sizes  
    PARITIES                # list of valid parities  
    STOPBITS                # list of valid stop bit widths

New values can be assigned to the following attributes, the port will be reconfigured, even if it‘s opened at that time:

[text] view plain copy

port                    # port name/number as set by the user  
    baudrate                # current baud rate setting  
    bytesize                # byte size in bits  
    parity                  # parity setting  
    stopbits                # stop bit with (1,2)  
    timeout                 # timeout setting  
    xonxoff                 # if Xon/Xoff flow control is enabled  
    rtscts                  # if hardware flow control is enabled

Exceptions
[text] view plain copy

serial.SerialException

Constants
parity:
[text] view plain copy

serial.PARITY_NONE  
    serial.PARITY_EVEN  
    serial.PARITY_ODD

stopbits:
[text] view plain copy

serial.STOPBITS_ONE  
    al.STOPBITS_TWO

bytesize:
[text] view plain copy

serial.FIVEBITS  
    serial.SIXBITS  
    serial.SEVENBITS  
    serial.EIGHTBITS  
---------------------
作者:TiRan_Yang
来源:CSDN
原文:https://blog.csdn.net/lovelyaiq/article/details/48101487
版权声明:本文为博主原创文章,转载请附上博文链接!

原文地址:https://www.cnblogs.com/yay1688/p/9961116.html

时间: 2024-08-29 13:53:24

转:Python通过pyserial控制串口操作的相关文章

Raspberry pi 使用python+pySerial实现串口通信(转)

Raspberry pi 使用python+pySerial实现串口通信 转:http://blog.csdn.net/homeway999/article/details/8642353 目录(?)[+] Raspberry pi 使用pythonpySerial实现串口通信 Raspberry pi端安装pyserial 方法1source安装 方法2pip安装 Raspberry pi端连接串口 Windows端连接串口 Raspberry pi 使用python+pySerial实现串口

V-rep学习笔记:串口操作

VREP Regular API提供了串口操作的相关函数,可以对串口进行打开.关闭和读写: 下面使用一款淘宝上常见的AHRS(Attitude and heading reference system,航姿参考系统)模块来驱动VREP中的虚拟模型,控制其姿态.VREP通过串口读取传感器实时发送的数据并进行解析. 传感器通过串口发送2种数据: 解算后的姿态角和气压高度等数据 原始的传感器ADC数据(直接从传感器读取出来的测量值,没有经过解算处理) 下面是VREP中以16进制显示的接收到的串口数据:

MATLAB串口操作和GUI编程

简单的MATLAB GUI编程和串口控制.Word编辑,如需PDF版本,请留言.说实话这个挺难看的……     概述 本文介绍了程序AD9512_Serial_GUI的编程思路和功能.该程序设计到MATLAB的图像用户界面编程的基本方法和串口的基本操作.程序目的在于通过串口写控制字对AD9512进行配置(AD9512通过SPI写入寄存器,本程序只是整个控制程序中的一部分). 修订历史 以下表格展示了本文档的修订过程 日期 版本号 修订内容 2015/01/15 V0.0 初始版本,试验版[1]

三、python的流程控制

三.python的流程控制 1.顺序结构 python和shell,java等语言都有一定的执行顺序即顺序结构. python语言在解释器中的执行顺序是:从上到下依次执行,从左到右执行,所以函数或者变量必须先声明后调用. 2.分支选择结构 在python中只有if选择结构,没有java里的switch...case..结构和shell里的case ...;;;....esac结构,并且与java中的用法规则相似,但是语法格式不一样. 当表达式的结果是数据类型里面的布尔型中的true时,执行if后

学习python对文件内容的操作

在Python中对文件的操作使用open(filename,"w"),这里filename是文件名称,w指写入操作,会自动覆盖文件中的所有内容,还有r读操作和a追加操作等. 需要注意的是:只能同时进行一项操作,比如写的时候不能读,即使你使用w+参数,也只是读出来空白内容,不过不会报错,所有执行完一项操作使用新的参数才能继续不同的操作,如: f = open(filename,'w')  #以写操作打开文件filename,文件存在则覆盖,不存在则建立 f.write('this is 

Python中列表list常见操作

主要涉及知识点 列表是我们python里面最常见的数据类型,我们主要有以下的操作. 1.索引 2.切片 3.追加 4.删除 5.长度 6.循环 (也称遍历) 7.包含 8.嵌套 例如定义列表: List2=['openstack','python','linux',"docker","zabbix","nginx","linux","linux","123","ww33##&q

Python/C++ 对字符串的操作

字符串操作在任何语言中都很常用. 本文列举了一些常见的Python/c++ 对字符串的操作. c++ 的使用了boost libraray,  所涉及到的函数都在  <boost/algorithm/string.hpp> 中定义.   python  c++ 大小写转换 'str'.upper(),  'str'.lower() boost::to_upper('str'), boost::to_upper_copy('str') 字符串包含某个substr str.find(substr)

QT5 串口操作

Qt5 提供了两个类用于串口操作,分别是:QSerialPort和QSerialPortInfo. 最基本的操作示例代码如下: 1 #ifndef DIALOG_H 2 #define DIALOG_H 3 4 #include <QDialog> 5 6 #include <QDebug> 7 #include <QSerialPort> 8 #include <QSerialPortInfo> 9 10 namespace Ui { 11 class D

WPF获取控件内部的ScrollViewer,并控制ScrollViewer操作

//获取内部  ScrollViewer方法 public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject        {            if (obj != null)            {                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)