Softivation

Drone skips the first target (ArduPilot GUIDED with Python)

If your drone skips the first target and flies straight to the second point, your Python code isn't waiting for it to arrive. Copy and run code that measures arrival in ArduPilot GUIDED.

Furkan IŞIKAY 7 min read

You send two points to the drone from Python: first the corner to the north, then the target to the east. The drone takes off and, without ever reaching the first point, flies a diagonal line to the second. There's no error message in the code, and both commands appear to have gone out.

Some teams notice this and put a line between the two commands that waits for the autopilot's "arrived" message, and this time the code sits at the first point forever. Both symptoms have the same root: the code doesn't know when the drone has reached the target.

Why the drone never stops at the first point

In GUIDED mode, every position target you send overwrites the previous one. The autopilot has no target queue. When Python finishes a line and moves on to the next, the drone is still near the takeoff point, and the new target instantly erases the old one.

The diagram below shows the top-down tracks of two flights. On the red track, the two targets were sent back to back. The drone gets no closer than 27 meters to target 1 and turns straight toward target 2. On the blue track, the code waited for arrival at the first point, and the drone turned the corner before moving on to the second.

The second target erases the first: tracks of two flights

With two targets sent back to back, the drone gets no closer than 27 meters to the first target
Look at where the red track comes closest to target 1.

Imagine you write code for a payload drop task that first sends the drone over the target and then opens the servo. If you don't wait for arrival, Python moves straight on to the servo line while the drone is still on its way, and the payload drops well short of the target.

Doesn't the autopilot say it has arrived?

Not with the default settings. In ArduCopter 4.7, when the GUID_OPTIONS parameter is 0, the position target goes straight to the position controller, and no MISSION_ITEM_REACHED message is sent on arrival. That's why code waiting for this message hangs.

The distance to target shown in Mission Planner also comes from the wp_dist field of the NAV_CONTROLLER_OUTPUT message, and it's a whole number of meters. When the drone is 0.7 meters from the target, this field reads 0. You can't check a threshold under 1 meter with this number.

The most reliable approach is for the code to read the drone's position itself and calculate the distance to the target. The position already arrives several times per second in GLOBAL_POSITION_INT. The only thing missing is a loop that compares this number against a threshold.

The most common mistake: writing target commands one after another and assuming the drone will visit them in order. DroneKit's simple_goto also returns immediately, and every command after it cancels the previous target.

Let the code measure arrival itself

The program below takes off and sends the drone 40 meters north, then 40 meters east. After each target, the varis_bekle function doesn't move on to the next line until the horizontal distance drops below 1 meter and the altitude difference below 0.5 meters.

Pythonhedef_bekle.py
import math
import time
from pymavlink import mavutil

BAGLANTI = "tcp:127.0.0.1:5760"   # Pi UART: "/dev/serial0"
BAUD = 57600                       # same as SERIALx_BAUD on the Pixhawk side
ESIK_M = 1.0                       # horizontal arrival threshold (meters)
IRTIFA_ESIK_M = 0.5

m = mavutil.mavlink_connection(BAGLANTI, baud=BAUD, source_system=255)
m.wait_heartbeat()
m.mav.request_data_stream_send(m.target_system, m.target_component,
                               mavutil.mavlink.MAV_DATA_STREAM_ALL, 10, 1)


def mesafe_m(lat1, lon1, lat2, lon2):
    r = 6371000.0
    p1, p2 = math.radians(lat1), math.radians(lat2)
    a = (math.sin((p2 - p1) / 2) ** 2 +
         math.cos(p1) * math.cos(p2) * math.sin(math.radians(lon2 - lon1) / 2) ** 2)
    return 2 * r * math.asin(math.sqrt(a))


def hedef_gonder(lat, lon, irtifa):
    m.mav.set_position_target_global_int_send(
        0, m.target_system, m.target_component,
        mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT,
        0b110111111000,                 # position only
        int(lat * 1e7), int(lon * 1e7), irtifa,
        0, 0, 0, 0, 0, 0, 0, 0)


