Embedded Electronics Blog

ATMEL AVR Tips – Input Output Ports Code Snippets

2015-08-12-AVR_Tips_Input_output

In the previous Blog Post ( How to access Input / Output Ports ?) we learned how to use DDRx, PINx, and PORTx registers to access GPIOs.

In this post you will find some ready to use AVR Input Output Ports (GPIO) settings (c code snippets) for AVR microcontrollers. This snippets will help you to: set or reset pins, toggle bit, toggle pin, read from pin, write to pin, enable pullup, make pin tristate input, and so on. These can help you learn and understand GPIOs registers better. These port settings are applicable for any 8 bit AVR, such as ATmega8, ATmega16, ATmega32, ATmega2560, ATtiny series, etc.

GPIO settings:

For various Input Output possibilities.

  Description Code
1 To make all pins of GPIO port as high impedance (tristated) inputs. DDRx  = 0b00000000;
PORTx = 0b00000000;
2 To make all pins of GPIO port as pullup inputs. This enables internal weak pullup on the port pins thereby setting a pin to logic 1. DDRx  = 0b00000000;
PORTx = 0b11111111;
3 To make alternate pins of GPIO as tristate inputs and outputs, starting with pin 0 as tristated input, pin 1 as output and so on … with default logic value on the output pins is logic 0. DDRx  = 0b10101010;
PORTx = 0b00000000;
4 To make alternate pins of GPIO as pullup inputs and outputs, starting with pin 0 as pullup input, pin 1 as output and so on … with default logic value on the output pins is logic 0. DDRx  = 0b10101010;
PORTx = 0b01010101;
5 To make lower nibble of GPIO port as tristated input and higher nibble as output, with default output value of logic 0. DDRx  = 0b11110000;
PORTx = 0b00000000;
6 To make lower nibble of GPIO port as pullup input and higher nibble as output, with default output value of logic 0. DDRx  = 0b11110000;
PORTx = 0b00001111;
Note :
1) Replace x by PORT name. Such as PORTA, PORTB, etc.

 

Modify GPIO output values (Assuming DDR register is correctly set) :

Description Code
1 Set Bit 0 of GPIO port x to 0 without disturbing other  bits PORTx = PORTx & 0b11111110;
 2 Set Bit n of GPIO port x to 0 without disturbing other bits PORTx = PORTx & (~(1<<n));
 3 Set Bit 0 of GPIO port x to 1 without disturbing other bits PORTx = PORTx | 0b00000001;
 4 Set Bit n of GPIO port x to 1 without disturbing other bits PORTx = PORTx | (1<<n);
 5 Toggle Bit 0 of GPIO port x without disturbing other bits PORTx = PORTx ^ 1;
(This is an indirect method and will result in multiple assembly instructions.)
Or
PINx = 0b00000001;
(This is a direct method and will result in a single instruction.)
 6 Toggle Bit n of GPIO port x without disturbing other bits PORTx = PORTx ^ (1<<n);
Or
PINx = (1<<n);
Notes :
1) Replace ‘x’ by PORT name. Such as PORTA, PORTB, etc.
2) ‘n’ denotes the bit number of desired GPIO pin.

Do you want any more code snippets relating to GPIOs? Leave us a comment below, or write to us.

 

Exit mobile version