Found something unclear in making codevisionavr code

231 views Asked by At

I got a code example which says like this:

DDRA = (1<<DDA7) |  (1<<DDA6) |  (1<<DDA5) |  (1<<DDA4) |  
   (1<<DDA3) |  (1<<DDA2) |  (1<<DDA1) |  (1<<DDA0);

What does that code means? What is the function of DDA? And is "<<” a bitwise ?

1

There are 1 answers

0
TomServo On

The constants DDA0 etc. refer to bit positions in the DDRA register. This register determines which of the eight pins on port A are input and which are outputs. A 1 in a bit position means output pin, and a 0 (default) means it's an input pin.

(1 << DDA0)

with DDA0 defined as zero means, "put a 1 into this register after bitwise-shifting it zero positions to the left." So yes, bitwise operators. In other words, make the least significant bit a 1. The others shift a one various positions to the left, making them 2,4,8, etc.

The net result of this statement is that all bit positions are ORed together, resulting in a value of 11111111 or 0xFF, which means that the entire PORTA port is set to be output.

It's worth noting that this entire statement could be simplified by simply using:

DDRA = 0xFF;

Even though this is shorter, there is no code size penalty because the compiler collapses the long expression on the right to 0xFF anyway. You'll see both styles of programming ports as you explore more.

From the ATmega documentation:

Configuring the Pin Each port pin consists of three register bits: DDxn, PORTxn, and PINxn. As shown in the Register Description, the DDxn bits are accessed at the DDRx I/O address, the PORTxn bits at the PORTx I/O address, and the PINxn bits at the PINx I/O address.

The DDxn bit in the DDRx Register selects the direction of this pin. If DDxn is written to '1', Pxn is configured as an output pin. If DDxn is written to '0', Pxn is configured as an input pin.

If PORTxn is written to '1' when the pin is configured as an input pin, the pull-up resistor is activated. To switch the pull-up resistor off, PORTxn has to be written to '0' or the pin has to be configured as an output pin. The port pins are tri-stated when reset condition becomes active, even if no clocks are running.

If PORTxn is written to '1' when the pin is configured as an output pin, the port pin is driven high. If PORTxn is written logic zero when the pin is configured as an output pin, the port pin is driven low.

Toggling the Pin Writing a '1' to PINxn toggles the value of PORTxn, independent on the value of DDRxn. The SBI instruction can be used to toggle one single bit in a port.