PORTx
If DDRx sets the direction, PORTx sets value to the corresponding pin. DDRx can set a bit to be either input or output, PORTx changes its functionality based on it. Let us consider both cases.
When pins are set as Output
Suppose all pins are set to be output. i.e. DDRx = 0xFF. Now, writing 1 to a bit in PORTx will make output high (normally +5 Volts) for that particular pin; writing 0 makes output low and gives low (0 Volts) in that particular pin.
When pins are set as Input
Suppose a particular bit in DDRx is set as Input (0), then there are two possibilities. If corresponding PORTx bit is set to 1, then an internal pull-up resistor is enabled. This means even if we do not connect this pin to anything it still reads as 1. However, this can read as 0 by externally connecting it to ground and pulling it down.
An interesting state happens if PORTx is set to 0 and pins are set as Input. In this case, pin enters into a tri-state mode and internal pull-up resistor is disabled. This makes the pin enter into a state of high impedance. Even if the pin is not connected, it catches noise from surrounding objects and read result from this pin is unpredictable. It is always a good practice enable the internal pull-up resistor while reading. This tri-state is used for receiving analog inputs, especially when using internal Analog to Digital converter.
PINx
The functionality of a PINx register is straightforward; it reads data from the Port Pin. If DDRx is set to Input (0) for a particular bit, then we can read data from PINx. However if DDRx is set to Output (1), then reading PINx register gives the same data which has been output on that particular Pin.
Some newer AVR’s have an additional feature where it can write to PINx register to toggle the value of PORTx, irrespective of Data Direction Register.
We can summarize register functionalities in a simple table format.
DDRx.n | PORTx.n | Status |
1 | 1 | Output High, +5 Volts |
1 | 0 | Output Low, 0 Volts |
0 | 1 | Internal Pull up enabled |
0 | 0 | Tri-state with High Impedence |
x denotes port number, n denotes pin number
These concepts start being more clear once we get into practical applications.
Do you have anything to say?
Visit the Forum to discuss, learn and share anything related to robotics and electronics !!