Hello World!
blog for everything
EntriesAbout Me

AVR I/O Registers

By bshabanov
Published in Code
August 14, 2020
1 min read

There are many great AVR tutorials for beginners, so I am not going to make another one. Instead, this entry will be more like a reference than a tutorial. Unlike Arduino, when you want to set some pin of the microcontroller in the LOW or HIGH state in AVR, we use REGISTERS instead of digitalWrite/digitalRead function. These registers are:

  • DDRx – Data Direction Register for port x
  • PINx – Read from Port x
  • PORTx – Write to Port x

0x04
0x04


#Data Direction Register

The DDR register is most likely the first register that you configure since the DDR register determines if pins on a specific port are inputs or outputs.
In other words, you can say DDR is the equivalent of “pinMode”. The DDR register is 8 bits long and each bit corresponds to a pin on that I/O port. Each bit can be set as 1 (output) or 0 (input). For example: if we want to set whole port B as output we would use the following code:

DDRB = 0xFF;

Setting only one pin:

// Set PB4 as output
DDRB |= (1 << PB4)

// The above is same as 
pinMode(PB4, OUTPUT)

// Set PB4 as input
DDRB &= ~(1 << PB4)

// The above is same as 
pinMode(PB4, INPUT)

#PINx Register

The PIN register follows the same concept as DRR, but instead of writing to register, we read from it, and the returned value is the state of the pin. Example:

// Do something if PB4 is HIGH 
if ( PINB & (1 << PB4)) {
    ...
}

// The above is same as 
if (digitalRead(PB4) == HIGH) {
    ...
}

// Do something if PB4 is LOW 
if ( !(PINB & (1 << PB4)) ) {
    ...
}

// The above is same as 
if (digitalRead(PB4) == LOW) {
    ...
} 

##PORTx Register

The last register allows us to set the state of a pin.

Example:

// Set PB4 to HIGH
PORTB |= (1 << PB4); 

// The above is same as
digitalWrite(PB4, HIGHT);

// Set PB4 to LOW
PORTB &= ~(1 << PB4); 

// The above is same as
digitalWrite(PB4, LOW);

#Example for DDR, PIN, and PORT

0x04
ATtiny85 pinout

#include <avr/io.h>
#include <util/delay.h>

int main(void) {
    /**
     * Configure PORT B bit 4 to output and all other to an input
     * PB4 will be INPUT
     * PB3 will be OUTPUT
     */
    DDRB = 0b00010000;

    // Infinity loop
    while (1) {
        // Wait until the switch goes PB4 HIGH
        if(PINB & (1 << PB4)) {         
            // Toggle the LED found on PIND0
            PORTB = PORTB ^ (1 << PB3);

            // Force a delay to prevent de-bounce!
            _delay_ms(100);

            // Wait until the button is released
            while(PINB & (1 << PB4));
        }
    }
}


Tags

#code#dev#bitwise
Previous Article
Creating My First Blog

bshabanov

Discover the world

Categories

Code
Misc
Electronics

Related Posts

Make ESP8266 Deauther
September 14, 2020
1 min
0x48 0x65 0x6c 0x6c 0x6f 0x20 0x57 0x6f 0x72 0x6c 0x64 0x21
2021 and still discovering the world