Softivation

Flight mode jumps to STABILIZE in a C# ground station

If the flight mode in your C# ground station jumps between GUIDED and STABILIZE, you're also reading the Pi's HEARTBEAT. Here are the filter that separates the autopilot's message, and the code.

Furkan IŞIKAY 11 min read

In the C# ground station you wrote yourself, you put the drone in GUIDED. The mode label says GUIDED for a moment, then goes back to STABILIZE, then GUIDED again. Mission Planner shows a steady GUIDED at the same time, and nobody is touching the transmitter.

This often starts the week a Raspberry Pi is mounted on the drone. What breaks the label is a second HEARTBEAT arriving on the same link. The drone's mode hasn't changed.

Why the mode label flips back and forth

The autopilot sends a HEARTBEAT message once per second and writes the flight mode as a number in this message's custom_mode field. On Copter, 0 means STABILIZE, 4 means GUIDED, and 5 means LOITER.

The autopilot isn't the only one that sends a HEARTBEAT. MAVProxy or mavlink-router running on the Pi, and a gimbal or camera that speaks MAVLink, also send their own. These don't carry a flight mode; they write 0 into custom_mode most of the time, and sometimes a number with their own meaning. 0 also maps to STABILIZE in the Copter table.

The Pixhawk also forwards the HEARTBEAT from the Pi on TELEM2 to its other telemetry ports. If your GCS listens through the radio on TELEM1, it receives messages from both sources back to back on the same link. Code that reads the mode from every incoming HEARTBEAT rewrites the label on every message.

Two HEARTBEATs on the same link, two different labels on screen

Two HEARTBEATs on the same link, two different labels on screen
Line up with the red dots: the middle label drops to STABILIZE at each one, while the bottom one stays put.

The top strip of the figure shows the order of arrival on the link. Each packet from the Pi sets the unfiltered code's label to STABILIZE until the next autopilot message. The filtered code ignores those packets entirely.

In a Fighting UAV mission, while the Pi finds the target on the camera and steers the drone in GUIDED, the pilot sees STABILIZE on screen and reaches for the transmitter even though the drone is flying in the mode you wanted.

Separate the autopilot's message from the rest

Every MAVLink packet carries who it came from: a system ID (sysid) and a component ID (compid). The autopilot talks with compid 1. The Pi in the figure uses 191, the companion computer's ID.

The second marker is the HEARTBEAT's autopilot field. By MAVLink convention, every device that isn't an autopilot writes 8 here, while ArduPilot sends 3. MAVLink's heartbeat page also gives the recommended way to identify an autopilot as this field not being 8.

Write the mode to the screen only when three conditions hold together: the sysid is your vehicle, the compid is 1, and autopilot is not 8.

You may not see the problem at the bench. The Pixhawk forwards messages only to ports that have sent it at least one packet. A GCS that sends no packets never receives the Pi's HEARTBEAT. After the first ARM or mode command, those messages start arriving too, and the label breaks.

C# code with the filter

The program below reads MAVLink from a serial port or TCP and prints two columns for each HEARTBEAT: the mode that code reading every message would show, and the mode the filtered code shows. It also sends its own HEARTBEAT once per second. That way the Pixhawk treats the port as active and you see the real traffic from the field.

  • Enter: create a new project with dotnet new console, add the serial port package with dotnet add package System.IO.Ports, and replace Program.cs with this code. Set HedefSysid to your vehicle's MAV_SYSID value.
  • You'll see: on each line, the source's sysid:compid, the type and ap fields, and the two-column mode.
  • If not: if there's no second source in the list but the label still jumps, look at the ap column. If two different rows show 3, two vehicles on the same radio network are using the same MAV_SYSID.
C#Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Net.Sockets;

// Usage: dotnet run -- COM5 57600 or dotnet run -- tcp 127.0.0.1 5760
Stream akis;
if (args[0] == "tcp")
    akis = new TcpClient(args[1], int.Parse(args[2])).GetStream();
