1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| import easygui import sys import serial import time
def servoWriteCmd(id, cmd, par1 = None, par2 = None): buf = bytearray(b'\x55\x55') try: len = 3 buf1 = bytearray(b'') if par1 is not None: len += 2 par1 = 0xffff & par1 buf1.extend([(0xff & par1), (0xff & (par1 >> 8))]) if par2 is not None: len += 2 par2 = 0xffff & par2 buf1.extend([(0xff & par2), (0xff & (par2 >> 8))]) buf.extend([(0xff & id), (0xff & len), (0xff & cmd)]) buf.extend(buf1) sum = 0x00 for b in buf: sum += b sum = sum - 0x55 - 0x55 sum = ~sum buf.append(0xff & sum) serialHandle.write(buf) except Exception as e: print(e)
def readPosition(id): serialHandle.flushInput() servoWriteCmd(id, command["POS_READ"]) time.sleep(0.00034) time.sleep(0.005) count = serialHandle.inWaiting() pos = None if count != 0: recv_data = serialHandle.read(count) if count == 8: if recv_data[0] == 0x55 and recv_data[1] == 0x55 and recv_data[4] == 0x1C : pos= 0xffff & (recv_data[5] | (0xff00 & (recv_data[6] << 8))) return pos
portx = "COM5" bps = 115200
timex = None serialHandle = serial.Serial(portx, bps, timeout=timex) command = {"MOVE_WRITE": 1, "POS_READ": 28, "LOAD_UNLOAD_WRITE": 31}
pos = [] while True:
msg = "舵机状态" title = "机械臂" choice = easygui.indexbox(msg, title, choices=('读取', '移动','上电','掉电')) duoji = [2,3,4] for id in duoji: servoWriteCmd(id, command["LOAD_UNLOAD_WRITE"], 0)
if str(choice) == '0': pos = [] ''' for id in duoji: pos.append(readPosition(id)) # easygui.msgbox("舵机位置为:" + str(readPosition(id))) # readPosition(id)读取位置 servoWriteCmd(id, command["LOAD_UNLOAD_WRITE"], 0) # 命令马达掉电,使舵机可以用手扭动 ''' pos.append(readPosition(1)) pos.append(readPosition(2)) pos.append(readPosition(3)) pos.append(readPosition(4)) easygui.msgbox("舵机1状态为:"+str(readPosition(1))+"\n舵机2状态为:"+str(readPosition(2))+"\n舵机3状态为:"+str(readPosition(3))+"\n舵机4状态为:"+str(readPosition(4)),"结果") elif str(choice) == '1': for id_index in range(len(duoji)): id = duoji[id_index] servoWriteCmd(id, command["MOVE_WRITE"], pos[id_index], 200) easygui.msgbox("正在移动") elif str(choice)=='2': for id in duoji: servoWriteCmd(id, command["LOAD_UNLOAD_WRITE"], 1) elif str(choice)=='3': for id in duoji: servoWriteCmd(id, command["LOAD_UNLOAD_WRITE"], 0)
msg = "你希望重新读取状态?" title = "请选择" if easygui.ccbox(msg, title): pass else: sys.exit(0)
|