python串口编程_python串口通信
首先,应该安装serial模块pySeiral,还能开始后续的操作。在windows环境最好安装32位的python,否则可能无法安装pySerial,原因不明,如果有人解决该问题,可留言告诉我。
1、字符串的发送接收
短接串口的2、3脚,创建一个文本,如:
import serial
t = serial.Serial('com12',9600)
n = t.write('you are my world')
print t.portstr
print n
str = t.read(n)
print str或者你可以稍微添加几句,变成你任意输入后打印出你的键入信息。
import serial
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其中,read(value)方法的参数value为需要读取的字符长度。 如果想要全部读取,提供两个方法:
1)inWaiting():监测接收字符。 inWaitting返回接收字符串的长度值,然后把这个值赋给read做参数。
2)readall():读取全部字符,使用该函数由于是阻塞模式,除非接受的字符串以EOF结尾或者超出缓冲区,否则函数不会返回。一般要结合超时设置,设置串口的timeout参数
import serial
ser = serial.Serial('com2')
while 1:
n = ser.inWaiting()
str = ser.read(n)
if str:
print strimport serial
ser = serial.Serial('com2',timeout=0.01) # open first serial port
while 1:
str = ser.readall()
if str:
print str
2,十六进制显示
十六进制显示的实质是把接收到的字符诸葛转换成其对应的ASCII码,然后将ASCII码值再转换成十六进制数显示出来,这样就可以显示特殊字符了。
在这里定义了一个函数,如hexShow(argv),代码如下:
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'
list='aabbccddee'
hexer=list.decode("hex")
print hexer
需要注意一点,如果字符串list的长度为奇数,则decode会报错,可以按照实际情况,用字符串的切片操作,在字符串的开头或结尾加一个'0'
假如在串口助手以十六进制发送字符串"abc",那么你在python中则这样操作“self.l_serial.write(”\x61\x62\x63") ”
当然,还有另外一个方法:
strSerial = "abc"
strHex = binascii.b2a_hex(strSerial)
#print strHex
strhex = strHex.decode("hex")
#print strhex
self.l_serial.write(strhex);
附pySerial基本属性和方法说明
Overview
This module encapsulates the access for the serial port. It provides backends for Python running on Windows, Linux, BSD (possibly any POSIX compliant system), Jython
and IronPython (.NET and Mono). The module named "serial" automatically selects the appropriate backend.
It is released under a free software license, seeLICENSE.txtfor
more details.
(C) 2001-2008 Chris Liechticliechti@gmx.net
Theproject
page on SourceForgeand here is theSVN
repositoryand theDownload
Page.
The homepage is onhttp://pyserial.sf.net/
Features
same class based interface on all supported platforms
access to the port settings through Python 2.2+ properties
port numbering starts at zero, no need to know the port name in the user program
port string (device name) can be specified if access through numbering is inappropriate
support for different bytesizes, stopbits, parity and flow control with RTS/CTS and/or Xon/Xoff
working with or without receive timeout
file like API with "read" and "write" ("readline" etc. also supported)
The files in this package are 100% pure Python. They depend on non standard but common packages on Windows (pywin32) and Jython (JavaComm). POSIX (Linux, BSD) uses only modules from the standard Python distribution)
The port is set up for binary transmission. No NULL byte stripping, CR-LF translation etc. (which are many times enabled for POSIX.) This makes this module universally useful.
Requirements
Python 2.2 or newer
pywin32 extensions on Windows
"Java Communications" (JavaComm) or compatible extension for Java/Jython
Installation
from source
Extract files from the archive, open a shell/console in that directory and let Distutils do the rest:
python setup.py install
The files get installed in the "Lib/site-packages" directory.
easy_install
An EGG is available from the Python Package Index:http://pypi.python.org/pypi/pyserial
easy_install pyserial
windows installer
There is also a Windows installer for end users. It is located in theDownload
Page
Developers may be interested to get the source archive, because it contains examples and the readme.
Short introduction
Open port 0 at "9600,8,N,1", no timeout
>>> 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
>>> 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
>>> 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(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
Be carefully when using "readline". Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received. Also note
that "readlines" only works with a timeout. "readlines" depends on having a timeout and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly.
Do also have a look at the example files in the examples directory in the source distribution or online.
Examples
Please look in the SVN Repository. There is an example directory where you can find a simple terminal and more.
http://pyserial.svn.sourceforge.net/viewvc/pyserial/trunk/pyserial/examples/
Parameters for the Serial class
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:
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
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:
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:
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
serial.SerialException
Constants
parity:
serial.PARITY_NONE
serial.PARITY_EVEN
serial.PARITY_ODD
stopbits:
serial.STOPBITS_ONE
serial.STOPBITS_TWO
bytesize:
serial.FIVEBITS
serial.SIXBITS
serial.SEVENBITS
serial.EIGHTBITS
python串口编程_python串口通信相关推荐
- 单片机 串口编程之串口通信仿真实验
单片机 串口编程之串口通信仿真实验 一.简述 记--简单的使能串口,串口收发数据的例子.(使用Proteus仿真+虚拟串口调试) 代码,仿真文件打包:链接: https:/ ...
- python树莓派编程_python树莓派编程
广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 例如,你可以用树莓派搭建你自己的家用云存储服务器.? 树莓派用python来进行 ...
- 面向串口编程java_Java串口编程例子
最近笔者接触到串口编程,网上搜了些资料,顺便整理一下.网上都在推荐使用Java RXTX开源类库,它提供了Windows.Linux等不同操作系统下的串口和并口通信实现,遵循GNU LGPL协议.看起 ...
- python socket编程_Python学习记录-socket编程
1. OSI七层模型详解 2. Python socket 什么是 Socket? Socket又称"套接字",应用程序通常通过"套接字"向网络发出请求或者应答 ...
- QT学习串口编程之串口软件的UI设计
学会了如何使用QT进行界面设计之后,接下来让我们来进入第二阶段的学习--串口编程吧. 首先我们需要对串口软件的UI界面进行仿写. 首先存在一个接收方和发送方,接收框主要是串口软件接收设备发来的数据,发 ...
- python 网络编程_Python网络编程(原书第2版)
Python网络编程(原书第2版) 作者:(美)埃里克·周(Eric Chou) 著 出版日期:2019年06月 文件大小:54.50M 支持设备: ¥68.00 适用客户端: 言商书局 iPad/i ...
- python socket编程_Python Socket编程实现网络编程
对于有经验的开发人员来说,掌握的编程语言应该是不少的.在这些编程语言中,网络编程的应用时必不可少的.其中Python也是这样的编程语言.我们今天将会在这里为大家详细介绍一下Python Socket编 ...
- python gpu编程_Python笔记_第四篇_高阶编程_进程、线程、协程_5.GPU加速
Numba:高性能计算的高生产率 在这篇文章中,笔者将向你介绍一个来自Anaconda的Python编译器Numba,它可以在CUDA-capable GPU或多核cpu上编译Python代码.Pyt ...
- python多线程编程_python多线程编程(1): python对多线程的支持
前面介绍过多线程的基本概念,理解了这些基本概念,掌握python多线程编程就比较容易了. 在开始之前,首先要了解一下python对多线程的支持. 虚拟机层面 Python虚拟机使用GIL(Global ...
最新文章
- 【Redis学习笔记】2018-06-12 复制与传播
- 光流 | OpenCV实现简单的optical flow(代码类)
- muduo网络库学习(六)缓冲区Buffer及TcpConnection的读写操作
- 什么是迭代器,JS如何实现迭代器
- 高效的企业测试-结论(6/6)
- springmvc为什么不能拦截jsp页面?
- 戴尔SC5020发布,专为提高效率/经济性优化设计的中端存储利器
- 阿里云智能 AIoT 首席科学家丁险峰:阿里全面进军 IoT 这一年 | 问底中国 IT 技术演进
- PHP批量去除PHP文件中bom的代码
- 2058. 笨拙的手指
- 分享一个小软件fences(桌面管理软件)
- 协同级CRM能帮助企业带来哪些管理提升?
- oracle招聘ocp认证,OracleOCP认证要通过哪些考试?
- html默认样式重置,我们真的需要CSS重置来清除默认样式吗?
- 婚庆行业发展报告,2021怎么精准引流?
- 整数大小比较(YZOJ-1034)
- html模板渲染引擎有什么作用
- 不错的在线印章生成器网站
- 1814 Problem A 剩下的树
- 腾讯/阿里/百度 BAT人才体系的职位层级、薪酬、晋升标准
热门文章
- [CC]CC插件初探
- WeUI 为微信 Web 服务量身设计-h5前端框架
- paip.gui控件tabs控件加载内容的原理以及easyui最佳实现
- java json返回null_java-JSON jsonObject.optString()返回字符串“ null”
- 信息学奥赛一本通 1013:温度表达转化 | OpenJudge NOI 1.3 08
- 数列极差(信息学奥赛一本通-T1427)
- 动态规划 —— 线性 DP —— 序列问题
- Maximum sum(信息学奥赛一本通-T1305)
- Catch him(HDU-2351)
- 8 SD配置-企业结构-分配-给公司代码分配销售组织