Softivation

Pixhawk data is garbled in a C# interface: count the bytes first

If Pixhawk data comes out corrupted in a C# ground control station, the problem isn't the link; it's how you read the MAVLink frame. Symptom, cause, and working read code.

Furkan IŞIKAY 10 min read

You wrote your own ground control station in C#. The port opens, the light is on, bytes are flowing. But the altitude on the screen is 12 meters one moment and 3,400 meters the next. The yaw value also goes wild now and then.

The link isn't broken; the way you read is. If you read the same byte stream with two different designs, one extracts 5,440 packets, while the other invents 181 extra packets from the same stream.

What happens on screen

The symptom always comes in the same order. At first everything looks fine, a few seconds later a field jumps, then it recovers, then it jumps again. If you close and reopen the app, it works fine for a while longer.

This pattern comes from the parser starting a frame at a wrong spot inside the stream and then recovering at the next real frame.

The header tells you where the frame ends

The stream coming from the autopilot consists of MAVLink frames lined up back to back. Each frame starts with the byte 0xFD, but its length isn't fixed.

The header is 10 bytes, and the payload length comes in the header's second byte (LEN). The total length is 12 + LEN bytes. A signed frame adds 13 bytes to that. In a sample 20-second stream taken from ArduCopter, the packet length varies between 14 and 56 bytes.

This gives the first rule: you can only skip a frame by its own length. A read that assumes a fixed length slips at the second packet and never recovers.

A byte inside the payload can be 0xFD too

The common design is this: look for the byte 0xFD in the buffer and treat the spot you find as the start of a packet. But the payload carries raw binary data, and nothing prevents a 0xFD byte from appearing inside it.

In the figure below, you read the same bytes with two designs. Look at the FD with the yellow border: the read that looks for 0xFD stops there, while the read that advances frame by frame skips the length it calculated from LEN and never sees it.

The same bytes, two read designs

A MAVLink frame in the byte stream: header, payload, and CRC. The frame-by-frame read skips 12 plus LEN bytes and lands on the next real 0xFD. The read that looks for 0xFD stops at the FD byte inside the payload and starts a fake frame
Where to look: the FD byte with the yellow border. The dashed red arrow stops there and starts a fake frame. The blue arrow skips the length it calculated from LEN and never sees it.

The only thing that makes the distinction is CRC verification. If the CRC matches, it really is the start of a frame. If it doesn't, you've landed on a random byte inside the payload and you only shift by 1 byte.

In a 20-second, 190,653-byte stream taken from ArduCopter, the byte 0xFD appears 5,622 times, and 5,440 of them are real frame starts. In the same stream 0xFE also appears 143 times, which means code that looks for a v1 start triggers falsely that many more times. The ratio changes with the stream's content; it is never zero.

A Read call doesn't return as many bytes as you ask for

The second trap is in the read layer. On the C# side, both SerialPort and NetworkStream can return without filling the entire buffer.

If you read the same stream with a 256-byte buffer, 202 of 803 calls (25.2%) return fewer than 256 bytes. The smallest return is 25 bytes and the average is 237.4 bytes. 13.3% of the frames are also split across two separate read calls.

In the figure below, look at the yellow frame: the read boundary splits it in two, and the first piece waits for the next read.

A Read call cuts the frame in the middle

Frames of different lengths arriving back to back on the link. The boundaries of the Read calls split a frame in the middle, and the leftover part waits in the buffer and is completed by the next read
Where to look: the yellow frame. The red dashed read boundary splits it in two. The first piece waits at the start of the buffer until the next Read arrives.

Code that ignores the returned value and processes the whole buffer parses the bytes left over from the previous round a second time in a quarter of the reads. The resulting duplicate packets look like line noise, but the source is your own code.

Fix the read loop in two steps

Two fixes are enough. First, use the number that the Read call returns.

C#read loop
// Read does not return as many bytes as you asked for on every call.
// Ignoring the return value means processing the old part of the buffer again.
var tampon = new byte[256];
while (calisiyor)
{
    int adet = akis.Read(tampon, 0, tampon.Length);
    if (adet <= 0) break;                 // link closed
    okuyucu.BaytEkle(tampon, adet);       // only as many as actually arrived
}

Second, put in a reader that accumulates incoming bytes and consumes only frames whose CRC matches. The leftover tail is handed over to the next read.

