Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - AVR - Simple PORTB, DDRB, PINB explanation

Tags:

c

avr

atmega

I am working on school project and need to learn the basics of C with a AVR atmega controller.

I don't understand how everything is set up. For example PORTB, PORTD, DDRB; DDRD, PINB, PIND and stuff like that. And I don't know how everything works with if statements, while loops, etc.

Can someone give me a short explanation please?

I have a few code lines...

DDRB = 0b00000011; // I know that here DDRB is set to input/output

And an if statement:

if (PINB & (1 << PINB0)){
    A = true;
}

Can someone explain me how this 'if statement' works? Why PINB & (1<< PINB0))?

Thanks

like image 729
Mike_NotGuilty Avatar asked Jan 08 '14 11:01

Mike_NotGuilty


People also ask

What is Ddrb in AVR?

This register is used to configure the PORT pins as Input or Output. Writing 1's to DDRx will make the corresponding PORTx pins as output. Similarly writing 0's to DDRx will make the corresponding PORTx pins as Input. DDRB = 0xff; // Configure PORTB as Output.

What is Ddrb and Portb?

DDR stands for “Data Direction Register” and 'x' indicates port alphabet. As the name suggests, this register is used to set the direction of Port pins to be either input or output. For input, set 0 and for output, set 1. Let us consider PortB, as shown in the figure.

What is Portb in AVR?

Ports in the AVR are gates from the central processing unit to internal and external hard- and software components. The CPU communicates with these components, reads from them or writes to them, e.g. to the timers or the parallel ports.

What is the meaning of Ddrb?

DDRB - The Port B Data Direction Register. Bit.


1 Answers

Do you means what is if-condition PINB & (1<< PINB0))?

It checks whether PINB0 + 1 number bit( from rhs) is ON (1) in PINB or OFF (0).

For example. (a & (1 << 2)) checks whether 3rd bit is ON in a or OFF. In the expression two operators are used << bitwise left shift and & bitwise and below I have explained for one byte example:

  1. 1 is 0000 0001
  2. 1 << 2 after left shift gives 0000 0100
  3. a bitwise and with 0000 0100 gives either all zeros 0000 0000 or 0000 0100

    3a. If all zeros then if condition is false (when third bit in a is zero).
    3b. If result of bitwise and is 0000 0100 then if condition evaluates as true (when third bit in a is one).

like image 156
Grijesh Chauhan Avatar answered Sep 20 '22 15:09

Grijesh Chauhan