python(50)-Serial-串口类-读写

基本函数:

 #  串口操作:设置、打开、读取、写入、关闭
    com= serial.Serial('com1', 9600, timeout=0.5)  
    com.open()           # 端口:打开
    com.isOpen()         # 状态:是否已被打开
    com.read_all()       # 操作:读
    com.write(cmd)       # 操作:写
    com.close()          # 端口: 关闭

注意点:写完读取时需要增加延时,当为‘b`’表示没读到。
 

import binascii

from serial import Serial

if __name__ == "__main__":
   com = Serial(port='COM2', baudrate=9600,bytesize=8, parity='N',stopbits=1,  #1.实例化串口及各项参数
                dsrdtr=False, rtscts=False, xonxoff=False, timeout=2)

   if (com.isOpen() == False):                                                #2.查看串口状态 如果串口没打开打开它
      com.open()
   if (com.isOpen() == True):                                                 #3. 如果串口已打开 关了重开
       com.close()
       com.open()
       hexCmd="01 03 06 00 00 10 44 8E"
       hexCmd = hexCmd.replace(' ', '')  # 去除空格
       cmd = binascii.a2b_hex(hexCmd)  # 转换为16进制串

       write_len = com.write(cmd)                                            #4. Hex发送
       print("write:")
       print(cmd)
       rels = com.read_all()                                                 #5.读取
       print(rels)                             #
       while True:
           rels = com.read_all()
           if rels:  # 返回不为空 跳出死循环
               break
       if rels:
           print("read:")
           print(rels)


 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值