python操作串口.docx
《python操作串口.docx》由会员分享,可在线阅读,更多相关《python操作串口.docx(10页珍藏版)》请在冰豆网上搜索。
python操作串口
python串口编程整理(更新完)
分类:
python2012-06-0710:
3613027人阅读评论(3)收藏举报
python编程importhexinputlist
python的串口网上有很多例子,这里了只是把认为好的整理到一起。
首先,应该安装serial模块,还能开始后续的操作。
我用的python2.6,serial模块可以在这里下载安装serial模块下载
1,字符串的发送接收
短接串口的2、3脚,创建一个文本,如:
[python]viewplaincopy
importserial
t=serial.Serial('com12',9600)
n=t.write('youaremyworld')
printt.portstr
printn
str=t.read(n)
printstr
或者你可以稍微添加几句,变成你任意输入后打印出你的键入信息。
[python]viewplaincopy
importserial
t=serial.Serial('com12',9600)
printt.portstr
strInput=raw_input('entersomewords:
')
n=t.write(strInput)
printn
str=t.read(n)
printstr
其中,read(value)方法的参数value为需要读取的字符长度。
如果想要全部读取,提供两个方法:
1)inWaiting:
:
监测接收字符。
inWaitting返回接收字符串的长度值,然后把这个值赋给read做参数。
2)readall():
:
读取全部字符。
===================================================================================================================================
2,十六进制显示
十六进制显示的实质是把接收到的字符逐个转换成其对应的ASCII码,然后将ASCII码值再转换成十六进制数显示出来,这样就可以显示特殊字符了。
在这里定义了一个函数,如hexShow(argv),代码如下:
[python]viewplaincopy
importserial
defhexShow(argv):
result=''
hLen=len(argv)
foriinxrange(hLen):
hvol=ord(argv[i])
hhex='%02x'%hvol
result+=hhex+''
print'hexShow:
',result
t=serial.Serial('com12',9600)
printt.portstr
strInput=raw_input('entersomewords:
')
n=t.write(strInput)
printn
str=t.read(n)
printstr
hexShow(str)
===================================================================================================================================
Note:
xrange()函数:
Likerange(),butinsteadofreturningalist,returnsanobjectthatgeneratesthenumbersintherangeondemand.Forlooping,thisisslightlyfasterthanrange()andmorememoryefficient.
3,十六进制发送
十六进制发送实质是发送十六进制格式的字符串,如'\xaa','\x0b'。
重点在于怎么样把一个字符串转换成十六进制的格式,有两个误区:
1)'\x'+'aa'是不可以,涉及到转义符反斜杠
2)'\\x'+'aa'和r'\x'+'aa'也不可以,这样的打印结果虽然是\xaa,但赋给变量的值却是'\\xaa'
这里用到decode函数,
[python]viewplaincopy
list='aabbccddee'
hexer=list.decode("hex")
printhexer
需要注意一点,如果字符串list的长度为奇数,则decode会报错,可以按照实际情况,用字符串的切片操作,在字符串的开头或结尾加一个'0'
假如在串口助手以十六进制发送字符串"abc",那么你在python中则这样操作“self.l_serial.write(”\x61\x62\x63")”
当然,还有另外一个方法:
[python]viewplaincopy
strSerial="abc"
strHex=binascii.b2a_hex(strSerial)
#printstrHex
strhex=strHex.decode("hex")
#printstrhex
self.l_serial.write(strhex);
同样可以达到相同目的。
那么,串口方面的就整理完了。
一、
为了使用python操作串口,首先需要下载相关模块:
pyserial(
pywin32(
2,十六进制显示
十六进制显示的实质是把接收到的字符诸葛转换成其对应的ASCII码,然后将ASCII码值再转换成十六进制数显示出来,这样就可以显示特殊字符了。
在这里定义了一个函数,如hexShow(argv),代码如下:
[python]viewplaincopy
importserial
defhexShow(argv):
result=''
hLen=len(argv)
foriinxrange(hLen):
hvol=ord(argv[i])
hhex='%02x'%hvol
result+=hhex+''
print'hexShow:
',result
t=serial.Serial('com12',9600)
printt.portstr
strInput=raw_input('entersomewords:
')
n=t.write(strInput)
printn
str=t.read(n)
printstr
hexShow(str)
===================================================================================================================================
3,十六进制发送
十六进制发送实质是发送十六进制格式的字符串,如'\xaa','\x0b'。
重点在于怎么样把一个字符串转换成十六进制的格式,有两个误区:
1)'\x'+'aa'是不可以,涉及到转义符反斜杠
2)'\\x'+'aa'和r'\x'+'aa'也不可以,这样的打印结果虽然是\xaa,但赋给变量的值却是'\\xaa'
这里用到decode函数,
[python]viewplaincopy
list='aabbccddee'
hexer=list.decode("hex")
printhexer
需要注意一点,如果字符串list的长度为奇数,则decode会报错,可以按照实际情况,用字符串的切片操作,在字符串的开头或结尾加一个'0'
假如在串口助手以十六进制发送字符串"abc",那么你在python中则这样操作“self.l_serial.write(”\x61\x62\x63")”
当然,还有另外一个方法:
[python]viewplaincopy
strSerial="abc"
strHex=binascii.b2a_hex(strSerial)
#printstrHex
strhex=strHex.decode("hex")
#printstrhex
self.l_serial.write(strhex);
同样可以达到相同目的。
那么,串口方面的就整理完了
Overview
Thismoduleencapsulatestheaccessfortheserialport.ItprovidesbackendsforPythonrunningonWindows,Linux,BSD(possiblyanyPOSIXcompliantsystem),JythonandIronPython(.NETandMono).Themodulenamed"serial"automaticallyselectstheappropriatebackend.
Itisreleasedunderafreesoftwarelicense,seeLICENSE.txtformoredetails.
(C)2001-2008ChrisLiechticliechti@
TheprojectpageonSourceForgeandhereistheSVNrepositoryandtheDownloadPage.
Thehomepageison
Features
sameclassbasedinterfaceonallsupportedplatforms
accesstotheportsettingsthroughPython2.2+properties
portnumberingstartsatzero,noneedtoknowtheportnameintheuserprogram
portstring(devicename)canbespecifiedifaccessthroughnumberingisinappropriate
supportfordifferentbytesizes,stopbits,parityandflowcontrolwithRTS/CTSand/orXon/Xoff
workingwithorwithoutreceivetimeout
filelikeAPIwith"read"and"write"("readline"etc.alsosupported)
Thefilesinthispackageare100%purePython.TheydependonnonstandardbutcommonpackagesonWindows(pywin32)andJython(JavaComm).POSIX(Linux,BSD)usesonlymodulesfromthestandardPythondistribution)
Theportissetupforbinarytransmission.NoNULLbytestripping,CR-LFtranslationetc.(whicharemanytimesenabledforPOSIX.)Thismakesthismoduleuniversallyuseful.
Requirements
Python2.2ornewer
pywin32extensionsonWindows
"JavaCommunications"(JavaComm)orcompatibleextensionforJava/Jython
Installation
fromsource
Extractfilesfromthearchive,openashell/consoleinthatdirectoryandletDistutilsdotherest:
pythonsetup.pyinstall
Thefilesgetinstalledinthe"Lib/site-packages"directory.
easy_install
AnEGGisavailablefromthePythonPackageIndex:
http:
//pypi.python.org/pypi/pyserial
easy_installpyserial
windowsinstaller
ThereisalsoaWindowsinstallerforendusers.ItislocatedintheDownloadPage
Developersmaybeinterestedtogetthesourcearchive,becauseitcontainsexamplesandthereadme.
Shortintroduction
Openport0at"9600,8,N,1",notimeout
>>>importserial
>>>ser=serial.Serial(0)#openfirstserialport
>>>printser.portstr#checkwhichportwasreallyused
>>>ser.write("hello")#writeastring
>>>ser.close()#closeport
Opennamedportat"19200,8,N,1",1stimeout
>>>ser=serial.Serial('/dev/ttyS1',19200,timeout=1)
>>>x=ser.read()#readonebyte
>>>s=ser.read(10)#readuptotenbytes(timeout)
>>>line=ser.readline()#reada'\n'terminatedline
>>>ser.close()
Opensecondportat"38400,8,E,1",nonblockingHWhandshaking
>>>ser=serial.Serial(1,38400,timeout=0,
...parity=serial.PARITY_EVEN,rtscts=1)
>>>s=ser.read(100)#readuptoonehundredbytes
...#orasmuchisinthebuffer
GetaSerialinstanceandconfigure/openitlater
>>>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
Becarefullywhenusing"readline".Dospecifyatimeoutwhenopeningtheserialportotherwiseitcouldblockforeverifnonewlinecharacterisreceived.Alsonotethat"readlines"onlyworkswithatimeout."readlines"dependsonhavingatimeoutandinterpretsthatasEOF(endoffile).Itraisesanexceptioniftheportisnotopenedcorrectly.
Doalsohavealookattheexamplefilesintheexamplesdirectoryinthesourcedistributionoronline.
Examples
PleaselookintheSVNRepository.Thereisanexampledirectorywhereyoucanfindasimpleterminalandmore.
ParametersfortheSerialclass
ser=serial.Serial(
port=None,#numberofdevice,numberingstartsat
#zero.ifeverythingfails,theuser
#canspecifyadevicestring,note
#thatthisisn'tportableanymore
#ifnoportisspecifiedanunconfigured
#anclosedserialportobjectiscreated
baudrate=9600,#baudrate
bytesize=EIGHTBITS,#numberofdatabits
parity=PARITY_NONE,#enableparitychecking
stopbits=STOPBITS_ONE,#numberofstopbits
timeout=None,#setatimeoutvalue,Noneforwaitingforever
xonxoff=0,#enablesoftwareflowcontrol
rtscts=0,#enableRTS/CTSflowcontrol
interCharTimeout=None#Inter-charactertimeout,Nonetodisable
)
Theportisimmediatelyopenedonobjectcreation,ifaportisgiven.ItisnotopenedifportisNone.
Optionsforreadtimeout:
timeout=None#waitforever
timeout=0#non-blockingmode(returnimmediatelyonread)
timeout=x#settimeouttoxseconds(floatallowed)
MethodsofSerialinstances
open()#openport
close()#closeportimmediately
setBaudrate(baudrate)#changebaudrateonanopenport
inWaiting()#returnthenumberofcharsinthereceivebuffer
read(size=1)#read"size"characters
write(s)#writethestringstotheport
flushInput()#flushinputbuffer,discardingallit'scontents
flushOutput()#flushoutputbuffer,abortoutput
sendBreak()#sendbreakcondition
setRTS(level=1)#setRTSlinetospecifiedlogiclevel
setDTR(level=1)#setDTRlinetospecifiedlogiclevel
getCTS()#returnthestateoftheCTSline
getDSR()#returnthestateoftheDSRline
getRI()#returnthestateoftheRIline
getCD()#returnthestateoftheCDline
AttributesofSerialinstances
ReadOnly:
portstr#devicename
BAUDRATES#listofvalidbaudrates
BYTESIZES#listofvalidbytesizes
PARITIES#listofvalidparities
STOPBITS#listofvalidstopbitwidths
Newvaluescanbeassignedtothefollowingattributes,theportwillbereconfigured,evenifit'sopenedatthattime:
port#portname/numberassetbytheuser
baudrate#currentbaudratesetting
bytesize#bytesizeinbits
parity#paritysetting
stopbits