1. 程式人生 > 其它 >Pixhawk無人機擴充套件教程(8)---使用鍵盤控制無人機飛行

Pixhawk無人機擴充套件教程(8)---使用鍵盤控制無人機飛行

技術標籤:dronekit無人機-蒼穹四軸

摘自:https://mp.weixin.qq.com/s?__biz=Mzg2NDI0MzU5NA==&mid=2247484515&idx=2&sn=7cd2a23c6661d985c0198fb48bc9317f&chksm=ce6d1e86f91a979021d078d45513f7b6af112b1cd685f92fdeaec94d7a2ac33be34529c36ccb&scene=21#wechat_redirect

Pixhawk無人機擴充套件教程(8)---使用鍵盤控制無人機飛行

原創 CJKK 蒼穹四軸DIY

2020-05-20

在前面的教程中,我們通過Dronekit程式設計實現了對無人機的位置控制和速度控制。在給點GPS座標點和明確飛行路徑的情況下,使用這兩種方式非常方便的。但是如果在GPS座標點不明確,或則飛行線路也沒有確定的情況下,如何通過Dronekit程式設計實現自由控制無人機飛行方向呢?

下面給大家介紹一種方法:

先看一下執行視訊:

以上視訊我們可以看到,通過python程式我們可以使用鍵盤方向按鍵實現對無人機的控制。具體方法如下:

一、安裝python-tk

sudo apt-get install python-tk

二、控制程式如下:

"""Simple script for take off and control with arrow keys
""" importtimefrom 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] #定義起飛函式defarm_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速度命令的功能defset_velocity_body(vehicle,vx,vy,vz):"""Remember:vzispositivedownward!!! Bitmask to indicate which dimensions should be ignored by the vehicle (a value of 0b0000000000000000 or 0b0000001000000000 indicates that none of the setpoint dimensions should be ignored). Mapping: bit 1: x, bit 2: y, bit 3: z, bit 4: vx, bit 5: vy, bit 6: vz, bit7:ax,bit8:ay,bit9: """ 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() #按鍵事件功能defkey(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()

如果提示格式錯誤,請刪除問程式碼中中文註釋!