def varis_bekle(lat, lon, irtifa, zaman_asimi=60):
    baslangic = time.time()
    while time.time() - baslangic < zaman_asimi:
        if m.flightmode != "GUIDED":
            print("Mode changed:", m.flightmode, "- bekleme iptal")
            return False
        p = m.recv_match(type="GLOBAL_POSITION_INT", blocking=True, timeout=2)
        if p is None:
            continue
        yatay = mesafe_m(p.lat / 1e7, p.lon / 1e7, lat, lon)
        dikey = abs(p.relative_alt / 1000 - irtifa)
        if yatay < ESIK_M and dikey < IRTIFA_ESIK_M:
            print(f"Arrived: horizontal {yatay:.2f} m, vertical {dikey:.2f} m, t={p.time_boot_ms/1000:.1f} s")
            return True
    print("Timeout: target not reached")
    return False


def kuzey_dogu(lat0, lon0, kuzey_m, dogu_m):
    dlat = kuzey_m / 6378137.0
    dlon = dogu_m / (6378137.0 * math.cos(math.radians(lat0)))
    return lat0 + math.degrees(dlat), lon0 + math.degrees(dlon)


# GPS, GUIDED, ARM, takeoff
while True:
    g = m.recv_match(type="GPS_RAW_INT", blocking=True)
    if g.fix_type >= 3 and g.satellites_visible >= 6:
        break
m.set_mode("GUIDED")
for deneme in range(5):            # ARM may be rejected on the first try
    m.arducopter_arm()
    m.recv_match(type="HEARTBEAT", blocking=True, timeout=3)
    if m.motors_armed():
        break
    time.sleep(8)
m.mav.command_long_send(m.target_system, m.target_component,
                        mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 0, 0, 0, 0, 0, 0, 0, 10)
ev = m.recv_match(type="GLOBAL_POSITION_INT", blocking=True)
lat0, lon0 = ev.lat / 1e7, ev.lon / 1e7
while m.recv_match(type="GLOBAL_POSITION_INT", blocking=True).relative_alt < 9500:
    pass
print("Takeoff complete")

# two points: first 40 m north, then 40 m east
for kuzey, dogu in ((40, 0), (40, 40)):
    lat, lon = kuzey_dogu(lat0, lon0, kuzey, dogu)
    hedef_gonder(lat, lon, 10)
    if not varis_bekle(lat, lon, 10):
        break

m.set_mode("LAND")
print("LAND")
  • Enter: put your own link on the BAGLANTI line. On the Raspberry Pi's UART, use "/dev/serial0" and the same baud as SERIALx_BAUD on the Pixhawk.
  • You'll see: a "Varildi" line at each point. The horizontal value on that line should be below the threshold.
  • If not: if it prints "Zaman asimi" after 60 seconds, the threshold is tighter than the position the drone can hold in the air. First set ESIK_M to 1.5 or 2, then check the GPS horizontal accuracy.

The function also checks the mode on every pass. If the pilot switches to LOITER or RTL from the transmitter, the wait ends and the code doesn't send the next target. That way Python doesn't take back the control the pilot has taken.

What you'll see

If you run the program and the drone completes both points, you'll see this in the terminal:

Output
Takeoff complete
Arrived: horizontal 0.94 m, vertical 0.02 m, t=4716.3 s
Arrived: horizontal 0.71 m, vertical 0.01 m, t=4724.0 s
LAND

The t value is the time the autopilot has counted since boot. The difference between the two lines tells you how many seconds the second 40-meter leg took, about 8 seconds in this example.

Error messages and their meanings

Mode change to Guided failed: requires position

The autopilot refused to switch to GUIDED while its position estimate wasn't ready. The code then stays in another mode, and varis_bekle prints "Mod degisti" on the first pass and exits. That's why the GPS loop in the program won't move on to the GUIDED command until it sees a 3D fix and at least 6 satellites.

Zaman asimi: hedefe varilamadi

The drone didn't get inside the threshold within 60 seconds. Either the threshold is too tight, the target is too far, or the drone can't hold its position that tightly in the wind. Print the last distance to the target and compare it with the threshold.

Mod degisti: LAND - bekleme iptal

The mode left GUIDED during the wait: the pilot took over or a failsafe kicked in. The code stops on purpose. Look for the reason in the Messages tab in Mission Planner.

Learn autonomous control with Python from start to finish

We explain step by step how the autopilot decides on arrival, which setting makes MISSION_ITEM_REACHED arrive, and which log field to check, in a lesson of the Drone Control with Python from Scratch course.

Was this article helpful?

Free resourceArduPilot SITL setup guideTry your code in SITL before heading out to the field: setup and connection, start to finish.