Search code examples
c++arduinoled

Weird output for RGB


I am trying to manage some LED strips with my mobile device using bluetooth + Adafruit NeoPixel. I almost had the sketch finished but I have found the numbers for RGB are not appearing as I expected and I cannot find what I am doing wrong.

Imagine that from my mobile I have sent the following RGB code "0,19,255", when I check the console I see the following result:

output.png

As you can see the first two lines are ok, but the third one we can see 2550. The 0 should no be there and I cannot figure it out the problem.

So I decided isolate the code and try to keep the minimum to identify the root cause and this is the code:

#include <SoftwareSerial.h>
#include <Adafruit_NeoPixel.h>

SoftwareSerial BT (10, 11);

#define PIN        2
#define NUMPIXELS 144

Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRBW + NEO_KHZ800);

int red = "";

void setup() {
  Serial.begin(9600);
  Serial.println("Ready");
  BT.begin(38400);
  pixels.begin();           
  pixels.show();           
  pixels.setBrightness(20);
}

void loop() {
    while (BT.available()>0){
        red = BT.parseInt();
        Serial.println(red);
  }
}

Solution

  • You describe that for the shown output you sent via mobile "0,19,255".
    Yet in the shown output that obviously is only the second part of a longer sequence of numbers sent, which starts with "0,21".

    Assuming that what you send is always of the format you have described, i.e. three numbers, separated by two ",", the shown output is most likely the result of you sending first "0,21,255" and then another triplet "0,19,255".

    These two messages together would end up in an input buffer "0,21,2550,19,255".

    Now I have to do some speculation. Most parsers, when told to look for numbers within the buffer, will look for digits followed by non-digits. They would end up yielding "0,21,2550".

    Without knowing details of the parsers working it is hard to say how to fix your problem.
    I would however definitly experiment with sending triplets which end in a non-digit.

    For example:

    "0,21,255,"
    or
    "0,21,255 "
    or
    "0,21,255;"

    If none of them work you might need to explicitly expect the non-digit, i.e. between triplets of numbers read a character and either ignore it or compare it to " ,", " " or ";" for additional self-checking features.

    (Writing this I rely on user zdf not intending to make an answer, because while I did spot the "2550" as "255""0", zdf spotted the only two "," inside the question body in sample input, which I missed. I will of course adapt my answer to one created by zdf, to not use their contribution without their consent.)