So im making a bluetooth controlled RGB led strip with arduino and i've been advised not to use the Serial.readString() function , so i tried making a loop like thingy but its not working, can anyone help me out
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
void loop() {
//while is reading the message
while(Serial.available() > 0){
r_char = char(Serial.read());
if(r_char == 'R'){
flag = true;
}
else{
message += r_char;
}
}
yes(); }
void yes(){
if(flag == true){
redTempValue= message.substring(0,message.indexOf('G'));
greenTempValue= message.substring(message.indexOf('G')+1,message.indexOf('B'));
blueTempValue= message.substring(message.indexOf('B')+1,11);
Serial.print('R');
Serial.println(redTempValue.toInt());
Serial.print('G');
Serial.println(greenTempValue.toInt());
Serial.print('B');
Serial.println(blueTempValue.toInt());
Serial.print("MESSAGE ");
Serial.println(message);
}
flag=false;
message= "";
}
THE input is supposed to be like this : R255G255B255
I tried to test this code with a serial monitor and its not working...
the output it gives is in the attachments but its like this
If your strip is an addressable strip where each led can be addressed individually, you must be careful. During the update of the strip, interrupts are disabled and you can loose serial data.
No, but you can find a character with strchr() and a substring with strstr(). And the link I provided comes with a parse example that demonstrates how to extract data if you use comma separation.
Does not look like it's addressable so the examples in Serial Input Basics - updated should give you something to go on.
You can change the format that you send to <r,g,b>; e.g. <255,0,0> for red. There is no need to add a letter for the colour, it's defined by the 'protocol' which says that the first number is for red, the second one for green and the last one for blue.
thanks all for help and i made it work, i made changes to the mobile app to send in R255G255B255E format and changed the code to stop reading the string at E and somehow it works without any errors!!! yayyyy
Yes you can. Wrap the char[ ] in a SafeString and then use String type methods on that.
char input[ 30];
// some reading stuf here
cSFA(sfInput,input); // wrap the char [ ] in a SafeString
int idx = sfInput.indexOf('R'); // etc
SafeString toInt(i) returns true or false and update i if true. It is much more robust then String.toInt or c-string atol. both of which just return 0 if the number is invalid.
People forget , including myself, that you can set the timeout for readString and readStringUntil( ) using Serial.setTimeout( ). So setting the timeout to say 2mS for 9600 baud gives a very responsive readString and readStringUntil
Edit - But.. That approach still blocks the whole loop while the Input is being read which can be a problem.
See my tutorial on Arduino Software Solutions for lots of alternatives for reading from Serial with their pros and cons.