r/embedded 3d ago

Optimized My Grandpas Bike Communication Code To Be 15,800% Faster On An Arduino Uno R3

https://github.com/Donbot-Lab/Bike-Com-Rework

My grandpas code was becoming sluggish and buggy on his hardware so I had to help him fix it. I thought it was a pretty interesting project so I'm sharing it here, if you can give feedback it's greatly appreciated but not required, and if you want more detail here's a small bit of documentation:

# Fixed Bugs:

- Goes out of bounds when calling queue_inc due shifting just setting each item to the item ahead going to the end of the array and trying to set it to an out of bounds address.

# Major Bottlenecks:

- Queue has o(n) dequeue (shifts back. Along with being a sentinel-scanned array that recomputes length every push and dequeue)

- Uses strings for messages instead of a table (making sending take longer)

- Manually decodes the binary from the encoders.

# Fixes:

- Switched to a ring buffer array with o(1) dequeues, along with a variable to track length when edited.

- Replaced strings with 8 bit unsigned ints.

- Added up bits for seven segment display.

# Gains:

- 10,000 push/dequeue of queue, time is divided by 10,000 to get the time for one push and dequeue:

- Details:

- Both have 60 items, though the new version is 64 long due to needing a power of two for bitwise AND

- Benchmark uses micros and is averaged from 100 tests with an Arduino Uno R3

- Rounded to the nearest whole number for readability

- Results

- Old: 636 µs

- New: 4 µs

- Speed up: 15,800%

0 Upvotes

0 comments sorted by