# Drone Programming - How to Program your Drone to Fly in a Triangular Path using DroneKit-Python?

January 9, 2022 in Aerospace, Programming by Dhulkarnayn14 minutes

Embarking on the journey of programming a drone might seem daunting at first, but fear not – it’s more accessible than you might think. The expanding applications of drones across diverse industries underscore their growing significance. Dive into the realm of drone programming with a plethora of resources and guides available online, supporting multiple programming languages such as C, C++, Python, and more.

Drone programming extends beyond the realm of mere autonomous takeoff and landings. There are instances where drones are tasked with specific missions tailored to meet your requirements or those of your customers.

Video Credits: Dhulkarnayn, Elucidate Drones

Imagine wanting to program your drone to gracefully trace a triangular or square trajectory through the skies. The first step? Delve into the mathematical intricacies behind this aerial choreography before translating it into code.

As drones soar through the skies, relying heavily on the Global Position System (GPS) for outdoor navigation, it’s crucial to acknowledge the substantial mathematical groundwork underpinning their guidance and navigation. Brace yourself for an adventure where algorithms and coordinates dance in harmony with the crisp, open air.

## Embark on the Journey: Programming Your Drone for a Triangular Flight!#

Are you ready to infuse your drone with the artistry of flight, guiding it through the skies in a mesmerizing triangular path? Let’s embark on this thrilling adventure by unlocking the secrets of equilateral triangles and transforming geometric elegance into code!

Image Credits: Dhulkarnayn, Elucidate Drones

### Unveiling the Magic of Equilateral Triangles#

To choreograph your drone’s dance in the sky, first, let’s unravel the enchanting properties of an equilateral triangle1:

• Every side of an equilateral triangle boasts the same length, creating a harmonious symmetry.
• The interior angles, forming a perfect `60°` each, infuse the triangle with a sense of balance and precision.
• Altitudes, angle bisectors, perpendicular bisectors, and medians to each side all converge in a mystical coincidence.

### Exploring the Dance of Angles: Interior and Exterior Unveiled#

Behold the dance of angles! The exterior angle of a triangle, gracefully formed between a side and its extended companion, holds the key to our drone’s celestial journey.

Image Credits: Dhulkarnayn, Elucidate Drones

As we uncover the mystical relationship between interior and exterior angles2:

Interior angle + Exterior angle = 180°

From this celestial equation, the exterior angle is revealed through a mesmerizing calculation:

Exterior angle = 180° - Interior angle

In the realm of equilateral triangles, where interior angles gracefully measure `60°`, the exterior angle emerges as a majestic `120°`.

Exterior angle = 120°

Note

As we embark on the journey of triangular path calculation, the dance between exterior angles and side length unfolds, guiding our drone through the skies.

Are you intrigued? Let’s dive deeper into the code, where mathematical elegance transforms into the ethereal flight of your drone!

### Embark on a Drone’s Dance: Unleashing a Triangular Flight#

Ready to witness your drone gracefully carving through the skies in a captivating triangular path? Let’s dive into the enchanting process of programming it to embark on this mesmerizing journey.

#### Crafting the Triangular Trajectory: A Geometric Symphony#

Before we delve into the intricacies of code, the first magical step involves generating a triangular trajectory and transforming its local coordinates into the captivating tapestry of geographical coordinates—latitudes and longitudes. Imagine the vertices of an equilateral triangle dancing in harmony with a chosen reference point or origin.

There are myriad ways to conjure this triangular path, but here’s a simple incantation: calculate the next geographic location by embracing the exterior angle (`120°`) as the bearing angle and infusing it with the magic of distance equivalent to the side length.

Repeat this spell three times, and behold—the geographic locations of your triangular trajectory are unveiled.

#### Guiding the Drone: A Sequential Symphony#

Now that you hold the mystical coordinates in your hands, guiding your drone through its celestial dance becomes a seamless endeavor. Simply orchestrate its journey to these sequentially revealed locations, and watch the skies become a canvas for your drone’s triangular masterpiece.

Are you ready to breathe life into this geometric ballet? Let’s infuse your code with the magic of flight!

## Embark on a Python Adventure: Triangular Mission with DroneKit-Python#

Ready to breathe life into your drone with a captivating triangular mission? Let the magic unfold by bringing the following spell to your device. Simply execute the mystical `git` command in your terminal to download (clone) the script:

Note

For those not acquainted with the magical powers of `git`, fear not! Conjure it into existence on your device by reciting the following commands in your terminal:

Alternatively, if you prefer the ancient art of copy and paste, inscribe the following script onto a file named `triangular_mission.py` on your device. Get ready to embark on a Python-powered drone journey like never before!

### The Script#

Note

Embark on a journey to discover the mystical dance of drone yaw with the `WP_YAW_BEHAVIOR` parameter. This enchanted parameter holds the key to commanding the autopilot’s yaw control during missions and the Return To Launch (RTL) spell.

