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
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.
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.
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.
DDRB - The Port B Data Direction Register. Bit.
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
is 0000 0001
1 << 2
after left shift gives 0000 0100
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With