码迷,mamicode.com
首页 > 编程语言 > 详细

Python 串口通信操作

时间:2017-12-09 16:57:25      阅读:356      评论:0      收藏:0      [点我收藏+]

标签:测试   pytho   dal   vol   timeout   for   通信   bytearray   packages   

下载  pyserial包 https://pypi.python.org/packages/source/p/pyserial/pyserial-2.7.tar.gz#md5=794506184df83ef2290de0d18803dd11

然后解压,例如解压到D:/pyserial.打开cmd,cd 指令切换到D:\pyserial下。执行安装指令 python setup.py install

编写测试代码。

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‘] = ‘打开成功!‘
        except Exception as ex:
            self.lblInfo[‘text‘] = ‘打开失败!‘

#使用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 串口通信操作

标签:测试   pytho   dal   vol   timeout   for   通信   bytearray   packages   

原文地址:http://www.cnblogs.com/huangziqing/p/8011756.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!