Digital IO Example

Now that we have covered all of the theory lets take a look at an example. This first example program is incredibly simple and simply turns the built in LED of the Xplained board  whenever the button is pressed. Lets build it up in steps.

Turning the LED On

Opening a new file generates the default main file as shown below.

#include <avr/io.h>

int main(void)
{    
    while (1) 
    {
    }
}

From the datasheet for the Xplained board we can quickly find that the user LED is connected to PB5. This is pin 5 of port B. Lets set that to an output using the following code:

DDRB |= (1<<DDB5);

We can now insert this into our main.c file.

#include <avr/io.h>

int main(void)
{
    // Set PortB pin 5 as an output.
    DDRB |= (1<<DDB5);
    
    while (1)
    {
    }
}

Next let set pin 5 high using the following code:

        // Set Pin 5 High
        PORTB |= (1<<PORTB5);

Inserting this into our code gives
#include <avr/io.h>

int main(void)
{
    // Set PortB pin 5 as an output.
    DDRB |= (1<<DDB5);
    
    while (1)
    {
       PORTB |= (1<<PORTB5);
    }
}

We now have a functioning piece of code that we can upload to the board. Upon uploading the user LED on the board will turn on. Next lets look at adding some input processing to turn on the LED when the user presses the button.

Adding Button Input

dfgh