else
{
    var port = new SerialPort(args[0], int.Parse(args[1]));
    port.Open();
    akis = port.BaseStream;
}

const byte HedefSysid = 1;          // the vehicle's MAV_SYSID value
string ekrandakiMod = "?";

var copterModlari = new Dictionary<uint, string> {
    [0] = "STABILIZE", [1] = "ACRO", [2] = "ALT_HOLD", [3] = "AUTO", [4] = "GUIDED",
    [5] = "LOITER", [6] = "RTL", [7] = "CIRCLE", [9] = "LAND", [11] = "DRIFT",
    [13] = "SPORT", [14] = "FLIP", [15] = "AUTOTUNE", [16] = "POSHOLD", [17] = "BRAKE",
    [18] = "THROW", [19] = "AVOID_ADSB", [20] = "GUIDED_NOGPS", [21] = "SMART_RTL",
    [22] = "FLOWHOLD", [23] = "FOLLOW", [24] = "ZIGZAG", [25] = "SYSTEMID",
    [26] = "AUTOROTATE", [27] = "AUTO_RTL", [28] = "TURTLE" };

string ModAdi(uint m) => copterModlari.TryGetValue(m, out var ad) ? ad : $"MOD_{m}";

// Is it the autopilot's HEARTBEAT? Companion computers, gimbals and GCSs send autopilot=8.
bool OtopilotMu(byte sysid, byte compid, byte autopilot) =>
    sysid == HedefSysid && compid == 1 && autopilot != 8;

// The autopilot forwards messages only to ports it has received packets from.
// That's why the GCS sends its own HEARTBEAT once per second.
byte sira = 0;
using var hbZamanlayici = new System.Threading.Timer(_ =>
{
    var paket = GcsHeartbeat(sira++);
    try { akis.Write(paket, 0, paket.Length); } catch (IOException) { }
}, null, 0, 1000);

var tampon = new List<byte>();
var oku = new byte[512];
while (true)
{
    int n;
    try { n = akis.Read(oku, 0, oku.Length); }
    catch (IOException) { break; }                      // connection lost
    if (n <= 0) break;
    for (int i = 0; i < n; i++) tampon.Add(oku[i]);
    while (CerceveAl(tampon, out byte sys, out byte comp, out uint msgid, out byte[] yuk))
    {
        if (msgid != 0) continue;                       // HEARTBEAT only
        var p = new byte[9];
        Array.Copy(yuk, p, Math.Min(yuk.Length, 9));    // MAVLink2 trims trailing zeros
        uint customMode = BitConverter.ToUInt32(p, 0);
        byte tip = p[4], autopilot = p[5];
        string ham = ModAdi(customMode);
        string not = "";
        if (OtopilotMu(sys, comp, autopilot)) ekrandakiMod = ham;
        else not = " (skipped)";
        Console.WriteLine($"{sys,3}:{comp,-3} type={tip,-2} ap={autopilot} mode={customMode,-2} | raw: {ham,-9} | filtered: {ekrandakiMod}{not}");
    }
}

// Extracts a single MAVLink frame from the buffer; drops the frame if the CRC fails.
static bool CerceveAl(List<byte> t, out byte sys, out byte comp, out uint msgid, out byte[] yuk)
{
    sys = comp = 0; msgid = 0; yuk = Array.Empty<byte>();
    while (t.Count > 0)
    {
        int bas = t.FindIndex(b => b == 0xFD || b == 0xFE);
        if (bas < 0) { t.Clear(); return false; }
        if (bas > 0) t.RemoveRange(0, bas);
        bool v2 = t[0] == 0xFD;
        int baslik = v2 ? 10 : 6;
        if (t.Count < baslik) return false;
        int len = t[1];
        int imza = v2 && (t[2] & 0x01) != 0 ? 13 : 0;
        int toplam = baslik + len + 2 + imza;
        if (t.Count < toplam) return false;
        msgid = v2 ? (uint)(t[7] | t[8] << 8 | t[9] << 16) : t[5];
        sys = v2 ? t[5] : t[3];
        comp = v2 ? t[6] : t[4];
        ushort crc = 0xFFFF;
        for (int i = 1; i < baslik + len; i++) crc = X25(crc, t[i]);
        // CRC is checked for HEARTBEAT only (crc_extra = 50)
        bool tamam = msgid != 0 || (ushort)(t[baslik + len] | t[baslik + len + 1] << 8) == X25(crc, 50);
        yuk = t.GetRange(baslik, len).ToArray();
        t.RemoveRange(0, tamam ? toplam : 1);
        if (tamam) return true;
    }
    return false;
}