C#frame reader
// Read MAVLink bytes, advancing frame boundary by frame boundary.
// Once the buffer fills, consumes every complete frame in it,
// and carries the leftover partial tail over to the next read.
class CerceveOkuyucu
{
    readonly byte[] _tampon = new byte[8192];
    int _dolu;

    public void BaytEkle(byte[] gelen, int adet)
    {
        if (_dolu + adet > _tampon.Length) _dolu = 0;   // stream corrupted, start over
        Buffer.BlockCopy(gelen, 0, _tampon, _dolu, adet);
        _dolu += adet;

        int p = 0;
        while (_dolu - p >= 12)
        {
            if (_tampon[p] != 0xFD) { p++; continue; }

            int govde = _tampon[p + 1];
            int imza  = (_tampon[p + 2] & 0x01) != 0 ? 13 : 0;
            int boy   = 12 + govde + imza;

            if (_dolu - p < boy) break;                 // frame not complete yet

            int mesajId = _tampon[p + 7] | (_tampon[p + 8] << 8) | (_tampon[p + 9] << 16);
            if (CrcTutuyor(_tampon, p, govde, mesajId))
            {
                CerceveGeldi(mesajId, _tampon, p + 10, govde);
                p += boy;                               // advance by one full frame
            }
            else
            {
                p++;                                    // no match: shift by just 1 byte
            }
        }

        _dolu -= p;
        Buffer.BlockCopy(_tampon, p, _tampon, 0, _dolu); // move the tail to the front
    }

    bool CrcTutuyor(byte[] d, int bas, int govde, int mesajId)
    {
        if (!CrcEkstra.TryGetValue(mesajId, out byte ekstra)) return false;
        ushort crc = 0xFFFF;
        for (int k = 1; k < 10 + govde; k++) crc = Biriktir(d[bas + k], crc);
        crc = Biriktir(ekstra, crc);
        ushort gelen = (ushort)(d[bas + 10 + govde] | (d[bas + 11 + govde] << 8));
        return crc == gelen;
    }

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

The CrcEkstra table holds one byte for each message ID and is generated from the MAVLink definitions. Don't write the table by hand; use a generated table. Otherwise verification fails on every message.

With this reader, the stream above stays in sync from start to finish and all 5,440 frames come through. The design that looks for 0xFD in the buffer finds the same 5,440 frames too, but it also produces 181 more records, and those records land on the screen with random field values.

Example: At the competition area you're tracking the drone on the ground station's map screen. The altitude box jumps to 3,400 meters every few seconds and comes back. When the referee asks about the screen, it's easy to blame the telemetry module or the antenna, but if the value jumps and recovers, then jumps again, look at your read loop first. If the jumps stop once you put in the reader above, the problem was never the link.

The difference between TCP and a serial link

The numbers above are from a TCP connection. The framing logic is the same on both links; what changes is how the bytes arrive over the link.

  • On the TCP side, no bytes are lost and the order isn't disturbed. Every loss of sync you see comes from your code.
  • On a serial link, noise, baud drift, and a lack of flow control can really drop bytes. There, CRC catches both your mistake and the link's mistake.
  • If the SERIAL1_BAUD parameter says 57, the link is running at 57,600; the value is stored divided by a thousand.

Error Messages and Their Meanings

These three messages come out exactly this way on the .NET side. Which one you see tells you which layer the problem is in.

System.UnauthorizedAccessException: Access to the port 'COM3' is denied.

Another program is holding the port open. Mission Planner or an instance left over from a previous run is holding the line. Two applications can't share the same serial port.

System.IO.IOException: Unable to read data from the transport connection: Connection timed out.

The connection was established but the read timed out. You see this message if the baud rate doesn't match or the other side isn't speaking MAVLink. Check the SERIALx_PROTOCOL value first.

System.Net.Sockets.SocketException: Connection refused

On the TCP side, nobody is listening at the far end. The program you're trying to connect to has closed or the port number is wrong. When you see this message, there's no point tinkering with the parser; no bytes are arriving yet.

More on this topic

The reader above is the lowest layer of a working ground control station. The interface, logging, and command-sending layers sit on top of it.

The lesson that builds these end to end is in the C# Course from Beginner to Advanced. It also covers the firmware's decision order, log signatures, and board-specific differences.

Softivation YKİ library: start with a MAVLink connection, Turkish documentation, and a ready-made test interface when you write your own ground control station in C#.

Was this article helpful?

Free resourcePixhawk and ArduPilot error message glossaryThe messages in this article and similar ones are in the glossary: what they mean, why they appear, what to check first.