0
0
Embedded Cprogramming~5 mins

Configuring pin as input or output in Embedded C

Choose your learning style9 modes available
Introduction
We set a pin as input or output to control if it reads signals or sends signals in a circuit.
When you want to read a button press (input).
When you want to turn on an LED (output).
When you connect sensors that send data to the microcontroller (input).
When you want to control motors or buzzers (output).
When you need to switch between reading and sending signals on the same pin.
Syntax
Embedded C
DDRx |= (1 << PINx);   // Set pin as output
DDRx &= ~(1 << PINx);  // Set pin as input
DDRx is the Data Direction Register for port x (e.g., DDRB for port B).
PINx is the pin number (0 to 7 usually) on the port.
Examples
This sets pin 3 on port B to output mode.
Embedded C
DDRB |= (1 << 3);  // Set pin 3 of port B as output
This sets pin 2 on port C to input mode.
Embedded C
DDRC &= ~(1 << 2); // Set pin 2 of port C as input
Pin 0 of port D is output, pin 1 is input.
Embedded C
DDRD |= (1 << 0);  // Set pin 0 of port D as output
DDRD &= ~(1 << 1); // Set pin 1 of port D as input
Sample Program
This program sets pin 5 of port B as output and pin 4 as input. The microcontroller can now send signals on pin 5 and read signals on pin 4.
Embedded C
#include <avr/io.h>

int main(void) {
    // Set pin 5 of port B as output
    DDRB |= (1 << 5);

    // Set pin 4 of port B as input
    DDRB &= ~(1 << 4);

    while (1) {
        // Main loop does nothing
    }
    return 0;
}
OutputSuccess
Important Notes
Remember to enable pull-up resistors if you use input pins and want a default HIGH signal.
Changing pin direction while the program runs can be useful for some applications.
Always check your microcontroller datasheet for exact register names and pin numbers.
Summary
Pins can be set as input or output by changing bits in the Data Direction Register (DDR).
Setting a bit to 1 makes the pin an output; setting it to 0 makes it an input.
This lets the microcontroller know if it should read or send signals on that pin.