|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
在前面的教程中,我们通过Dronekit编程实现了对无人机的位置控制和速度控制。在给点GPS坐标点和明确飞行路径的情况下,使用这两种方式非常方便的。但是如果在GPS坐标点不明确,或则飞行线路也没有确定的情况下,如何通过Dronekit编程实现自由控制无人机飞行方向呢?下面给大家介绍一种方法:先看一下运行视频:
以上视频我们可以看到,通过python程序我们可以使用键盘方向按键实现对无人机的控制。具体方法如下:
一、安装python-tk
sudo apt-get install python-tk二、控制程序如下:"""Simple script for take off and control with arrow keys"""
import timefrom dronekit import connect, VehicleMode, LocationGlobalRelative, Command, LocationGlobalfrom pymavlink import mavutilimport Tkinter as tk
#通过SITL仿真运行print('Connecting...')vehicle = connect('udp:127.0.0.1:14551')
#设置飞行速度5m/sgnd_speed = 5 # [m/s]
#定义起飞函数def arm_and_takeoff(altitude):
while not vehicle.is_armable: print("waiting to be armable") time.sleep(1)
print("Arming motors") vehicle.mode = VehicleMode("GUIDED") vehicle.armed = True
while not vehicle.armed: time.sleep(1)
print("Taking Off") vehicle.simple_takeoff(altitude)
while True: v_alt = vehicle.location.global_relative_frame.alt print(">> Altitude = %.1f m"%v_alt) if v_alt >= altitude * 0.95: print("Target altitude reached") break time.sleep(1)
#定义发送mavlink速度命令的功能def set_velocity_body(vehicle, vx, vy, vz): """ Remember: vz is positive downward!!! Bitmask to indicate which dimensions should be ignored by the vehicle (a valueof0b0000000000000000 or0b0000001000000000 indicates that noneof the setpoint dimensions should be ignored). Mapping: bit1: x, bit2: y, bit3: z, bit4: vx, bit5: vy, bit6: vz, bit 7: ax, bit 8: ay, bit 9: """ msg = vehicle.message_factory.set_position_target_local_ned_encode( 0, 0, 0, mavutil.mavlink.MAV_FRAME_BODY_NED, 0b0000111111000111, #-- BITMASK -> Consider only the velocities 0, 0, 0, #-- POSITION vx, vy, vz, #-- VELOCITY 0, 0, 0, #-- ACCELERATIONS 0, 0) vehicle.send_mavlink(msg) vehicle.flush()
#按键事件功能def key(event): if event.char == event.keysym: #-- standard keys if event.keysym == 'r': print("r pressed >> Set the vehicle to RTL") vehicle.mode = VehicleMode("RTL") elif event.keysym == 'l': print("l pressed >> Set the vehicle to LAND") vehicle.mode = VehicleMode("LAND")
else: #-- non standard keys if event.keysym == 'Up': set_velocity_body(vehicle, gnd_speed, 0, 0) elif event.keysym == 'Down': set_velocity_body(vehicle,-gnd_speed, 0, 0) elif event.keysym == 'Left': set_velocity_body(vehicle, 0, -gnd_speed, 0) elif event.keysym == 'Right': set_velocity_body(vehicle, 0, gnd_speed, 0)
#主程序#起飞,目标高度10米arm_and_takeoff(10)
#等待键盘输入root = tk.Tk()print(">> Control the drone with the arrow keys. Press r for RTL mode")print(">> Control the drone with the arrow keys. Press l for LAND mode")root.bind_all('<Key>', key)root.mainloop()如果提示格式错误,请删除问代码中中文注释!
|
| |