Bad data on Serial controlled LED strip using Serial.ReadBytesUntil()

Hello,

Just to give some context, I made a project in which I can control 358 ws2812b Neopixels with an AzDelivery ESP32-WROOM-32. I love this chip and the project already functions perfectly fine with a http server running to control it. If you don't care about the things that worked before I recommend you skipping to the code now.

The thing I had in mind was to add a way for my PC to communicate with the ESP32 so I can display more complex animations on it. At first I tried to make it happen using a C++ Serial library but for some reason it was really slow when sending lots of data so I stopped working on that.
Then I switched over to a C# windows forms application and now I use the System.IO.Ports.SerialPort class for this.

As a proof of concept I sent the data to the LED strip in a string format. For example the string "000255000255000000\n" would mean the first pixel would be green and the second one would be red. It was done using the Serial.readStringUntil('\n') function and I got it to work with a baud rate of 500000. This worked quite well but I found out I had to pause around 30-50 ms to not write the data to the port too fast. I measured how long it took for the arduino to clear the buffer with this function and update the strip and it took around 82ms on average (with the readStringUntil() function taking around 67ms).
With some simple math I was able to figure out that this would be 1000 / 82 = 12 frames per second at most. This obviously is not acceptable when displaying fast moving complex patterns like waves. With a baud rate of 500000 and 358 neopixels the theoretical max lies at 500000 / 10 / 358 / 3 / 3 = 15 frames per second when using strings to send the data. (baudrate / 10 / numpixels / ledsperpixel / bytesperled).

So yeah, my results aren't half bad. The obvious thing to optimize now was the way I sent the data. Because I stored each value for an LED in integer form in a string this meant a value of 0-255 would take up 3 chars each. A value of 0-255 can obviously be stored as a single byte instead of as 3 bytes by using chars so this would make it around 3 times more efficient.

The only thing I changed was replacing the Serial.readStringUntil() function with the Serial.readBytesUntil() function and matching the logic to handle led values as bytes using the following code on the arduino.

byte data[1074];
int buffersize = sizeof(data) / sizeof(data[0]);
long ms;

if (Serial.available() > 0){
    ms = millis();

    Serial.readBytesUntil('\n', data, buffersize);

    for(int i = 0; i < NUMPIXELS; i++) {
      byte r = data[i * 3 + 0];
      byte g = data[i * 3 + 1];
      byte b = data[i * 3 + 2];

      pixels.setPixelColor(i, pixels.Color(r, g, b));
    }
    pixels.show();

    Serial.println(millis() - ms);
  }

The problem I'm experiencing with this function is that the time delta being returned by the Serial.print() is all over the place now and prints 11-12ms on the first time I send data and 32-33ms on the second time. This pattern repeats indefinetely and for some reason when displaying animations on it now it gets garbled after a few frames no matter how slow I play it. There must be something I'm doing wrong here.

This is the function I use to send the data (I use lists as I don't really care about efficiency on the PC end at the moment):

private void sendToArduino(List<byte> data)
    {
        if (connected)
        {
            data.Add((byte)'\n');
            port.Write(data.ToArray(), 0, data.Count);
        }
    }

This is the function I wrote for the wave pattern, which I use for testing animations:

double offset = 0;
double alpha;
Color Color1 = button4.BackColor;
Color Color2 = button5.BackColor;
List<byte> data = new List<byte>();
while (sinwave)
{
    data.Clear();
    if (offset > 2 * Math.PI)
        offset -= 2 * Math.PI;
    for (int i = 0; i < numpixels; i++)
    {
        alpha = (Math.Sin(i / sinlength + offset) + 1) / 2;
        data.Add((byte)(Color1.R + alpha * (Color2.R - Color1.R)));
        data.Add((byte)(Color1.G + alpha * (Color2.G - Color1.G)));
        data.Add((byte)(Color1.B + alpha * (Color2.B - Color1.B)));
    }
    sendToArduino(data);
    offset += ((double)1 / sinlength) * ((double)numpixels / 43.2);
    Thread.Sleep(50);
}
return;

I'm new to this forum but thanks in advance for anyone willing to waste their precious time on me.

If you send binary data, '\n' (0x10) is a valid value so I would not use readBytesUntil but readBytes and specify the number of bytes.

I'm absolutely not familiar with the ESP32; the only thing I know is that it's a two-core processor. So I might be totally on the wrong track with the below.

One possible problem is that the update of 358 neopixels takes 30 microseconds per pixel so 10 milliseconds for your strip; during that time, interrupts are disabled (at least on AVR processors, I think that the ESP32 is not different) and you might loose transmitted data.

One way to solve it is to transmit one byte from the PC, wait for an echo from the ESP32, send the next byte, wait for an echo, send the third byte and wait for an echo. That way you know when the ESP32 has handled the full message (3 bytes) and that you can send the next one. You might have to add some syncing capabilities so you can be sure that the first byte received is indeed the first byte of the 3-byte packet.

Another problem that I can see is that serial printing is buffered so you do not directly send. While the buffer is not full, you can write to the (internal) serial buffer without delay; after that, Serial print becomes blocking. Again, this applies to AVR but might also apply to the ESP32.

Thanks for using code tags in your first post.

Thanks for your reply! Wish I had seen it sooner lol, I found it hard to find my own post on this platform and expected to get a notification.

But I came back here because I also finally realized that \n is a valid byte character. I should have known that but I decided to switch over to Serial.read() anyways because this doesn't stop code execution (even though I plan on using the second core for the webserver so it doesn't matter that much).
I made it so that the arduino reads the bytearray until it encounters a byte value of 254 and the C# program changes all 254 data values to 255. This way the LED strip can still be at full brightness but due to the way our eyes and the intensity of these LEDs work you will never be able to tell the difference between a brightness of 254 and 255. Probably could get away with specifying the number of bytes to read but if it somehow misses even 1 byte it could break.
I might still add some syncing functionality so I don't have to manually configure a sleep delay so it runs at the max possible framerate but this could also introduce inconsistencies. Also was a little problem with the alpha variable always being the same due to a casting problem.

Thanks for going the extra step and giving the additional information which was a very useful insight and definitely something I will keep in mind.

It now works with a delay of exactly 20ms, anything below that and the end of the strip starts showing 'random' colors. This works out to exactly 50fps which is much better than before :), it's actually at the theoretical max framerate for 500000 baud. I could probably optimize it by increasing the baud rate and get it to 60fps+ but this is already over 4 times better.

Hartelijk bedankt (:

There was another topic where the user decided to use 255 as the end marker; he/she left 254 as the maximum value. Same effect.

Graag gedaan :wink: