Drone Programming - How to Control Drone with Keyboard using DroneKit-Python?
December 14, 2021 in Aerospace, Programming by Dhulkarnayn—12 minutes
Ever wondered about the buzzing world of drones? As of November 2021, the skies over the United States played host to a staggering 866,076 registered drones, with a whopping 337,832 of them taking on the role of commercial flyers, all according to the watchful eye of the Federal Aviation Administration (FAA). This armada of unmanned aircraft takes to the skies, each with its own mission – a spectacle that has become increasingly common in our daily lives.
Image Credits: Pixabay
If you find yourself in possession of a DIY drone or one governed by community-supported flight controllers such as pixhawk or navio, here’s a fascinating tidbit: you have the power to take control using the marvel that is DroneKit-Python.
The DroneKit-Python stands tall as an Application Programming Interface (API), a gateway empowering developers to craft Python applications that seamlessly communicate with their airborne companions via the MAVLink protocol.1 Remarkably, this ingenious tool has been embraced by the developer community, witnessing over 463,900 downloads, a testament to its popularity according to Pepy.2 Check out its impressive download statistics with this badge:
Unleashing the Power of Keyboards: A Symphony of Keypresses in Python
Embark on an exciting journey into the realm of drone programming, where your computer’s keyboard becomes the cockpit of control. But wait, before you navigate the skies, you must master the art of detecting keypresses using Python.
Image Credits: Pixabay
Enter the stage, where various Python packages eagerly await to assist you in the grand performance of keypress detection. Meet the contenders:
In this odyssey of code, we choose sshkeyboard
. Why, you ask? Well, compared to its counterparts, pyinput
and keyboard
, sshkeyboard
boasts some remarkable advantages.3
Unwrapping the Magic: Installing sshkeyboard
The gateway to the enchanting world of keyboard-controlled drones is none other than sshkeyboard
. To open this gateway on your device, wield the pip command in your terminal like a wizard:
For those who prefer shortcuts, conjure the terminal window with the mystical key combination Ctrl + Alt + T
Embracing the Symphony: Using sshkeyboard
With sshkeyboard
now at your beck and call, you can summon its powers into your Python script with a simple incantation:
Craft a parchment of code named keypress.py
on your device, etching the script within its digital confines. Save this script, for it holds the key to a harmonious connection between your keyboard and drone.
Unleashing the Magic
To set this magical script into motion, utter the following spell in your terminal:
Witness the Spellbinding Output
Behold, the script conjures a mesmerizing display, capturing the dance of keystrokes with an ethereal visual:
Detecting Keypresses using Python
In this spellbinding script, the listen_keyboard()
function takes center stage, weaving a tapestry of logged keypresses as it runs incessantly in a separate thread. The protagonist, press(key)
, plays its role by printing the keys summoned from the depths of the keyboard.
Note
By default, the script bows gracefully to the ESC key, halting its enchanting performance upon its command.
Unleashing Keyboard Sorcery: Dance of the Drones
Having mastered the enchanting art of keypress detection in Python, let’s now embark on a thrilling quest: controlling a drone using the magical incantations of your keyboard.
Note
Before delving into this mesmerizing realm, consider perusing my previous masterpiece, How to Control a Drone Using Python?. It’s a tale crafted for beginners, a primer to the technological wonders awaiting in drone programming.
To guide your drone’s graceful dance through the skies, you’ll need the trusted companion: the dronekit-python
package. With it, the very fabric of your scripts will intertwine with the essence of flight.
For the keyboard to become your wand in this aerial ballet, you must choreograph a set of keys to execute a symphony of tasks with each press. In essence, you’re mapping the language of keypresses to the graceful movements and actions of your drone.
The Python script showcased in this tale orchestrates the following majestic maneuvers when you invoke the listed keys on your keyboard:
Keys | Description |
---|---|
t | Takeoff |
l | Changes the vehicle mode to LAND |
g | Changes the vehicle mode to GUIDED |
r | Changes the vehicle mode to RTL |
← | Vehicle to the Left |
→ | Vehicle to the Right |
↑ | Moves the Vehicle Forward |
↓ | Moves the Vehicle Backward |
Spacebar | Increases vehicle altitude by 5 meters from the current altitude |
Tab | Decreases vehicle altitude by 5 meters from the current altitude |
Picture this: a keypress, like the stroke of a conductor’s baton, commands the drone to ascend from the earthly stage to a lofty 5 meters. And just as effortlessly, another key sends it gracefully landing to the same hallowed ground.
Unleashing the Python Wizardry: Dance with the Drone
Behold, the enchanted script that transforms your keyboard into a wand, commanding a drone to dance across the skies. To wield this magical prowess, you can either summon the script to your device through the mystical git
command or perform the ancient act of copy and paste into a file named keycontrol.py
.
Alternatively, you may choose to manually transcribe the script into a parchment named keycontrol.py
on your device.
The Spell Book: keycontrol.py
Source: Link
Note
WP_YAW_BEHAVIOR
is a parameter that determines how the autopilot controls the yaw during missions and Return To Launch (RTL).
As the method used in the above code is completely based on the heading angle, the yaw behavior of the drone is set to 0
(Never Change Yaw). You can change the WP_YAW_BEHAVIOR
parameter for other missions based on your needs by referring to the following table:
Value | Meaning |
---|---|
0 | Never change yaw |
1 | Face next waypoint |
2 | Face next waypoint except RTL |
3 | Face along GPS course |
Performance on Stage
To unveil the mesmerizing performance, execute the script keycontrol.py
with this spell:
The Grand Spectacle
Video Credits: Dhulkarnayn, Elucidate Drones
Note
Instead of using an actual drone, I’ve used ArduPilot’s Software In The Loop (SITL) simulation and Mission Planner as Ground Control Station (GCS) software. Mission Planner is one of the MAVLink supported Ground Control Station (GCS) software that runs natively on the Windows operating system. Also, you can able run Mission Planner on Linux and Mac OS using Mono.
Code Mastery
As the incantations in each function of this mystical script are self-explanatory, let’s delve into some sorcery to enhance the script based on your whims:
How to Change the Take Off Altitude?
To alter the default Take-Off altitude, modify altitude = 5
to your desired height. For instance, to set the take-off altitude to 10 meters:
How to Change the Default Distance?
Likewise, to adjust the default vehicle movement distance (set at 5 meters), amend default_distance = 5
to your preferred value. For example, to change the default distance to 10 meters:
Altitude Control
When space or tab is pressed, the altitude increases or decreases by 5 meters, respectively. To modify this threshold, alter changed_altitude = [(actual_altitude + 5), (actual_altitude - 5)]
. For instance, to change the threshold to 8 meters:
Voila! Now, let your fingers conjure the magic, and behold your drone’s dance at your command!
Conclusion
In this Python-powered drone odyssey, you’ve unlocked the art of orchestrating airborne performances with your keyboard. Your code is the choreographer, guiding the drone through a symphony of maneuvers.
But, it’s not a finale; it’s an intermission. The script is your canvas—customize, tweak, and watch your drone dance to your coding tune. This is your aerial ballet, with Python as the maestro.
Ready to join the dance? Share your thoughts, questions, and drone tales in the comments below. Let the coding symphony continue! 🚁💻🌌
Official Documentation, DroneKit-Python. ↩︎
How it works, Official Documentation, sshkeyboard. ↩︎
This post is licensed under Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) by the author.
Please consider supporting this project!
If this article has been of help to you, and you feel generous at the moment, don’t hesitate to buy us a coffee. It's an easy, fun and direct way to show your support — any amount of coffee is highly appreciated.