From C to Assembly: Blinking an LED the Hard Way
~4 hours of digging, one blinking LED, and a much better mental model of what "compiling" actually means.
The Inspiration
I've been programming since 2017 — variables, control flow, HTTP, web apps, the usual path. But I kept coming back to something Linus Torvalds said: that the compiler writes 100% of the code. I wanted to actually understand what that meant before taking it for granted.
So I went looking for the layer beneath the code I usually write: binary → hexadecimal opcodes → assembly → C. I wanted to see the whole stack, not just use the top of it.
What I Tried
I already knew my way around the Arduino IDE for uploading compiled sketches. While researching, I found out you could write raw hex machine code directly for the Arduino — but the resources I found were too dense to follow. So I stepped back one level, to assembly.
Searching further, I found a YouTube channel with an Arduino-assembly series. I copied one of their examples — a basic LED blink written entirely in AVR assembly, called from a C wrapper — and flashed it to my Uno.
That's when things started clicking. To actually understand why the code worked, I read up on:
- What the ALU and control unit do
- The chip's data width and address width
- How the ATmega328P's clock cycles are used to build a real time delay, using nothing but labeled code blocks acting as a loop
Seeing a for loop built from scratch — just labels, compares, and branches — out of raw instructions was the most satisfying part of the whole exercise.
The Code
The C side just declares the assembly routines as extern "C" and calls them from setup() and loop():
The actual work happens in the .S file — setting the pin direction with SBI DDRB, 4, toggling the LED with SBI/CBI PORTB, 4, and a hand-rolled delay loop using registers R20, R30, and R31:
Takeaway
A digitalWrite(LED, HIGH) is, underneath, a single bit flipped in a port register — and a delay() is just a loop counting down through however many clock cycles you need. Once you've built both by hand, the "high-level" versions stop feeling like magic and start feeling like a well-earned shortcut.
References
Further reading from my own research session: ChatGPT conversation · Perplexity search


Comments
Post a Comment