0
0
Embedded Cprogramming~5 mins

Direction register vs data register in Embedded C

Choose your learning style9 modes available
Introduction

Direction registers tell the microcontroller if a pin is an input or output. Data registers hold the actual values sent to or read from those pins.

Setting a pin to output so you can turn on an LED.
Reading a button press by setting a pin as input.
Controlling motors by sending signals through output pins.
Checking sensor values connected to input pins.
Syntax
Embedded C
/* Set pin direction */
DIR_REG = 0x01;  // Set pin 0 as output, others as input

/* Write data to pin */
DATA_REG = 0x01; // Set pin 0 high

/* Read data from pin */
input_value = DATA_REG & 0x01; // Read pin 0 value

Direction register bits: 1 means output, 0 means input.

Data register bits: writing sets output level; reading gets input level.

Examples
All pins become outputs. Data register sets alternating high and low signals.
Embedded C
DIR_REG = 0xFF;  // All pins set as output
DATA_REG = 0xAA; // Output pattern 10101010
All pins are inputs. Reading data register gets current pin states.
Embedded C
DIR_REG = 0x00;  // All pins set as input
input_val = DATA_REG; // Read all pins
Use bitwise OR to set pin direction and AND with NOT to clear output bit.
Embedded C
DIR_REG |= 0x04;  // Set pin 2 as output without changing others
DATA_REG &= ~0x04; // Set pin 2 low
Sample Program

This program shows how to set pin 0 as output and turn it on, then switch to input and read its value.

Embedded C
#include <stdint.h>
#include <stdio.h>

// Simulated registers
uint8_t DIR_REG = 0x00;  // Direction register
uint8_t DATA_REG = 0x00; // Data register

int main() {
    // Set pin 0 as output
    DIR_REG = 0x01;

    // Turn pin 0 ON
    DATA_REG = 0x01;

    // Print direction and data register values
    printf("DIR_REG = 0x%02X\n", DIR_REG);
    printf("DATA_REG = 0x%02X\n", DATA_REG);

    // Now set pin 0 as input
    DIR_REG = 0x00;

    // Simulate reading pin 0 as HIGH
    DATA_REG = 0x01;

    // Read pin 0 value
    uint8_t pin0_value = DATA_REG & 0x01;
    printf("Pin 0 input value = %d\n", pin0_value);

    return 0;
}
OutputSuccess
Important Notes

Always set the direction register before writing to the data register to avoid unexpected behavior.

Reading the data register on an input pin gives the current voltage level on that pin.

Summary

Direction register controls if a pin is input or output.

Data register holds the value sent to or read from the pin.

Use bitwise operations to change specific pins without affecting others.