0
\$\begingroup\$

Can some pins of the same port of AVR MCU's be declared as inputs and some as outputs?

If yes, then I am not able to understand how this works since we have to compare the pins of the port and also assign the values to output pins. It would be very nice if you provide even a simple program for this in C.

\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

Yes.

The DDRx register sets the direction of individual pins. A bit set to 0 configures the pin as input, and set as a 1 configures it as an output.

The PINx register contains the values read from any pins set to input.

The PORTx register is written to for setting the state of any pins set to output.

DDRB = 0x01; // Set pin 0 as output, all others as input on port B
if (PINB & 0x02) { // Check state of pin 1 on port B
    PORTB |= 0x01; // Set pin 0 on
} else {
    PORTB &= 0xFE; // Turn pin 0 off
}

Note the use of bitwise operators there to modify the existing value in the PORTB register, rather than writing a whole value. That allows you to set or clear an individual bit in the register.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.