Your First Circuit: Blinking an LED
The classic first microcontroller project: make an LED blink, on purpose, using nothing but a pin, a resistor, and a short delay loop.
Blinking an LED is the microcontroller world's equivalent of printing "Hello, World" — it's small enough to fully understand, but it proves every part of your toolchain and hardware setup is working end to end: the chip is programmed correctly, the oscillator is running, and your output pin is wired correctly.
The circuit is simple: connect an LED's longer leg (the anode) through a current-limiting resistor — typically a few hundred ohms — to a GPIO pin, and its shorter leg (the cathode) to ground. When the pin outputs a high voltage, current flows through the resistor and LED to ground, and the LED lights; when the pin outputs low, no current flows and the LED goes dark.
In software, the whole program is just three steps repeated forever: turn the pin on, wait, turn the pin off, wait. The "wait" is usually a simple software delay — a loop that does nothing useful except take a predictable amount of time — though later lessons on timers show a more precise way to time delays.
void main(void) {
TRISB0 = 0; // RB0 as output
while(1) {
LATB0 = 1; // LED on
__delay_ms(500); // wait half a second
LATB0 = 0; // LED off
__delay_ms(500); // wait half a second
}
}