BareMetal-C

C99 Coding Guidelines for Bare-Metal C Course using SDCC

1. Macros & Preprocessor

Rationale: The preprocessor is a text substitution tool. Strict syntax prevents precedence errors and side effects.


2. Data Types & Precision

Rationale: Z80 int size varies by compiler. Explicit types prevent ambiguity. The C99 standard does not specify whether char by itself should be signed or unsigned; avoid using char as well.


3. Memory Mapped I/O (MMIO)

Rationale: “Writing to IO” is simply writing to a specific memory address.


4. Memory Management

Rationale: Memory is finite (SRAM) and there is no OS.


5. Functions & Control Flow

Rationale: The Z80 stack is small and easy to overflow.


6. Bit Manipulation

Rationale: Hardware control requires changing specific bits without affecting others.


7. SDCC Specific Constraints

Rationale: SDCC optimizations are tailored for 8-bit systems.


8. Operator Use & Clarity

Rationale: Explicit operations prevent ambiguity and ensure the read-modify-write cycle is visible.


Sample “Perfect” Student Code

/*
 * Hardware: Z80 simulated with memory mapped LED at 0x8000
 * Goal: Blink LED
 */

#include <stdint.h>
#include <stdbool.h>

// Rule 3.2: Defined as macro with cast. 
// Rule 1.2: Address is a bit-pattern, so use U suffix.
#define IO_LED       ((volatile uint8_t *) 0x8000U)

void delay_loops(uint16_t count) {
    while (count > 0) {
        // Rule 8.1: Explicit subtraction (no count--)
        count = count - 1;

        // Rule 7.3: NOP for delay
        __asm__("nop");
    }
}

void main(void) {
    uint8_t pattern = 0x01U;

    // Rule 5.2: Infinite Super Loop
    while (true) {
        // 1. Write to Data Bus
        *IO_LED = pattern;

        // 2. Wait
        // Rule 1.2: '5000' is a count/scalar, so NO U suffix.
        delay_loops(5000);

        // 3. Logic: Shift pattern left
        if (pattern == 0x80U) {
            pattern = 0x01U;
        } else {
            // Rule 8.1: Explicit shift
            pattern = pattern << 1;
        }
    }
}

9. Read the C99 Style Guide

Read the C99 Style Guide next.