Optimizing Arduino Code

Optimizing Arduino Code
Photo by Harrison Broadbent / Unsplash

This is generally an uninteresting post. Skipping it is for the best. I am just testing out copying and pasting from Obsidian (my markdown based note editor of choice).

Problem

I'm working on my Room Occupancy Monitor project for intro to hands on engineering, but the damn Arduino Uno R3 only has 2KB of SRAM. Normally this is fine but the OLED display I'm using is 64x128 and requires 1KB of memory for the frame buffer (64x128 * 1byte/8bits). This is a problem as . With my current code I have 1144B left for local variables, but with the display's memory usage that only leaves me with 120B of memory left which... is not a lot. I could upgrade from the R3 to the R4 which would be great and all, but that costs money.

Other people have had this issue already so I'll use them as a baseline of what to do.

Working on it

So I did a bit of experimenting and bringing the memory usage down and leaving 1165B free allows the code to compile and allocate properly. Unfortunately the way I accomplished this is by breaking the "leaving room" counter functionality. I need to cut off ~20B of variables.

Looked around and changed the "distance" floats to int16_t:

// sonar stuff

int16_t calibrate_0 = 0, calibrate_1 = 0; // The calibration in the setup() function will set these to appropriate values.

int16_t distance_0, distance_1; // These are the distances (in cm) that each of the Ultrasonic sensors read.

int8_t count = 0, limit = 4; //Occupancy limit should be set here: e.g. for maximum 8 people in the shop set 'limit = 8'.

bool prev_blocked0 = false, prev_blocked1 = false; //These booleans record whether the entry/exit was blocked on the previous reading of the sensor.

And like that, I now have 1186B free! By changing 4 variables from float to int16, I saved 42B! I lose some precision on the distance sensors, but considering I'm using them more as tripwire sensors than actual distance sensors I think centimeter level-precision should be fine.

This may prove an issue in the future as I'm going to need to add more logic but I have little space for further storing of them. I guess this is what I get for using an old micro-controller as opposed to a microprocessor (like a pi), it's really not designed for heavy computational workloads.

Funny Tidbit

Arduino code is based of C++ which is... dangerous. For example, I was writing to the LED strip info vector but I accidentally indexed too high. Since there is no compiler check on this, this OVERWROTE the sensor calibration values to 0 (because I was setting the display LED's to black). Christ that took me a long time to figure out.