python 实现云台的基本控制
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
例如:Python 的设计具有很强的可读性,相比其他语言经常使用英文关键字,其他语言的一些标点符号,它具有比其他语言更有特色语法结构。易于学习、易于阅读、易于维护、具有可移植、可扩展等特性。
示例:云台用于相机的稳定器,起到平衡与稳定作用。云台的应用范围很广,各种特殊行业也对云台产品有一定的需求。
代码如下(示例):
class Mywindow(QtWidgets.QWidget, Ui_MainWindow):
# QtCore.QMetaObject.connectSlotsByName(Ui_MainWindow)
def init(self,):
super(Mywindow, self).init()
self.setupUi(self)
self.init()
self.setWindowTitle(“云台控制器”)
self.ser = serial.Serial()
self.port_check()
self.level_angel = 0
self.vertical_angle = 0
self.speed_data()
self.horizontalSlider.valueChanged.connect(self.valuechange)
self.horizontalSlider_2.valueChanged.connect(self.valuechange)
self.horizontalSlider.valueChanged.connect(self.va1)
self.horizontalSlider_2.valueChanged.connect(self.va2)
def init(self):
# self.status = self.statusbar
# self.status.showMessage('时间:', 1000)
# 串口检测
self.detected__button_1.clicked.connect(self.port_check)
# 串口显示
self.s1__box_8.currentTextChanged.connect(self.port_imf)
# 打开串口
self.open_button.clicked.connect(self.port_open)
# 关闭串口
self.close_button.clicked.connect(self.port_close)
# 定时器接收数据
self.timer = QTimer(self)
# self.timer.timeout.connect(self.data_receive)
# 按键控制动作
self.a_button.clicked.connect(self.data_send_a)
self.w_button.clicked.connect(self.data_send_w)
self.s_button.clicked.connect(self.data_send_s)
self.d_button.clicked.connect(self.data_send_d)
self.x_button.clicked.connect(self.data_send_x)
self.q_button.clicked.connect(self.data_send_q)
self.e_button.clicked.connect(self.data_send_e)
self.z_button.clicked.connect(self.data_send_z)
self.c_button.clicked.connect(self.data_send_c)
# 云台信息返回
self.inquire1_button.clicked.connect(self.send_level_angel)
self.inquire2_button.clicked.connect(self.send_vertical_angle)
# 角度控制
self.level_button.clicked.connect(self.send_leve)
self.vertical_button.clicked.connect(self.send_vertical)
self.pushButton.clicked.connect(self.exit)
# 速度控制
# self.setText(self.speed_data)
# 定义界面的操作
# 方向键控制
def port_check(self):
# 检测所有存在的串口,将信息存储在字典中
self.Com_Dict = {}
port_list = list(serial.tools.list_ports.comports())
self.s1__box_8.clear()
for port in port_list:
self.Com_Dict["%s" % port[0]] = "%s" % port[1]
self.s1__box_8.addItem(port[0])
if len(self.Com_Dict) == 0:
self.state_label.setText("无串口")
def port_imf(self):
# 显示选定的串口的详细信息
imf_s = self.s1__box_8.currentText()
if imf_s != "":
self.state_label.setText(self.Com_Dict[self.s1__box_8.currentText()])
# 打开串口
def port_open(self):
self.ser.port = self.s1__box_8.currentText()
self.ser.baudrate = int(self.s1__box_10.currentText())
self.ser.bytesize = int(self.s1__box_7.currentText())
self.ser.stopbits = int(self.s1__box_6.currentText())
self.ser.parity = self.s1__box_9.currentText()
try:
self.ser.open()
except:
QMessageBox.critical(self, "Port Error", "此串口不能被打开!")
return None
# 打开串口接收定时器,周期为2ms
self.timer.start(2)
if self.ser.isOpen():
self.open_button.setEnabled(False)
self.close_button.setEnabled(True)
self.groupBox_6.setTitle("串口状态(已开启)")
def port_close(self):
self.timer.stop()
# self.timer_send.stop()
try:
self.ser.close()
except:
pass
self.open_button.setEnabled(True)
self.close_button.setEnabled(False)
# self.lineEdit_3.setEnabled(True)
# 接收数据和发送数据数目置零
# self.data_num_received = 0
# self.lineEdit_3.setText(str(self.data_num_received))
# self.data_num_sended = 0
# self.lineEdit_4.setText(str(self.data_num_sended))
self.groupBox_6.setTitle("串口状态(已关闭)")
def data_send_a(self): # 控制向左方向
if self.ser.isOpen():
a = 'FF 01 00 04 00 00 08'
# a = a.strip()
# send_list = []
# input_s = a[2:].strip()
# while (a) != '':
# try:
# num = int(a[0:2], 16)
# except ValueError:
# QMessageBox.critical(self, 'wrong data', '请检查命令是否对应正确')
# # print("Data-send-a Error")
# a = a[2:].strip()
# send_list.append(num)
# # print(data)
# input_s = bytes(send_list)
# # print(input_s)
# self.ser.write(input_s)
"""方法2"""
f_list = a.split(" ")
d1 = self.va1()
d1 = str(d1)
data1 = hex(int(d1))[2:]
if len(data1) != 2:
data1 = data1.rjust(2, '0')
f_list[4] = data1
checksum = hex(sum([int(i, 16) for i in f_list[1:6]]))[2:]
if len(checksum) != 2:
checksum = checksum.rjust(2, '0')
f_list[6] = checksum
data_str = ''.join(f_list)
input_s = bytes.fromhex(data_str)
self.ser.write(input_s)
f_list = ' '.join(f_list)
self.lineEdit_3.setText(str(f_list))
else:
QMessageBox.critical(self, 'open-port-error', "Check whether the serial port is enabled")
# print("Check whether the serial port is enabled")
def data_send_w(self): # 控制向前方向
if self.ser.isOpen():
w = 'FF 01 00 08 00 00 09'
"""方法2"""
f_list = w.split(" ")
# d1 = self.va1()
# d1 = str(d1)
# data1 = hex(int(d1))[2:]
# f_list[4] = data1
d2 = self.va2()
d2 = str(d2)
data2 = hex(int(d2))[2:]
if len(data2) != 2:
data2 = data2.rjust(2, '0')
f_list[5] = data2
checksum = hex(sum([int(i, 16) for i in f_list[1:6]]))[2:]
if len(checksum) != 2:
checksum = checksum.rjust(2, '0')
f_list[6] = checksum
# print(f_list)
data_str = ''.join(f_list)
input_s = bytes.fromhex(data_str)
self.ser.write(input_s)
f_list = ' '.join(f_list)
self.lineEdit_3.setText(str(f_list))
else:
QMessageBox.critical(self, 'open-port-error', "Check whether the serial port is enabled")
# print("Check whether the serial port is enabled")
def data_send_s(self): # stop命令
if self.ser.isOpen():
s = 'FF 01 00 00 00 00 01'
s = s.strip()
send_list = []
input_s = s[2:].strip()
while (s) != '':
try:
num = int(s[0:2], 16)
except ValueError:
QMessageBox.critical(self, 'send-error', "请检查命令是否对应正确")
# print("Data-send-s Error")
s = s[2:].strip()
send_list.append(num)
input_s = bytes(send_list)
self.ser.write(input_s)
f_list = ['FF', '01', '00', '00', '00', '00', '01']
f_list = ' '.join(f_list)
self.lineEdit_3.setText(str(f_list))
else:
QMessageBox.critical(self, 'open-port-error', "Check whether the serial port is enabled")
# print("Check whether the serial port is enabled")
def data_send_d(self): # 控制向右方向
if self.ser.isOpen():
d = 'FF 01 00 02 03 00 06'
"""方法2"""
f_list = d.split(" ")
d1 = self.va1()
d1 = str(d1)
data1 = hex(int(d1))[2:]
if len(data1) != 2:
data1 = data1.rjust(2, '0')
f_list[4] = data1
checksum = hex(sum([int(i, 16) for i in f_list[1:6]]))[2:]
if len(checksum) != 2:
checksum = checksum.rjust(2, '0')
f_list[6] = checksum
# d2 = self.va2()
# d2 = str(d2)
# data2 = hex(int(d2))[2:]
# f_list[5] = data2
f_list[6] = checksum
data_str = ''.join(f_list)
input_s = bytes.fromhex(data_str)
self.ser.write(input_s)
f_list = ' '.join(f_list)
self.lineEdit_3.setText(str(f_list))
else:
QMessageBox.critical(self, 'open-port-error', "Check whether the serial port is enabled")
# print("Check whether the serial port is enabled")
def data_send_x(self): # 控制向后方向
if self.ser.isOpen():
x = 'FF 01 00 10 00 00 11'
"""方法2"""
f_list = x.split(" ")
# d1 = self.va1()
# d1 = str(d1)
# data1 = hex(int(d1))[2:]
# f_list[4] = data1
d2 = self.va2()
d2 = str(d2)
data2 = hex(int(d2))[2:]
if len(data2) != 2:
data2 = data2.rjust(2, '0')
f_list[5] = data2
checksum = hex(sum([int(i, 16) for i in f_list[1:6]]))[2:]
if len(checksum) != 2:
checksum = checksum.rjust(2, '0')
f_list[6] = checksum
# print(f_list)
data_str = ''.join(f_list)
input_s = bytes.fromhex(data_str)
self.ser.write(input_s)
f_list = ' '.join(f_list)
self.lineEdit_3.setText(str(f_list))
else:
QMessageBox.critical(self, 'open-port-error', "Check whether the serial port is enabled")
# print("Check whether the serial port is enabled")
def data_send_q(self): # 控制向前左方向
if self.ser.isOpen():
q = 'FF 01 00 0C 03 00 10'
"""方法2"""
f_list = q.split(" ")
d1 = self.va1()
d1 = str(d1)
data1 = hex(int(d1))[2:]
if len(data1) != 2:
data1 = data1.rjust(2, '0')
f_list[4] = data1
d2 = self.va2()
d2 = str(d2)
data2 = hex(int(d2))[2:]
if len(data2) != 2:
data2 = data2.rjust(2, '0')
f_list[5] = data2
checksum = hex(sum([int(i, 16) for i in f_list[1:6]]))[2:]
if len(checksum) != 2:
checksum = checksum.rjust(2, '0')
f_list[6] = checksum
data_str = ''.join(f_list)
input_s = bytes.fromhex(data_str)
self.ser.write(input_s)
f_list = ' '.join(f_list)
self.lineEdit_3.setText(str(f_list))
else:
QMessageBox.critical(self, 'open-port-error', "Check whether the serial port is enabled")
# print("Check whether the serial port is enabled")
def data_send_e(self): # 控制向前右方向
if self.ser.isOpen():
e = 'FF 01 00 0A 03 00 0E'
"""方法2"""
f_list = e.split(" ")
d1 = self.va1()
d1 = str(d1)
data1 = hex(int(d1))[2:]
if len(data1) != 2:
data1 = data1.rjust(2, '0')
f_list[4] = data1
d2 = self.va2()
d2 = str(d2)
data2 = hex(int(d2))[2:]
if len(data2) != 2:
data2 = data2.rjust(2, '0')
f_list[5] = data2
checksum = hex(sum([int(i, 16) for i in f_list[1:6]]))[2:]
if len(checksum) != 2:
checksum = checksum.rjust(2, '0')
f_list[6] = checksum
# print(f_list[6])
# print(f_list)
data_str = ''.join(f_list)
input_s = bytes.fromhex(data_str)
self.ser.write(input_s)
f_list = ' '.join(f_list)
self.lineEdit_3.setText(str(f_list))
else:
QMessageBox.critical(self, 'open-port-error', "Check whether the serial port is enabled")
# print("Check whether the serial port is enabled")
def data_send_z(self): # 控制向后左方向
if self.ser.isOpen():
z = 'FF 01 00 14 03 00 18'
"""方法2"""
f_list = z.split(" ")
d1 = self.va1()
d1 = str(d1)
data1 = hex(int(d1))[2:]
if len(data1) != 2:
data1 = data1.rjust(2, '0')
f_list[4] = data1
d2 = self.va2()
d2 = str(d2)
data2 = hex(int(d2))[2:]
if len(data2) != 2:
data2 = data2.rjust(2, '0')
f_list[5] = data2
checksum = hex(sum([int(i, 16) for i in f_list[1:6]]))[2:]
if len(checksum) != 2:
checksum = checksum.rjust(2, '0')
f_list[6] = checksum
# print(f_list[6])
data_str = ''.join(f_list)
input_s = bytes.fromhex(data_str)
self.ser.write(input_s)
f_list = ' '.join(f_list)
self.lineEdit_3.setText(str(f_list))
else:
QMessageBox.critical(self, 'open-port-error', "Check whether the serial port is enabled")
# print("Check whether the serial port is enabled")
def data_send_c(self): # 控制向后右方向
# checksum = 0
if self.ser.isOpen():
c = 'FF 01 00 12 03 00 16'
"""简化后的一种方式"""
f_list = c.split(" ")
# print(f_list)
d1 = self.va1()
d1 = str(d1)
data1 = hex(int(d1))[2:]
if len(data1) != 2:
data1 = data1.rjust(2, '0')
f_list[4] = data1
d2 = self.va2()
d2 = str(d2)
data2 = hex(int(d2))[2:]
if len(data2) != 2:
data2 = data2.rjust(2, '0')
f_list[5] = data2
checksum = hex(sum([int(i, 16) for i in f_list[1:6]]))[2:]
if len(checksum) != 2:
checksum = checksum.rjust(2, '0')
f_list[6] = checksum
# print(f_list[6])
# print(f_list)
data_str = ''.join(f_list)
# print(f_list[5])
# print(data_str)
input_s = bytes.fromhex(data_str)
# print(input_s)
self.ser.write(input_s)
f_list = ' '.join(f_list)
self.lineEdit_3.setText(str(f_list))
else:
QMessageBox.critical(self, 'open-port-error', "Check whether the serial port is enabled")
# print("Check whether the serial port is enabled")
def send_level_angel(self): # 水平角度查询
y_list = []
x_list = []
if self.ser.isOpen():
data = "FF 01 00 51 00 00 52"
d1 = bytes.fromhex(data)
result = self.ser.write(d1)
time.sleep(0.5)
count = self.ser.inWaiting()
if (count) > 0:
d2 = self.ser.read(count)
if d2 != b'':
d1 = str(binascii.b2a_hex(d2))[2:-1]
result_d1 = re.sub(r"(?<=\w)(?=(?:\w\w)+$)", " ", d1)
# y_list = []
# x_list = []
try:
x_list = result_d1.split(" ")
for i in x_list:
i = int("0x" + i, 16)
y_list.append(i)
except ValueError:
QMessageBox.critical(self, 'angle-error', "角度命令不正确,请查找并更改")
# print("Trans Error")
# QMessageBox.critical(self, 'send-error', "请检查命令是否对应正确")
pmsb = y_list[4]
plsb = y_list[5]
pdata = (pmsb * 256 + plsb)
pangle = (pdata / 100)
pangle = str(pangle)
# print(pangle)
self.label_3.setText(pangle)
# self.ser.close()
self.lineEdit_3.setText(data)
else:
QMessageBox.critical(self, 'Error', 'd2的类型为bytes')
else:
QMessageBox.critical(self, 'Error', '命令错误')
else:
QMessageBox.critical(self, 'open-port-error', "Check whether the serial port is enabled")
# print("Check whether the serial port is enabled")
def send_vertical_angle(self): # 垂直角度查询
if self.ser.isOpen():
data = "FF 01 00 53 00 00 54"
d1 = bytes.fromhex(data)
result = self.ser.write(d1)
time.sleep(0.5)
count = self.ser.inWaiting()
if (count) > 0:
d2 = self.ser.read(count)
if d2 != b'':
d1 = str(binascii.b2a_hex(d2))[2:-1]
result_d1 = re.sub(r"(?<=\w)(?=(?:\w\w)+$)", " ", d1)
y_list = []
x_list = []
try:
x_list = result_d1.split(" ")
for i in x_list:
i = int("0x" + i, 16)
y_list.append(i)
except:
# print("Trans Error")
QMessageBox.critical(self, 'angle-error', "角度命令不正确,请查找并更改")
tmsb = y_list[4]
tlsb = y_list[5]
Tdata = (tmsb * 256 + tlsb)
if Tdata > 18000:
Tdata = 36000-Tdata
elif Tdata <18000:
Tdata = -Tdata
else:
print("数据错误")
pangle = Tdata / 100
pangle = str(pangle)
# print(pangle)
self.label_4.setText(pangle)
self.lineEdit_3.setText(data)
else:
QMessageBox.critical(self, 'Error', 'd2的类型为bytes')
else:
QMessageBox.critical(self, 'Error', '命令错误')
else:
QMessageBox.critical(self, 'open-port-error', "Check whether the serial port is enabled")
# print("Check whether the serial port is enabled")
def send_leve(self): # 直接控制水平
if self.ser.isOpen():
le = "FF 01 00 4B 00 00 4C"
checksum = 0
x_list = []
input_data = self.lineEdit.text()
# print(input_data)
if int(input_data) == 0:
input_s = bytes.fromhex(le)
self.ser.write(input_s)
self.lineEdit_3.setText(le)
else:
da1 = int(input_data) * 100
da = hex(da1).upper()[2:]
byte_val = da.encode()
result_d1 = re.sub(r"(?<=\w)(?=(?:\w\w)+$)", ' ', da)
x_list = result_d1.split(' ')
d1 = x_list[0]
d2 = x_list[1]
if len(d1) != 2:
d1 = d1.rjust(2, '0')
fp = le.split(' ')
fp[4] = d1
fp[5] = d2
result = " ".join(fp)
checksum = hex(sum([int(i, 16) for i in fp[1:6]]))
d3 = checksum[-2:]
fp[6] = d3
data = " ".join(fp)
r1 = bytes.fromhex(data)
self.ser.write(r1)
self.lineEdit_3.setText(data)
else:
QMessageBox.critical(self, 'open-port-error', "Check whether the serial port is enabled")
# print("Check whether the serial port is enabled")
# self.lineEdit.setText(str("data"))
def send_vertical(self): # 直接控制垂直
if self.ser.isOpen():
ve = 'FF 01 00 4D 8C A0 7A'
checksum = 0
x_list = []
input_data = self.lineEdit_2.text()
# print(input_data)
if int(input_data) < 0:
da1 = -int(input_data) * 100
da = hex(da1).upper()[2:]
byte_val = da.encode()
result_d1 = re.sub(r"(?<=\w)(?=(?:\w\w)+$)", ' ', da)
x_list = result_d1.split(' ')
d1 = x_list[0]
d2 = x_list[1]
if len(d1) != 2:
d1 = d1.rjust(2, '0')
fp = ve.split(' ')
fp[4] = d1
# print(d1)
fp[5] = d2
result = " ".join(fp)
# print(fp)
checksum = hex(sum([int(i, 16) for i in fp[1:6]]))
d3 = checksum[-2:]
fp[6] = d3
data = " ".join(fp)
r1 = bytes.fromhex(data)
self.ser.write(r1)
self.lineEdit_3.setText(data)
elif int(input_data) > 0:
da1 = 36000 - int(input_data) * 100
da = hex(da1).upper()[2:]
byte_val = da.encode()
result_d1 = re.sub(r"(?<=\w)(?=(?:\w\w)+$)", ' ', da)
x_list = result_d1.split(' ')
d1 = x_list[0]
d2 = x_list[1]
if len(d1) != 2:
d1 = d1.rjust(2, '0')
fp = ve.split(' ')
fp[4] = d1
fp[5] = d2
result = " ".join(fp)
checksum = hex(sum([int(i, 16) for i in fp[1:6]]))
d3 = checksum[-2:]
fp[6] = d3
data = " ".join(fp)
r1 = bytes.fromhex(data)
self.ser.write(r1)
self.lineEdit_3.setText(data)
else:
input_s = bytes.fromhex(ve)
self.ser.write(input_s)
# print(input_s)
self.lineEdit_3.setText(ve)
else:
QMessageBox.critical(self, 'open-port-error', "Check whether the serial port is enabled")
# print("Check whether the serial port is enabled")
def speed_data(self): # 速度控制
self.horizontalSlider.setMinimum(0) ##设置最小值
self.horizontalSlider.setMaximum(63) #设置最大值dwa
self.horizontalSlider.setSingleStep(1) #步长
self.horizontalSlider.setValue(23) #设置当前值
data = self.horizontalSlider.value() #获取当前值
self.label_17.setText(str(data))
# print(data)
self.horizontalSlider_2.setMinimum(0)
self.horizontalSlider_2.setMaximum(63)
self.horizontalSlider_2.setSingleStep(1)
self.horizontalSlider_2.setValue(23)
data2 = self.horizontalSlider_2.value()
self.label_18.setText(str(data2))
def valuechange(self):
# print('current slider value=%s'%self.horizontalSlider.value())
self.label_17.setText(str(self.horizontalSlider.value()))
self.label_18.setText(str(self.horizontalSlider_2.value()))
data1 = self.horizontalSlider.value()
# print(data1)
data2 = self.horizontalSlider_2.value()
def va1(self): # 控制水平方向速度
data1 = self.horizontalSlider.value()
return data1
# print(data1)
def va2(self): # 控制垂直方向速度
data2 = self.horizontalSlider_2.value()
return data2
# print(data2)
def exit(self):
exit()
if name == ‘main’:
app = QtWidgets.QApplication(sys.argv)
win = Mywindow()
win.show()
sys.exit(app.exec_())
提示:这里对文章进行总结:
例如:以上就是初步实现云台控制的基本功能代码。