Focused on Your Needs
2. Write a Program to Turn on a LED
This tutorial shows how to write a program to turn on a LED when a button is pressed down.
Assuming the LED is connected to PD4 through a 330Ω resistor, and the button is connected to PD5 on an ATmega 328P microcontroller.
The LED has to be connected in series with a 330Ω resistor in order to prevent it from burning out.
One side of the button is connected to 5V, and another side is connected to PD5. when the button is pressed, PD5 will receive a 5V pulse.
There are standard libraries contain specific definitions for AVR microcontrollers. <avr/io.h>, which is one of the standard libraries, has to be added in the beginning of the code in order to include the I/O definitions.
Example 1: add a standard library
#include <avr/io.h>
A main function has to be created to process the code.
Example 2: write the main function
int main(void)
{
}
The input and output pins will be configured in the main function.
Example 3: configure the input and output
DDRD |= 1 << 4; //Set PIN4 in PORTD as an output
PORTD &= ~(1 << 4); //Set PIN4 in PORTD to LOW
DDRD &= ~(1 << 5); //Set PIN5 in PORTD as an output
PORTD &= ~(1 << 5); //Set PIN5 in PORTD to tri state
When PIN5 is at tri state, the pin needs to connect to a pull-down resistor.
A while loop is then added to allow the microcontroller to run based on the condition of the while loop. The microcontroller needs to continuously check if the button at PD5 is pressed, so the condition of the while loop is 1 which always gives a true condition so that the microcontroller is checking the code inside the while loop over and over. Inside the while loop, an if-else statement is written to tell the microcontroller to turn on the LED at PD4 when the button at PD5 is pressed. The full code would be shown below.
Example 4: the full code
#include <avr/io.h>
int main(void)
{
DDRD |= 1 << 4; //Set PIN4 in PORTD as an output
PORTD &= ~(1 << 4); //Set PIN4 in PORTD to LOW
DDRD &= ~(1 << 5); //Set PIN5 in PORTD as an output
PORTD &= ~(1 << 5); //Set PIN5 in PORTD to tri state
while (1)
{
if (bit_is_set(PIND,5))
PORTD |= 1 << 4;
else
PORTD &= ~(1 << 4);
}
}