// MAVLink2 HEARTBEAT: sysid 255, compid 190, tip=6 (GCS), autopilot=8 (INVALID)
static byte[] GcsHeartbeat(byte seq)
{
    byte[] p = { 0xFD, 9, 0, 0, seq, 255, 190, 0, 0, 0,
                 0, 0, 0, 0, 6, 8, 0, 0, 3, 0, 0 };
    ushort crc = 0xFFFF;
    for (int i = 1; i < 19; i++) crc = X25(crc, p[i]);
    crc = X25(crc, 50);
    p[19] = (byte)crc; p[20] = (byte)(crc >> 8);
    return p;
}

static ushort X25(ushort crc, byte b)
{
    byte tmp = (byte)(b ^ (crc & 0xFF));
    tmp ^= (byte)(tmp << 4);
    return (ushort)((crc >> 8) ^ (tmp << 8) ^ (tmp << 3) ^ (tmp >> 4));
}

If you start it with the radio's port and the Pi is sending a HEARTBEAT from TELEM2 while the drone is in GUIDED, you'll see this:

Output
dotnet run -- COM5 57600
  1:1 type=2 ap=3 mode=4 | raw: GUIDED | filtered: GUIDED
  1:191 type=18 ap=8 mode=0 | raw: STABILIZE | filtered: GUIDED (skipped)
  1:1 type=2 ap=3 mode=4 | raw: GUIDED | filtered: GUIDED

The raw column of the middle row is the value shown on screen by a GCS that updates its label from every HEARTBEAT.

Blocking the Pi's HEARTBEAT at the Pixhawk

If the Pi never talks to the ground station, you can also turn off forwarding on the autopilot. In ArduPilot 4.7, this setting is bit 1 of the MAVn_OPTIONS parameter. Set the value to 2 on the channel the Pi is connected to and restart the Pixhawk. Without a restart, forwarding continues.

Here n is the order of the ports that speak MAVLink. If USB, TELEM1 and TELEM2 are all on MAVLink, TELEM2 becomes MAV3. The setting cuts both directions, so no messages go from the ground station to the Pi either. If the Pi needs to send data to the GCS, don't touch this setting; fix the code.

Error Messages

Old forum answers say to add 1024 to SERIALn_OPTIONS to cut forwarding. In 4.7 this bit moved to MAVn_OPTIONS. If you set the old bit by hand, the drone won't arm, and the message shows the number of whichever port you configured instead of SERIAL1.

Subtract 1024 from SERIALn_OPTIONS, add 2 to the matching MAVn_OPTIONS, and restart the Pixhawk. The PreArm line goes away.

What's in the course

You'll find the version that discovers the target sysid on its own and picks the mode table from Copter or Plane by vehicle type, the source-code explanation of why and to which port the Pixhawk forwards the HEARTBEAT, and the quick diagnosis table in the Latest Additions section of the C# Course from Beginner to Advanced.

Custom Turkish Ground Control Station Library: a MAVLink GCS library written in C#, with Turkish code comments and documentation.

Was this article helpful?

Free resourceTEKNOFEST UAV software readiness checklistCheck off your UAV software readiness stage by stage on a printable list.