The thing I love about programming for Arduino is that, unlike programming in most other environments nowadays, you are forced to think about memory footprint, memory allocation, and how your code relates to the hardware.
That’s great for people like me who don’t really consider themselves coders at all, because “perfect code” is less about something that’s mathematically beautiful and conceptually elegant, and more about getting the job done. In fact the code is often more efficient if you spell it out line-by-line in a bunch of nested if statements, rather than abstracting it into a pre-written processing function that may do the job in fewer lines of code but end up costing more in storage space because the function itself is general purpose.
Take for example this code. Horrendous to mathematicians I’m sure, but lovely for electronics engineer types;
void callback(char* topic, byte* payload, unsigned int length) {
Serial.println("Volume Callback");
if (length == 1) { output = payload[0] - 48; Serial.println(output); }
else if (length == 2) { output = ((payload[0] - 48) * 10 + (payload[1] - 48)); Serial.println(output); }
else if (length ==3) { output = 100; Serial.println(output); }
}
In the above you can see I have a byte array, each location in the array is an ASCII representation of a digit that forms a number. I know that number coming in from the payload will only ever be between 0 and 100, AND have considered in what situations that might not be the case and what would happen. So it will have a maximum of 3 digits. Indeed if it does have 3 digits the number must definitely be exactly 100. And so rather than using expensive string to integer manipulation functions which add 2k (yes, 2k!) to my sketch it is cheaper to write it out in if statements that calculate it in a “units – tens – hundreds” way working on the basis that the characters 0 to 9 are represented in the ASCII table consecutively.
So oftentimes it’s more computationally efficient to write more lines of code than fewer, which is great for idiots like me who tend towards wanting to put everything in terms of flow charts and IF statements!
There are so many examples of the above I’ve discovered so far, e.g. using a switch statement, whilst looking a little clearer on the page, is worse than using IF statements unless you have over at least 4 cases. The exact detail depends on your sketch and how variables are stored of course.
Arduino helps us by showing us how many bytes your sketch is at compile time. Great for keeping an eye on things as you progress your project.
Leave a Reply