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.
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);
_delay_ms(500);
PORTB &= ~(1<<PB0);
_delay_ms(500);
}
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.