给大家带来python经由过程pyserial读写串口
如果您觉得本篇CentOSLinux教程讲得好,请记得点击右边漂浮的分享程序,把好文章分享给你的小伙伴们!由于有个须要用有源RFID弄资产治理的项目,须要用python读取读卡器的串口内容。因而装了pyserial模块,用了下很便利,整顿下经常使用功效1、
为了应用python操作串口,起首须要下载相干模块:
pyserial(http://pyserial.wiki.sourceforge.net/pySerial)pywin32(http://sourceforge.net/projects/pywin32/)
2,十六进制显示
十六进制显示的本质是把吸收到的字符诸葛转换成其对应的ASCII码,然后将ASCII码值再转换成十六进制数显示出来,如许就能够显示特别字符了。
在这里界说了一个函数,如hexShow(argv),代码以下:
viewplaincopy
importserialdefhexShow(argv):result=hLen=len(argv)foriinxrange(hLen):hvol=ord(argv)hhex=%02x%hvolresult+=hhex+printhexShow:,resultt=serial.Serial(com12,9600)printt.portstrstrInput=raw_input(entersomewords:)n=t.write(strInput)printnstr=t.read(n)printstrhexShow(str)
===================================================================================================================================
3,十六进制发送
十六进制发送本质是发送十六进制格局的字符串,如xaa,x0b。重点在于怎样把一个字符串转换成十六进制的格局,有两个误区:
1)x+aa是弗成以,触及到本义符反斜杠
2)x+aa和rx+aa也弗成以,如许的打印成果固然是xaa,但赋给变量的值倒是xaa
这里用到decode函数,
viewplaincopy
list=aabbccddeehexer=list.decode("hex")printhexer
须要留意一点,假如字符串list的长度为奇数,则decode会报错,可以依照现实情形,用字符串的切片操作,在字符串的开首或开头加一个0
假设在串口助手以十六进制发送字符串"abc",那末你在python中则如许操作“self.l_serial.write(”x61x62x63")”
固然,还有别的一个办法:
viewplaincopy
strSerial="abc"strHex=binascii.b2a_hex(strSerial)#printstrHexstrhex=strHex.decode("hex")#printstrhexself.l_serial.write(strhex);
异样可以到达雷同目标。
那末,串口方面的就整顿完了
Overview
Thismoduleencapsulatestheaccessfortheserialport.ItprovidesbackendsforPythonrunningonWindows,Linux,BSD(possiblyanyPOSIXcompliantsystem),JythonandIronPython(.NETandMono).Themodulenamed"serial"automaticallyselectstheappropriatebackend.
Itisreleasedunderafreesoftwarelicense,seeLICENSE.txtformoredetails.
(C)2001-2008ChrisLiechticliechti@gmx.net
TheprojectpageonSourceForgeandhereistheSVNrepositoryandtheDownloadPage.
Thehomepageisonhttp://pyserial.sf.net/
Features
sameclassbasedinterfaceonallsupportedplatformsaccesstotheportsettingsthroughPython2.2+propertiesportnumberingstartsatzero,noneedtoknowtheportnameintheuserprogramportstring(devicename)canbespecifiedifaccessthroughnumberingisinappropriatesupportfordifferentbytesizes,stopbits,parityandflowcontrolwithRTS/CTSand/orXon/XoffworkingwithorwithoutreceivetimeoutfilelikeAPIwith"read"and"write"("readline"etc.alsosupported)Thefilesinthispackageare100%purePython.TheydependonnonstandardbutcommonpackagesonWindows(pywin32)andJython(JavaComm).POSIX(Linux,BSD)usesonlymodulesfromthestandardPythondistribution)Theportissetupforbinarytransmission.NoNULLbytestripping,CR-LFtranslationetc.(whicharemanytimesenabledforPOSIX.)Thismakesthismoduleuniversallyuseful.
Requirements
Python2.2ornewerpywin32extensionsonWindows"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()#closeportOpennamedportat"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
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...#orasmuchisinthebufferGetaSerialinstanceandconfigure/openitlater
>>>ser=serial.Serial()>>>ser.baudrate=19200>>>ser.port=0>>>serSerial<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()FalseBecarefullywhenusing"readline".Dospecifyatimeoutwhenopeningtheserialportotherwiseitcouldblockforeverifnonewlinecharacterisreceived.Alsonotethat"readlines"onlyworkswithatimeout."readlines"dependsonhavingatimeoutandinterpretsthatasEOF(endoffile).Itraisesanexceptioniftheportisnotopenedcorrectly.Doalsohavealookattheexamplefilesintheexamplesdirectoryinthesourcedistributionoronline.
Examples
PleaselookintheSVNRepository.Thereisanexampledirectorywhereyoucanfindasimpleterminalandmore.
http://pyserial.svn.sourceforge.net/viewvc/pyserial/trunk/pyserial/examples/
ParametersfortheSerialclass
importserialdefhexShow(argv):result=hLen=len(argv)foriinxrange(hLen):hvol=ord(argv)hhex=%02x%hvolresult+=hhex+printhexShow:,resultt=serial.Serial(com12,9600)printt.portstrstrInput=raw_input(entersomewords:)n=t.write(strInput)printnstr=t.read(n)printstrhexShow(str)0Theportisimmediatelyopenedonobjectcreation,ifaportisgiven.ItisnotopenedifportisNone.
Optionsforreadtimeout:
importserialdefhexShow(argv):result=hLen=len(argv)foriinxrange(hLen):hvol=ord(argv)hhex=%02x%hvolresult+=hhex+printhexShow:,resultt=serial.Serial(com12,9600)printt.portstrstrInput=raw_input(entersomewords:)n=t.write(strInput)printnstr=t.read(n)printstrhexShow(str)1
MethodsofSerialinstances
importserialdefhexShow(argv):result=hLen=len(argv)foriinxrange(hLen):hvol=ord(argv)hhex=%02x%hvolresult+=hhex+printhexShow:,resultt=serial.Serial(com12,9600)printt.portstrstrInput=raw_input(entersomewords:)n=t.write(strInput)printnstr=t.read(n)printstrhexShow(str)2
AttributesofSerialinstances
ReadOnly:
importserialdefhexShow(argv):result=hLen=len(argv)foriinxrange(hLen):hvol=ord(argv)hhex=%02x%hvolresult+=hhex+printhexShow:,resultt=serial.Serial(com12,9600)printt.portstrstrInput=raw_input(entersomewords:)n=t.write(strInput)printnstr=t.read(n)printstrhexShow(str)3Newvaluescanbeassignedtothefollowingattributes,theportwillbereconfigured,evenifitsopenedatthattime:
importserialdefhexShow(argv):result=hLen=len(argv)foriinxrange(hLen):hvol=ord(argv)hhex=%02x%hvolresult+=hhex+printhexShow:,resultt=serial.Serial(com12,9600)printt.portstrstrInput=raw_input(entersomewords:)n=t.write(strInput)printnstr=t.read(n)printstrhexShow(str)4
Exceptions
importserialdefhexShow(argv):result=hLen=len(argv)foriinxrange(hLen):hvol=ord(argv)hhex=%02x%hvolresult+=hhex+printhexShow:,resultt=serial.Serial(com12,9600)printt.portstrstrInput=raw_input(entersomewords:)n=t.write(strInput)printnstr=t.read(n)printstrhexShow(str)5
Constants
parity:
importserialdefhexShow(argv):result=hLen=len(argv)foriinxrange(hLen):hvol=ord(argv)hhex=%02x%hvolresult+=hhex+printhexShow:,resultt=serial.Serial(com12,9600)printt.portstrstrInput=raw_input(entersomewords:)n=t.write(strInput)printnstr=t.read(n)printstrhexShow(str)6stopbits:
importserialdefhexShow(argv):result=hLen=len(argv)foriinxrange(hLen):hvol=ord(argv)hhex=%02x%hvolresult+=hhex+printhexShow:,resultt=serial.Serial(com12,9600)printt.portstrstrInput=raw_input(entersomewords:)n=t.write(strInput)printnstr=t.read(n)printstrhexShow(str)7bytesize:
importserialdefhexShow(argv):result=hLen=len(argv)foriinxrange(hLen):hvol=ord(argv)hhex=%02x%hvolresult+=hhex+printhexShow:,resultt=serial.Serial(com12,9600)printt.portstrstrInput=raw_input(entersomewords:)n=t.write(strInput)printnstr=t.read(n)printstrhexShow(str)8
如果您觉得本篇CentOSLinux教程讲得好,请记得点击右边漂浮的分享程序,把好文章分享给你的小伙伴们!
给大家带来python经由过程pyserial读写串口
尽量不要提问纯属是扯蛋.学习Linux特别是自己一个人初学入手的时候没人教很困难.当然如果可以的话平时多去买些Linux书...对学习Linux很有帮助. 永中office 2004增强版安装只需要默认安装即可使用并操作大多与win系统雷同,打印机的配置和管理,记录光盘等。 Linux高手更具有鼓励新手的文化精神。如何在Linux社区获得帮助,需要说明的是你要有周全的思考,准备好你的问题,不要草率的发问。 熟悉操作是日常学习Linux中的三大法宝。以下是作者学习Linux的一些个人经验,供参考: 未来的学习之路将是以指数增加的方式增长的。从网管员来说,命令行实际上就是规则,它总是有效的,同时也是灵活的。 掌握在Linux系统中安装软件,在安装Linux工具盘后大致日常所需的软件都会有,一般网络提供下载的软件都会有安装说明。 如果你有庞大而复杂的测试条件,尽量把它剪裁得越小越好。可能你会遇到这种情况,对于一个问题会出现不同内容回答,这时你需要通过实践来验证。 Linux高手更具有鼓励新手的文化精神。如何在Linux社区获得帮助,需要说明的是你要有周全的思考,准备好你的问题,不要草率的发问。
页:
[1]