一.serial串口通信

  1. 串口工具设置(a.端口、波特率、数据位;b.下面编辑栏输入串口协议组成的指令)
  2. python 调用serial模块实现串口通信(确保已安装serial模块:pip install pyserial)
#!/usr/bin/python
import serial

ser = serial.Serial('COM5', 115200)#串口通信链接:端口号、波特率、时间
''' 端口通信格式:
ser = serial.Serial('port', baudrate)
ser.write("指令协议")'''

class   Can_Off:
    def __init__(self):
        self.TYPE_ID = [0xA0]
        self.NODE_IDA = [0x0J]#电机版1
        self.NODE_IDB = [0x0K]#电机版2
        self.LENGTH = [0x05, 0x00]
        
        self.data1 = [0x0a, 0x0f, 0x0f, 0x0f]
        
    def co_action(self, arg=1):
        # arg:0-路径1,1路径2
        try:
            ser.write(cal.PacketData(self.TYPE_ID, self.NODE_IDA, self.LENGTH, self.data1, arg))
            ser.write(cal.PacketData(self.TYPE_ID, self.NODE_IDB, self.LENGTH, self.data1, arg))
        except Exception as ex:
            print(ex)
  if __name__ == "__main__":
	Can_off.co_action()
  1. Python调用 socket模块实现网口通信
#!/usr/bin/python
import socket

class Aut:
    def __init__(self,addr):
        self.addr = RemoteAddr#测试机“IP+端口号”
        self.ab =  b'\x01'

	    def au_one(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.sendto(self.ab, self.addr)
        except Exception as ex:
            print(ex)
            
RemoteAddr=(“*.*.*.*”,*)
au=Aut(RemoteAddr)
 if __name__ == "__main__":
 	au.au_one()