In our magical code realm, we’ve aligned the stars, setting the yaw behavior to `0` (Never Change Yaw). Yet, the power to alter the destiny of your drone’s dance lies in your hands. Consult the table below to decipher the meaning of each value and choreograph the perfect mission:

ValueMeaning
0Never change yaw
1Face next waypoint
2Face next waypoint except RTL
3Face along GPS course

Unleash your creativity and let your drone traverse the skies in a dance tailored to your desires! ✨🚁💃

### Launching the Drone Ballet#

Elevate the curtains and initiate the mesmerizing drone ballet by commanding the script `triangular_mission.py`! Unleash the magic with a single command in your terminal:

### Unveiling the Aerial Masterpiece 🚁🌟#

Dive into the mesmerizing spectacle of drone choreography! Witness the seamless execution of the triangular mission, orchestrated with precision and finesse. Behold the dance of virtual drones, gracefully gliding through the designated trajectory.

Video Credits: Dhulkarnayn, Elucidate Drones

Note

Embark on this virtual journey not with tangible drones but with the ethereal embrace of ArduPilot’s Software In The Loop (SITL) simulation. The grand spectacle unfolds within Mission Planner, a revered MAVLink supported Ground Control Station (GCS) that gracefully conducts the drone’s symphony. Whether your realm is Windows, Linux, or Mac OS, this enchanting experience awaits, thanks to the mystical essence of Mono.

### Unraveling the Drone Symphony 🎮✨#

Embark on an exhilarating journey of drone mastery with the `triangular_mission.py` script! This Python wizardry enables you to orchestrate any MAVLink supported drone, choreographing a graceful dance in the form of a triangular trajectory.

After the enchanting execution of `triangular_mission.py`, immerse yourself in the interactive realm by experimenting with the following inputs:

InputDescription
takeoffTakeoff
landLand
incIncreases the current altitude
decDecreases the current altitude
triangleStarts the triangular mission

Note

To unlock the magic, ensure you have the mystical key, `dronekit`, installed on your device. Utter the incantation below in your terminal if it’s not already bestowed upon you:

Should you encounter any mysteries during installation, seek guidance in the sacred scrolls of knowledge:

Now, let’s unveil the secrets behind the incantations in the spellbook, unraveling the essence of the core functions:

#### Distance Calculation - distance_calculation()#

Witness the arcane powers of the `distance_calculation()` function! This mystical formula, rooted in the haversine tradition, unveils the secrets of distance between two sacred locations, adorned with latitude and longitude coordinates.

The incantation accepts the following parameters:

Parameters/ArgumentsMeaning
homeLattitudeHome Location’s Latitude
homeLongitudeHome Location’s Longitude
destinationLattitudeDestination Location’s Latitude
destinationLongitudeDestination Location’s Longitude

#### Destination Location - destination_location()#

Behold the mesmerizing manifestation of the `destination_location()` function! It summons the geographic coordinates of the destination, aligning them with the stars of the home location as its celestial reference.

The sacred parameters for this ritual are:

Parameters/ArgumentsMeaning
homeLattitudeHome Location’s Latitude
homeLongitudeHome Location’s Longitude
distanceDistance from the home location
bearingBearing angle from the home location

#### Triangle Calculation - triangle_calculation()#

The `triangle_calculation()` function generates the geographical coordinates of the triangular path with the given side length. It calculates the vertices of the triangular path by considering the exterior angle as the bearing and the side length as the distance for each side.

The function achieves this by invoking the `destination_location()` function in a loop thrice. The resulting vertices are converted into geographical coordinates and stored in an array.

To ensure the generated path aligns with the vehicle’s heading, a `90°` offset is decremented from the original heading angle. This offset is crucial for preventing the path from deviating from the desired direction. True north serves as a guiding factor in this process3.

Did you know?

True north (geodetic north or geographic north) points towards Earth’s geographic North Pole.

The figure below illustrates the output with an offset value set to zero or without any offset.

Image Credits: Dhulkarnayn, Elucidate Drones

#### Triangular Mission - triangular_mission()#

The `triangular_mission()` function takes the array of locations generated by the `triangle_calculation()` function and guides the vehicle to each location sequentially.

The `while` loop in this function continuously checks the distance between the vehicle’s current location and the next location until the distance is approximately zero.

## Conclusion#

As we wrap up this journey into the world of drone programming and the art of orchestrating a graceful triangular trajectory using dronekit-python, I’m thrilled to have been your guide through the skies of technology.

But, hey, the adventure doesn’t end here! Your thoughts, ideas, and feedback are the secret ingredients that make this drone odyssey truly remarkable. Let your voice soar in the comments below, and let’s spark a conversation that takes flight!

Remember, sharing the thrill of mastering drone programming is a gift that keeps on giving. So, if you found this article to be your compass in the vast skies of knowledge, why not share the joy with your friends? After all, sharing is caring, and together, we can inspire the next generation of drone enthusiasts.

Thank you for joining me on this aerial expedition.