LESSONEmbedded C · Part 5EP.56 · 24 s

#define: name your pins

// WHAT YOU WILL LEARN

#define swaps names for numbers before compiling (LED_PIN 5), so code reads like English.

// LESSON NOTES

PORTB |= (1 << 5); … what does that 5 even mean? 🤔

1️⃣ NAME IT: #define LED_PIN 5, #define LED_DDR DDRB, #define LED_PORT PORTB. Now the code reads like English: LED_PORT |= (1 << LED_PIN); (Tip: #define has no ; at the end.)

2️⃣ FIND & REPLACE: before compiling, the preprocessor swaps every name for its value, so the compiler sees PORTB |= (1 << 5);. It's just text: it uses zero bytes of RAM. Run it and bit 5 (PB5 = D13) lights the L LED.

3️⃣ CHANGE ONE LINE: move the LED to D12? Change LED_PIN to 4 and every line that uses it follows (bit 4 = PB4 = D12).

📌 One name, one place to change it.

TESTED CODE · ec05_define.c · avr-gcc
// EC L05 - #define: give numbers a name
#include <avr/io.h>

#define LED_PIN  5        // D13 = PB5
#define LED_DDR  DDRB
#define LED_PORT PORTB

int main(void) {
    LED_DDR  |= (1 << LED_PIN);
    LED_PORT |= (1 << LED_PIN);
    while (1) { }
}
Read the voiceover (transcript)
  1. What does this five even mean?
  2. Name it! Hash define LED pin five. Now your code reads like English!
  3. Before compiling, the preprocessor swaps every name for its value. It's just text: zero bytes of RAM!
  4. Move the LED? Change one line, and the whole program follows!
  5. One name, one place to change it!
  6. Next: what is a register? Follow for part six!

Related lessons