px-lib  0.9.2
Cross-platform embedded library and documentation for 8/16/32-bit microcontrollers

How to configure and use general purpose (digital) I/O pins.

File(s):

The LED shines while the push button is being pressed.

Compact C techniques are used to manipulate individual bits of a Peripheral Control Register. It is good programming practice to encapsulate these often used and error prone pieces of code in macros, as has been demonstrated in flashing_led : Microchip AVR Flashing LED example.

The following piece of code:

PORTB = PORTB | 0x01; // Set bit 0 of PORTB register to enable LED
PORTB = PORTB & 0xfe; // Clear bit 0 of PORTB to disable LED

can be compacted to:

PORTB |= (1<<0); // Set bit 0 of PORTB register to enable LED
PORTB &= ~(1<<0); // Clear bit 0 of PORTB to disable LED

and better yet, be replaced with macros:

// General purpose bit manipulation macros
#define BIT_SET_HI(var, bit) var |= (1<<bit)
#define BIT_SET_LO(var, bit) var &= ~(1<<bit)
// Define LED GPIO pin
#define GPIO_LED_REG_PORT PORTB
#define GPIO_LED_BIT 0
// Define macros to turn LED on and off
#define LED_ON() BIT_SET_HI(GPIO_LED_REG_PORT, GPIO_LED_BIT)
#define LED_OFF() BIT_SET_LO(GPIO_LED_REG_PORT, GPIO_LED_BIT)
void example_fn(void)
{
LED_ON(); // Enable LED
LED_OFF(); // Disable LED
}

or best yet, use px_gpio.h : Microchip AVR GPIO driver. Here is an example:

#include "px_gpio.h"
// LED is on PORT B, pin 0, configured as an output, initally off
#define PX_GPIO_LED PX_GPIO(B, 0, PX_GPIO_DIR_OUT, PX_GPIO_INIT_LO)
// Push Button is on PORT D, pin 7, configured as an input, pull-up enabled
#define PX_GPIO_PB PX_GPIO(D, 7, PX_GPIO_DIR_IN, PX_GPIO_INIT_PULLUP)
int main(void)
{
// Initialise pins
PX_GPIO_PIN_INIT(PX_GPIO_LED);
PX_GPIO_PIN_INIT(PX_GPIO_PB);
// Repeat forever
for(;;)
{
// Is button being pressed?
if(PX_GPIO_PIN_IS_LO(PX_GPIO_PB))
{
// Enable LED
PX_GPIO_PIN_SET_HI(PX_GPIO_LED);
}
else
{
// Disable LED
PX_GPIO_PIN_SET_LO(PX_GPIO_LED);
}
}
}

Assuming Atmel Studio 7 is installed in it's default location, The peripheral registers and bit names are defined in:

C:\Program Files (x86)\Atmel\Studio\7.0\toolchain\avr8\avr8-gnu-toolchain\avr\include\avr\iom328p.h