Raspberry Pi #
How to blink an LED using C on a Raspberry Pi.
Requirements #
- Raspberry Pi (with Raspbian OS installed)
- Breadboard
- LED
- 220-ohm resistor
- Jumper wires
- GPIO pin reference
Setting Up Your Raspberry Pi #
Connect your Raspberry Pi to a monitor, keyboard, and mouse. Power it on. If the screen resolution is low and everything appears enlarged, restart the Pi as the monitor may not have been detected correctly.
Hardware Setup #
Ideally you should turn off your Raspberry Pi before connecting the components to prevent damage, but since we are only connecting an LED in this case it is safe to keep it powered on.
Using the breadboard:
- Connect the long leg (anode) of the LED to a GPIO pin (e.g., Wiring Pi Pin 15) using a jumper wire.
- Connect the short leg (cathode) of the LED to one end of the resistor.
- Connect the other end of the resistor to a GND (ground) pin on the Raspberry Pi.
Use the GPIO pin reference chart linked above for accurate connections.
Writing the Blink Program #
Open Geany on your Raspberry Pi. Create a new file and save it with a .c extension, for example, blink_led.c. It’s important to use the .c extension so that Geany recognizes it as a C file.
Enter the following code:
#include <wiringPi.h>
#include <stdio.h>
#define LED_PIN 15 // WiringPi pin 15 is GPIO14.
int main(void) {
if (wiringPiSetup() == -1) { // Initialize wiringPi.
printf("Setup wiringPi failed!");
return 1;
}
pinMode(LED_PIN, OUTPUT); // Set pin mode to output.
while(1) {
digitalWrite(LED_PIN, HIGH); // Turn on LED.
delay(1000); // Wait for a second.
digitalWrite(LED_PIN, LOW); // Turn off LED.
delay(1000); // Wait for a second.
}
return 0;
}
Save the file.
Compiling and Running Your Program #
To compile your program, open a terminal in the directory containing blink_led.c and run:
gcc -o blink_led blink_led.c -lwiringPi
This creates an executable named blink_led. Run your program with:
sudo ./blink_led
Your LED should now blink on and off every second. To stop the program, press CTRL + C.
Geany may already be set up for this step and you will be able to just hit build and run inside the IDE.