Download Pyserial Package Https://pypi.python.org/packages/source/p/pyserial/pyserial-2.7.tar.gz#md5=794506184df83ef2290de0d18803dd11
Then unzip, for example, unzip to d:/pyserial. Open the CMD,CD command to switch to D:\pyserial. Execute installation Instructions Python setup.py install
Write the test code.
def opencom (Self,*args): #设置端口和波特率 selcomport = ' com2 ' #波特率 selbaudrate =9600 #奇偶校验 selparity = ' N ' try: if (not self.myserial): self.myserial = serial. Serial (Port=selcomport, baudrate=selbaudrate,bytesize=8,parity=selparity,stopbits=1,timeout=5) else: if (Self.mySerial.isOpen ()): self.mySerial.close () self.myserial = serial. Serial (Port=selcomport, Baudrate=selbaudrate, Bytesize=8, parity=selparity, Stopbits=1, timeout=5) self.lblinfo[' text '] = ' open successfully! ' except Exception as ex: self.lblinfo[' text '] = ' open failed! ‘
#使用com口发送modbus协议给终端设备.
def btnemid_click (self):
Barray = ByteArray ([0x05, 0x03, 0xa#, 0x54, 0x00, 0x08])
Voldemid = Self.txbOldEmId.get ()
Vnewemid = Self.txbNewEmId.get ()
BARRAY[0] = Int (voldemid)
BARRAY[5] = Int (vnewemid)
#crc校验
Strinput = Utils.crc16_append (Barray)
Print (Barray)
n = self.mySerial.write (Barray)
if (n > 0):
str = Self.mySerial.readall ()
self.lblinfo[' text '] = ' success! ‘
# for S in str:
# Print (Hex (s))
Else
self.lblinfo[' text '] = ' erroe!
Python Serial communication operation