Help me optimise this arduino code (it runs to slow)

Well if you need help, we'll be here!

1 Like

arduino's are always a fun thing to have :smiley:

I don't see any reference to erroneous strings there.

But just logically, you'd get an incomplete string in cases where the string is just being sent while your code is reading it. That can happen with and without timeout.

EDIT: By without timeout I mean a timeout of 0.

It worked! huray!

Optimization tip, strings will eat up gobs of ram. Store them in flash by using the PROGMEM modifier or F( ) macro.

Serial.print(F("This is stored in FLASH"));

https://www.arduino.cc/en/Reference/PROGMEM

2 Likes

Nice, thank you

float AlphaFloat = 0.0;

floats are probably slow, int would be faster if possible

String RedStr = SoftSerial.readStringUntil(',');
Serial.read();
String GreenStr = SoftSerial.readStringUntil(',');
Serial.read();
String BlueStr = SoftSerial.readStringUntil(',');
Serial.read();
String AlphaStr = SoftSerial.readStringUntil('\0');
RedInt = RedStr.toInt();
GreenInt = GreenStr.toInt();
BlueInt = BlueStr.toInt();
AlphaFloat = AlphaStr.toFloat();

instead of reading strings in multiple passes and casting them to the proper type, serialize the input and grab everything at once.
Something like:

cin.get(redint","greenint","blueint","alphafloat"\n")

its sort of ugly, and can go wrong if your working with iffy code, but can free up a few cycles.

if not, reading until \n and iterating through the character array to get your ints and float would definitely use less ram, and possibly still be faster than multiple strings and typecasting.

RedInt = constrain(RedInt, 0, 255);
GreenInt = constrain(GreenInt, 0, 255);
BlueInt = constrain(BlueInt, 0, 255);
AlphaFloat = constrain(AlphaFloat, 0.0, 1.0);

instead of keeping them as integers (16 bit) and constraining them to 8bit numbers maybe cast them to byte?

i'm assuming that BluetoothData.equals("something") polls hardware or checks something.

That big nested if keeps checking over and over which is probably eating up time.
get the input once, and then decide what to do instead of getting input, if that fails grab input again and try until something catches.

string commandStr = BluetoothData.equals()
int enumCmd =0;
if commandStr == "readAll" enumCmd=1
if commandStr== "setLed" enumCmd=2
...

switch(commandStr)
case 1: //do stuff;
case 2: // do other stuff;
...

1 Like