ATmega328p LED Blink Programming Tutorial

 In this tutorial it is shown how to make a LED blink with ATmega328p microcontroller. The circuit schematic and LED blink program code are provided. A tutorial link that teaches how to upload the code into the microcontroller is also provided.

LED blink Circuit Schematic

The connection setup for ATmega328p for LED blink is shown in circuit diagram below.

ATmega328p LED blink circuit diagram
 In the above circuit diagram, the power supply is 5V. The reset pin 1 or the PC6 pin is pulled up to 5V using the resistor R4. Also the same reset pin is connected to a momentary switch to ground. When the switch is pressed the microcontroller is reset. An external 16MHz crystal is connected to the microcontroller as shown in the circuit diagram. The external crystal is actually not required because the ATmega328p has internal clock which can be run at different frequency, usually 8MHz. So the external crystal oscillator connection is optional. The LED D1 which is turned on and off is connected to the pin 14 which is the Port B0 pin or PB0 via the 270Ohm resistor R2.

For reference purpose the ATmega328p pin diagram is shown below.


The C program code to blink the LED is below.

#include <avr/io.h>
#include <util/delay.h>

int main()
   DDRB |= (1<<PB0);

   while (1){
		PORTB |= (1<<PB0);
		PORTB &= ~(1<<PB0);
   return 0;

In the above program code, two libraries are included which is the io.h and delay.h. The io.h has definition for microcontroller port numbers and other input/output function declaration. The delay.h is used here so that we can use the _delay_ms() function in the main code section. In the main() function we first set the PD2 pin to which is connected to the LED as an output pin. Then in the while() function we continuously set the PD2 pin high first, then a 500ms delay with _delay_ms() function, set the PD2 low and again insert 500ms delay. When we set PD2 high and low with delay we get LED blink.

To write the above program and upload to the ATega328p microcontroller you can use ATMEL studio IDE(Integrated Development Environment) software that is widely used to program these AVR microcontrolllers. The ATMEL Studio. ATMEL studio can be downloaded for free just using google search. The How to Program ATmega328p using ATMEL Studio & AVR ISP MKII tutorial shows how to write program in ATMEL studio and upload it to ATmega328p.

So in this way we can write program to blink an LED with ATmega328p microcontroller. The blinking of LED is actually just sending square waves to the port pin. For generating square wave see the tutorials ATmega328P Fast PWM mode Programming Examples, Programming ATmega328p in CTC mode and Phase Correct PWM with ATmega328P.

Another ATmega328p programming tutorial that might want to see is how to program ATmega328P UART.

Post a Comment

Previous Post Next Post