## Concurrency in Single-Core Microcontrollers
The ATmega328P possesses a single processing core running at 16 MHz. It cannot execute true multi-threaded parallel computation. Yet embedded systems must simultaneously read sensors, update displays, listen for serial telemetry, and respond instantly to emergency stop buttons.
Achieving responsiveness requires two essential programming patterns: non-blocking cooperative task scheduling and hardware interrupt service routines.
1. The Evils of delay() vs Non-Blocking millis()
When you execute delay(500), the CPU enters a tight counting loop:
CPU CLOCK TIMELINE WITH delay():
[ Task 1: Check Temperature ]
|
v
[ delay(5000) ] ===> [ CPU FROZEN: 80,000,000 CLOCK CYCLES WASTED ] ===>
|
(Emergency Stop button pressed during delay is COMPLETELY IGNORED!)
CPU CLOCK TIMELINE WITH millis() NON-BLOCKING SCHEDULER:
Cycle 0ms: Check Temperature? (Interval not met -> skip)
Cycle 1ms: Check Button State? (Instantly processed!)
Cycle 2ms: Update LED Display? (Done)
Cycle 3ms: Read Serial Port? (Done)
... (Repeats thousands of times per second without ever stalling!)2. Hardware Interrupt Architecture
A Hardware Interrupt is an electrical mechanism that forces the CPU to suspend its current execution, save its program counter register onto the stack, and jump to a specialized function called an Interrupt Service Routine (ISR):
Normal loop() Execution: [ Step A ] ---> [ Step B ] --------(Paused!)--------> [ Step C ]
| ^
ELECTRICAL TRIGGER (Pin D2 RISING EDGE): | (Jump to ISR) | (Resume)
v |
Interrupt Service Routine (ISR): [ Execute ISR Action ] --+ATmega328P External Interrupt Pins
- INT0: Digital Pin D2
- INT1: Digital Pin D3
Interrupt Modes
- LOW: Triggers continuously whenever the pin is at 0V.
- CHANGE: Triggers whenever the pin changes state (HIGH-to-LOW or LOW-to-HIGH).
- RISING: Triggers on the transition from LOW to HIGH (0V to 5V).
- FALLING: Triggers on the transition from HIGH to LOW (5V to 0V).
3. The 4 Golden Rules of Writing ISRs
+-----+----------------------------+---------------------------------------------------+
| No. | Engineering Rule | Technical Reason & Hazard Avoidance |
+-----+----------------------------+---------------------------------------------------+
| 1 | **Keep ISRs Ultra-Short** | Long ISRs stall timer updates and block other |
| | (< 50 microseconds) | pending interrupts. Never do math or loops in ISR.|
+-----+----------------------------+---------------------------------------------------+
| 2 | **Never Call delay()** | delay() depends on hardware Timer0 interrupts, |
| | | which are disabled inside an ISR. delay() hangs! |
+-----+----------------------------+---------------------------------------------------+
| 3 | **Never Call Serial.print()| Serial transmission relies on UART interrupts; |
| | | calling Serial inside an ISR causes deadlocks. |
+-----+----------------------------+---------------------------------------------------+
| 4 | **Declare Shared State as | Informs the C++ compiler that the variable can |
| | volatile** | change unexpectedly outside the main program flow.|
+-----+----------------------------+---------------------------------------------------+Production ISR Implementation: Rotary Encoder / Pulse Tachometer
// =============================================================================
// HIGH-SPEED PULSE TACHOMETER USING HARDWARE INTERRUPT
// =============================================================================
const uint8_t INTERRUPT_PIN = 2; // Pin D2 (INT0)
volatile uint32_t pulseCount = 0; // Volatile: modified inside ISR!
uint32_t lastReportTime = 0;
// Interrupt Service Routine (Must take no arguments and return void)
void countPulseISR() {
pulseCount++; // Ultra-fast single atomic increment
}
void setup() {
Serial.begin(115200);
pinMode(INTERRUPT_PIN, INPUT_PULLUP);
// Attach ISR to Pin 2 on Falling Edge (active-low pulse)
attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), countPulseISR, FALLING);
}
void loop() {
uint32_t now = millis();
// Report calculated RPM once every 1000ms
if (now - lastReportTime >= 1000) {
lastReportTime = now;
// Atomically copy and reset the volatile counter
noInterrupts(); // Disable interrupts briefly to prevent race conditions
uint32_t copyCount = pulseCount;
pulseCount = 0;
interrupts(); // Re-enable interrupts immediately
uint32_t rpm = (copyCount * 60); // Assuming 1 pulse per revolution
Serial.print(F("RPS: "));
Serial.print(copyCount);
Serial.print(F(" | Motor Speed: "));
Serial.print(rpm);
Serial.println(F(" RPM"));
}
}