10. I/O Port
If the pin is not configured as an alternate function, the default is the general-purpose I/O pin state. When used as a general-purpose digital I/O, all I/O ports have a true “read-modify-write” function, which supports bit manipulation instructions such as SETB or CLR to independently change the direction of certain pins or port levels.
10.2 GPIO Register
All registers and bits in this section are expressed in a common format: the lowercase “n” represents the serial number of the port (n = 0, 1, 2, 3), and the lowercase “x” represents the serial number of the bit (x = 0, 1, 2, 3, 4, 5, 6, 7).
Table 10.2.1 GPIO Register List
| Name | Address | Description | Reset value |
|---|---|---|---|
| P0 | 80h | P0 port input and output register | FFh |
| P0_DIR | C4h | P0 port direction control register | 00h |
| P0_PU | C5h | Port 0 pull-up enable register | 00h/FFh |
| P1 | 90h | P1 port input and output register | FFh |
| P1_IE | B9h | P1 port input enable register | FFh |
| P1_DIR | BAh | P1 port direction control register | 00h |
| P1_PU | BBh | P1 port pull-up enable register | FFh |
| P2 | A0h | P2 port input and output register | FFh |
| P2_DIR | BCh | P2 port direction control register | 00h |
| P2_PU | BDh | P2 port pull-up enable register | FFh |
| P3 | B0h | P3 port input and output register | FFh |
| P3_DIR | BEh | P3 port direction control register | 00h |
| P3_PU | BFh | P3 port pull-up enable register | FFh |
| P4_OUT | C0h | P4 port output register | 00h |
| P4_IN | C1h | P4 port input register (read only) | FFh |
| P4_DIR | C2h | P4 port direction control register | 00h |
| P4_PU | C3h | P4 port pull-up enable register | FFh |
| P4_CFG | C7h | P4 port configuration register | 00h |
| P5_IN | C7h | P5 port input register (read only) | 00h |
| PIN_FUNC | CEh | Pin Function Select Register | 00h |
| PORT_CFG | C6h | Port Configuration Register | 0Fh |
| XBUS_SPEED | FDh | Bus speed configuration register | FFh |
| XBUS_AUX | A2h | Bus auxiliary setting register | 00h |
Port configuration register (PORT_CFG):
| Bit | Name | Access | Description | Reset value |
|---|---|---|---|---|
| [7:4] | bPn_DRV | RW | Pn port output drive capability selection, this bit is 0 to select the drive current 5mA level. This bit is 1 for P0 / P2 / P3 to select the drive current 20mA level, and for P1 to select the drive current 10mA level | 0000b |
| [3:0] | bPn_OC | RW | Pn port open-drain output enable, this bit is 0 to set the port as push-pull output. This bit is 1 to set the port to be open-drain output | 1111b |
Pn port input and output register (Pn):
| Bit | Name | Access | Description | Reset value |
|---|---|---|---|---|
| [7:0] | Pn.0 |
Pn port direction control register (Pn_DIR):
| Bit | Name | Access | Description | Reset value |
|---|---|---|---|---|
| [7:0] | Pn_DIR | RW | Pn.x pin direction setting | 00h |
P0 port pull-up enable register (P0_PU) and Pn port pull-up enable register (Pn_PU), where n = 1/2/3:
The configuration of the Pn port is implemented by the combination of the bit bPn_OC in the PORT_CFG, the port direction control register Pn_DIR, and the port pull-up enable register Pn_PU, as follows.
Table 10.2.2 Port configuration register combinations
| bPn_OC | Pn_DIR | Pn_PU | Description |
|---|---|---|---|
| 0 | 0 | 0 | High-impedance input mode, no pull-up resistor on pin |
| 0 | 0 | 1 | Pull-up input mode, pins have pull-up resistors |
| 0 | 1 | x | Push-pull output mode, with symmetrical driving ability, can output or absorb large current |
| 1 | 0 | 0 | High-impedance input weak quasi-bidirectional mode, open-drain output, no pull-up resistor on pin |
| 1 | 1 | 0 | High-impedance input quasi-bidirectional mode, open-drain output, no pull-up resistor on the pin, when the output changes from low to high, it automatically drives high for 2 clock cycles to speed up the conversion |
| 1 | 0 | 1 | Weak quasi-bidirectional mode (imitation of 8051), open-drain output, support input, pin with pull-up resistor |
| 1 | 1 | 1 | Quasi-bidirectional mode (standard 8051), open-drain output, support input, pins have pull-up resistors, when the output changes from low to high, it automatically drives high for 2 clock cycles to speed up the conversion |
P3 support pure input or push-pull output and quasi-bidirectional modes. Port P4 supports pure input or push-pull output and other modes. Each pin has a freely controllable internal pull-up resistor connected to VDD33, and a protection diode connected to GND.
Figure 10.2.1 is the equivalent schematic of the P1.x pin of the P1 port. After removing P1_IE and AIN and ADC_CHANN, it can be applied to the P0, P2, and P3 ports.
Figure 10.2.1 I/O pin equivalent schematic

P1 port input enable register (P1_IE):
| Bit | Name | Access | Description | Reset value |
|---|---|---|---|---|
| [7:0] | P1_IE | RW | P1.x pin input enable, if this bit is 0, the pin is used for ADC analog input, digital input is disabled. If this bit is 1, the digital input is enabled | FFh |
10.3 P4 port
P4 port output register (P4_OUT):
| Bit | Name | Access | Description | Reset value |
|---|---|---|---|---|
| [7:0] | P4_OUT.0 |
P4 port input register (P4_IN):
| Bit | Name | Access | Description | Reset value |
|---|---|---|---|---|
| [7:0] | P4_IN | R0 | P4.x pin status input bit | FFh |
P4 port pull-up enable register (P4_PU):
| Bit | Name | Access | Description | Reset value |
|---|---|---|---|---|
| [7:0] | P4_PU | RW | P4.x pin pull-up resistor is enabled, this bit is 0 to disable pull-up; this bit is 1 to enable pull-up | FFh |
P4 port direction control register (P4_DIR):
| Bit | Name | Access | Description | Reset value |
|---|---|---|---|---|
| [7:0] | P4_DIR | RW | P4.x pin direction setting, this bit is 0 for input; this bit is 1 for output | 00h |
P4 port configuration register (P4_CFG) and P5 port input register (P5_IN):
GPIO interrupt request activation status:
When bIE_IO_EDGE = 0, this bit is 1 to indicate the GPIO input active level, interrupt will be requested, and 0 to indicate the input invalid level.
When bIE_IO_EDGE = 1, this bit is used as an edge interrupt flag. A value of 1 indicates that a valid edge was detected.This bit cannot be cleared by software. It can only be automatically cleared during reset or level interrupt mode or when entering the corresponding interrupt service routine zero
10.4 GPIO Multiplexing and Mapping
Some of the I / O pins of CH559 have alternate functions. After power-on, they are all general-purpose I / O pins. After different function modules are enabled, the corresponding pins are configured as the corresponding function pins of the respective function modules.
Pin function selection register (PIN_FUNC):
| Bit | Name | Access | Description | Reset value |
|---|---|---|---|---|
| 7 | bPWM1_PIN_X | RW | PWM1/PWM2 pin mapping enable bit, if this bit is 0, PWM1/2 uses P2.4/P2.5. If this bit is 1, PWM1/2 uses P4.3/P4.5 | 0 |
| 6 | bTMR3_PIN_X | RW | PWM3/CAP3 pin mapping enable bit. When this bit is 0, PWM3/CAP3 uses P1.2. When this bit is 1, PWM3/CAP3 uses P4.2 | 0 |
| 5 | bT2EX_PIN_X | RW | T2EX/CAP2 pin mapping enable bit. When this bit is 0, T2EX/CAP2 uses P1.1. When this bit is 1, T2EX/CAP2 uses P2.5 | 0 |
| 4 | bUART0_PIN_X | RW | UART0 pin mapping enable bit. When this bit is 0, RXD0/TXD0 uses P3.0/P3.1. When this bit is 1, RXD0/TXD0 uses P0.2/P0.3. | 0 |
| 3 | bXBUS_EN | RW | xBUS external bus function enable bit, this bit is 0 to disable the external bus; this bit is 1 to enable the P0 port as an 8-bit data bus, and P3.6/P3.7 as write/read strobe control during bus access | 0 |
| 2 | bXBUS_CS_OE | RW | xBUS external bus chip select output enable bit. This bit is 0 to disable the output of chip select and can be decoded by external circuits. P3.4 is set as CS0 when this bit is 1 (XCS0 chip select 0, active low), and When ALE is disabled, the bus address A15 is inverted and output to P3.3 (equivalent to chip select 1, active low) | 0 |
| 1 | bXBUS_AH_OE | RW | xBUS External bus high 8-bit address output enable bit, this bit is 0 to disable output. When this bit is 1, during the MOVX_@DPTR instruction access to the external bus, the P2 port output bus address is the upper 8 bits | 0 |
| 0 | bXBUS_AL_OE | RW | The lower 8-bit address output enable bit of the xBUS external bus. When this bit is 0, it is a multiplexed address mode. When accessing the external bus, the lower 8 bits of the address are multiplexed with the data bus as required, and the external circuit is controlled by ALE to latch. If this bit is 1, it is the direct address mode.The lower 8-bit addresses A0 |
A7 are output through P4.0
Figure 10.2.1 I/O pin equivalent schematic
| GPIO | Other functions: in order of priority from left to right |
|---|---|
| P0[0] | AD0, UDTR/bUDTR, P0.0 |
| P0[1] | AD1, URTS/bURTS, P0.1 |
| P0[2] | AD2, RXD_/bRXD_, P0.2 |
| P0[3] | AD3, TXD_/bTXD_, P0.3 |
| P0[4] | AD4, UCTS/bUCTS, P0.4 |
| P0[5] | AD5, UDSR/bUDSR, P0.5 |
| P0[6] | AD6, URI/bURI, P0.6 |
| P0[7] | AD7, UDCD/bUDCD, P0.7 |
| P1[0] | AIN0, T2/bT2, CAP1/bCAP1, P1.0 |
| P1[1] | AIN1, T2EX/bT2EX, CAP2/bCAP2, P1.1 |
| P1[2] | AIN2, PWM3/bPWM3, CAP3/bCAP3, P1.2 |
| P1[3] | AIN3, P1.3 |
| P1[4] | AIN4, SCS/bSCS, P1.4 |
| P1[5] | AIN5, MOSI/bMOSI, P1.5 |
| P1[6] | AIN6, MISO/bMISO, P1.6 |
| P1[7] | AIN7, SCK/bSCK, P1.7 |
| P2[0] | A8, P2.0 |
| P2[1] | MOSI1/bMOSI1, A9, P2.1 |
| P2[2] | MISO1/bMISO1, A10, P2.2 |
| P2[3] | SCK1/bSCK1, A11, P2.3 |
| P2[4] | PWM1/bPWM1, A12, P2.4 |
| P2[5] | TNOW/bTNOW, PWM2/bPWM2, A13, T2EX_/bT2EX_, CAP2_/bCAP2_, P2.5 |
| P2[6] | RXD1/bRXD1, A14, P2.6 |
| P2[7] | TXD1/bTXD1, DA7/bDA7, A15, P2.7 |
| P3[0] | RXD/bRXD, P3.0 |
| P3[1] | TXD/bTXD, P3.1 |
| P3[2] | LED0/bLED0, INT0/bINT0, P3.2 |
| P3[3] | LED1/bLED1, !A15, INT1/bINT1, P3.3 |
| P3[4] | LEDC/bLEDC, XCS0/bXCS0, T0/bT0, P3.4 |
| P3[5] | DA6/bDA6, T1/bT1, P3.5 |
| P3[6] | WR/bWR, P3.6 |
| P3[7] | RD/bRD, P3.7 |
| P4[0] | LED2/bLED2, A0, RXD1_/bRXD1_, P4.0 |
| P4[1] | A1, P4.1 |
| P4[2] | PWM3_/bPWM3_, CAP3_/bCAP3_, A2, P4.2 |
| P4[3] | PWM1_/bPWM1_, A3, P4.3 |
| P4[4] | LED3/bLED3, TNOW_/bTNOW_, TXD1_/bTXD1_, A4, P4.4 |
| P4[5] | PWM2_/bPWM2_, A5, P4.5 |
| P4[6] | XI, SCS_/bSCS_, P4.6 |
| P4[7] | XO, SCK_/bSCK_, P4.7 |
| P5[0] | DM/bDM, P5.0 |
| P5[1] | DP/bDP, P5.1 |
| P5[4] | HM/bHM, ALE, XB, P5.4 |
| P5[5] | HP/bHP, !A15, XA, P5.5 |
| P5[7] | RST/bRST, P5.7 |
The priority order from left to right described in the above table refers to the priority order when multiple functional modules compete to use the GPIO. For example, the P2 port has been set to the upper 8 bits of the output bus address. If only the A8
A11 addresses are actually used, then P2.4/P2.5 can still be used for higher priority PWM1/PWM2 functions, P2.6 It can still be used for RXD1 function, P2.7 can still be used for higher priority TXD1 or DA7 functions, so as to avoid wasting P2.4
Overview
There are not many people who can completely understand the internal structure and various modes of the GPIO (General Purpose Input and Output) of the processor. Recently, a lot of information about this part has been searched on Baidu, and many of the questions are not uniform. . This article will list all the issues involved in IO as much as possible, explain clearly the questions with clear answers, and raise questions for those who still have questions for discussion.
In a nutshell, the functional modes of IO can be roughly divided into three categories: input, output, and input and output.Among them, as the basic input IO, it is relatively simple, and the main knowledge involved is the high-impedance state. As the output IO, compared with the input, the working mode mainly has Open Drain mode and Push-Pull. Mode, this part involves more knowledge points; for input and output IO, the easy to be confused is the difference between quasi-bidirectional and bidirectional ports.
The details of each mode are described in order in this order.
Input IO
The input IO mentioned here refers to only the input and does not have the output function. At this point, the requirement for the input pin is high resistance (high resistance and tristate are the same concept). The types of basic input circuits can be broadly classified into three categories: basic input IO circuits, Schmitt trigger input circuits, and weak pull-up input circuits.
Start with the most basic basic input IO circuit, the circuit shown in Figure 1.

The buffer U1 therein is a tristate buffer having a control input and having high impedance characteristics. In layman’s terms, this buffer is high-impedance externally. It is equivalent to the fact that the physical pin is completely isolated from the internal bus when the control input is not enabled, and the internal circuit is not affected at all. The function of the control input is to issue an operation command to read the Pin state. The process is shown in Figure 2.

One disadvantage of this basic circuit is that jitter occurs when reading the edge of an external signal, as shown in the following figure.

Therefore, the Schmitt trigger input circuit solves the above-mentioned problem of jitter, and the signal after passing through the Schmitt trigger is as shown in FIG.

Another problem with the input circuit is that when the input pin is left floating, is the level detected at the input high or low? When the input signal is not driven, that is, floating, any noise on the input pin changes the level detected at the input, as shown in Figure 5.

To solve this problem, a weak pull-up resistor can be added to the input pin, as shown in Figure 6.

Thus, when the input pin is left floating, it will be pulled high by RP and there will be a certain state on the internal bus.
But this structure has certain problems. The first obvious point is that when the input pin is left floating, it reads 1 and when the input pin is driven high, it reads 1 and only reads when the input pin is driven low. It is 0. That is, the way to read 1 is to "read non-zero".
Another problem is that the circuit is not high-impedance externally, and in some sense is also outputting outward. When the external driving circuit is different, an erroneous detection result may occur. For example, the external driving circuit is a structure as shown in FIG. 7, in which a high level or a low level can be output by K to a different end.

If the circuit shown in Figure 7 is output low, it is connected to an input pin with a weak pull-up resistor. The structure is as follows.

According to Ohm’s law, the level at the test point is
Therefore, the input signal measured by the CPU is high, and the external drive circuit expects the output level to be low. The reason for this error is that the input circuit of this structure is not really high impedance, or the input IO is actually output, and it affects the external input circuit.
The occurrence of this situation also shows that the signal is transmitted in two stages before and after, why the output impedance is small and the input impedance is large. In this example, the output impedance of the peripheral driver circuit is very large, reaching 100Kohm; and the impedance at the input is not large enough, only 10Kohm, so there is a problem. If the input impedance at the input is truly high impedance (infinity), as shown below, there will be no problems.

The input circuit with weak pull-up mentioned above is the case of the quasi-bidirectional port mentioned in the following sections.
Output IO
The two main modes of the IO output circuit are Push-Pull Output and Open Drain Output.
Push-Pull Output
The structure of the push-pull output is controlled by two transistors or MOS tubes with complementary signals. The two tubes are always kept one off and the other is on. As shown in Figure 10.

The biggest feature of the push-pull output is that it can truly output high level and low level, and has driving capability at both levels.
Supplementary note: The so-called driving ability refers to the ability to output current. For driving large loads (ie, the smaller the internal resistance of the load, the larger the load), for example, the IO output is 5V, and the internal resistance of the load is 10 ohms. Therefore, according to Ohm’s law, the current on the load can be normally 0.5A (calculated) The power is 2.5W). Obviously, the general IO cannot have such a large driving capability, that is, there is no way to output such a large current. The result is that the output voltage will be pulled down and will not reach the nominal 5V.
Of course, if only the digital signal is transmitted, the input impedance of the next stage is theoretically high impedance, that is, only the voltage needs to be transmitted, there is basically no current, and there is no power, so that a large driving capability is not required.
For the push-pull output, the current flow when the output is high or low is shown in Figure 11. Therefore, compared with the open-drain output described later, the driving ability at the output high level is much stronger.

However, one disadvantage of the push-pull output is that if the two push-pull output structures are connected together, one output is high, that is, the upper MOS is turned on, and the lower MOS is turned on; while the other output is low, that is, the upper The MOS is closed and the lower MOS is turned on. The current flows directly from the VCC of the first pin through the upper MOS and through the lower MOS of the second pin to GND. The resistance on the entire path is small, and a short circuit may occur, which may cause damage to the port.This is also the reason why the push-pull output cannot achieve "line and".
Open Drain Output
It is often said that the open-drain output is the opposite of the push-pull output. The most common difference between the open-drain output and the push-pull output is that the open-drain output cannot truly output a high level, that is, there is no driving capability at a high level, and it is necessary to use an external The pull-up resistor completes the external drive. The following is an explanation of the internal structure and principle of why there is no driving capability when the open-drain output is high, and further compares the difference with the push-pull output.
First, we need to introduce some open-drain output and open-collector output. The principle and characteristics of these two outputs are basically similar. The difference is that one uses a MOS tube, where "drain" refers to the drain of the MOS tube; the other uses a triode, where the "set" refers to the triode collector. Both of these are actually output modes corresponding to the push-pull output. Since the MOS tube is used more often, the word "open-drain output" is often used instead of the open-drain output and the open-collector output.
The introduction begins with the open collector output, and the schematic circuit junction is shown in Figure 12.

The circuit on the left side of Figure 12 is the most basic circuit for the open-collector (OC) output. When the input is high, the NPN transistor is turned on, the Output is pulled to GND, and the output is low. When the input is low, the NPN transistor Closed, Output is equivalent to an open circuit (output high impedance). Output high impedance at high level (What are the meanings of high resistance, tristate, and floating? High resistance and dangling are not a meaning), there is no driving capability at this time. This is the biggest feature of open drain and open collector output. How to use this feature to complete various functions will be introduced later. Although this circuit completes the function of the open collector output, it will appear that the input is high and the output is low; the input is low and the output is high.
In the circuit on the right side of Figure 12, a triode is used to complete the "inversion". When the input is high, the first transistor is turned on, and the input of the second transistor is pulled to GND, so the second transistor is closed and the output is high impedance; when the input is low, the first The transistor is closed, at which point the input of the second transistor is pulled high by the pull-up resistor, so the second transistor is turned on and the output is pulled to GND. Thus, the input and output of this circuit are in phase.
Next, the circuit for open-drain output is shown, as shown in Figure 13. The principle is basically the same as the open collector output, except that the triode is replaced by MOS.

Then talk about the characteristics of open-drain and open-collector output and their applications. Since the two are similar, if there is no special explanation in the following, open-drain and open-collector output circuits are indicated by open-drain.
The main characteristic of the open-drain output is that the high level has no driving capability, and an external pull-up resistor is required to actually output a high level. The circuit is shown in FIG.
Figure 14
When the MOS transistor is closed, the open-drain output circuit outputs a high level, and when connected to the load, the current flows from the external power supply, flows through the pull-up resistor RPU, flows into the load, and finally enters GND.
An obvious advantage of this feature of the open-drain output is that the level of the output can be easily adjusted because the output level is completely determined by the power supply level to which the pull-up resistor is connected. Therefore, where level shifting is required, it is very suitable to use the open drain output.
Another benefit of this feature of open-drain output is that it can implement the "line and" function. The so-called "line and" means that multiple signal lines are directly connected together, only when all When the signals are all high, the combined bus is high; as long as any one or more signals are low, the bus is low. The push-pull output will not work. If the high level and the low level are connected together, current backflow will occur and the device will be damaged.
Difference between push-pull and open-drain output
Figure 15
Two-way IO
Many processor pins can be configured as bidirectional ports. The requirement for bidirectional ports is to both output the signal and read back the external signal input. To achieve these two points at the same time is somewhat difficult in principle. First, let’s start with the internal structure of the open-drain output IO port of the processor, as shown in Figure 16.

The structure is based on Figure 13, with an FF added before the transistor for the purpose of controlling the timing of the output signal. A more common application is when multiple IOs are used as a bus, each pin on the bus is required to simultaneously output data.
For the open-drain output structure, the output Q terminal of the FF is connected to the drive buffer, so that the read operation is read not by the state of the external pin, but by the state of its own output.
Two-way open drain IO
However, the structure of Fig. 16 is slightly modified. As shown in Fig. 17, the structure is called a bidirectional open drain IO structure. The change was to connect the input driver buffer to the PIN.

When the output of the structure is "1", T1 is turned off, and the pin presents a high resistance to the outside, and there is no problem as an input pin. However, if the structure outputs "0", T1 is turned on, and the pin is short-circuited to the ground, that is, no matter what signal is externally input, all of the U2 read back is low. Therefore, for such a structure, if it is required to be used as an input pin, it is necessary to output "1" to U1 to read the external pin data.
Quasi-bidirectional open drain IO
Quasi-bidirectional ports are also mentioned in many documents. In fact, the quasi-bidirectional port is a pull-up resistor added to the structure of Figure 17, as shown in Figure 18.

This structure has the following differences and differences compared to Figure 17:
When used as an input pin, you must also write "1" to U1 to achieve the purpose of disconnecting T1. So whether you need to write "1" in advance is not the difference between bidirectional IO and quasi-bidirectional IO. Both of them must be written "1" in advance when they are used as input ports.
When the bidirectional port is input as a true high-impedance state, and the quasi-bidirectional IO is used as an input port, the input impedance is not high-resistance, so there may be a problem as shown in Figure 8 of this figure. .
The quasi-bidirectional port reads the input state and defaults to high. That is, the method of judging the external input signal is "not low is high". That is, the structure can only accurately identify the external low level, and cannot distinguish between the dangling and the true high. So as long as the reading is not 0, the external is considered to be 1.
Push-pull output as bidirectional IO
If the output portion of the bidirectional port is a push-pull output structure, then all ports of the upper and lower tubes must be made high impedance as an input.
51 single-chip P0 port
In the discussion of the bidirectional port, the more complicated one is the P0 port of the 51 MCU. Here we discuss in detail the structure and working principle of the P0 port of 51 single-chip microcomputer.
The internal structure of the P0 port is shown in Figure 19.

The internal structure is complex and includes the following devices:
U1: AND gate. One input is connected to the control line and the other input is connected to this address/data signal. Due to the characteristics of the AND gate, when the control line is 1, the AND gate output is consistent with the level of the address/data signal; if the control line is 0, the output is constant. The control signal line then corresponds to the enable signal of the AND gate.
U2: Inverter, the output signal is the inverted signal of the address/data signal.
Both U3 and U6 are tristate buffers with control inputs and high impedance characteristics that act to present a high impedance state for the outside. The level of the external signal can be read into the data bus when the control is enabled.
U4: is the latch, the purpose is to control the time of the pin output signal.
U5: Analog switch that controls whether the input signal to V2 is from the Q non-output of latch U4 or from the output of inverter U2.
V1 and V2 are two MOS tubes, respectively.
After learning about the individual devices, I started to explain how working in each mode works:
When P0 is used for address/data lines:
When P0 is used as the address/data line, it is the address and data multiplexing bus. P0 needs to output the address and needs to read back the data signal.
When P0 needs to output address information, the control signal of U1 is 0, and the analog switch U5 is connected to the output of the U2 inverter. Therefore, when the signal transmitted from the address signal line is 1, the input signal output to V1 is "1" after the control line "1" is phased, and V1 is turned off. After the address signal "1" is inverted, the input to the V2 through the analog switch is "0", and V2 is turned on. Thus, as shown in Fig. 20, the pin outputs "0".

When the signal transmitted from the address signal line is 1, the input signal to V1 is "0" after the control line "1" is phased, and V1 is turned on. After the address signal "0" is inverted, the input to the V2 through the analog switch is "1", and V2 is turned off, so the situation is as shown in Fig. 21, and the pin outputs "1".

Therefore, when outputting as an address line, both MOS transistors V1 and V2 are used, which is a push-pull output.
When P0 outputs the lower 8-bit address information, it will become the data bus. At this time, the CPU operation is the control terminal output 0, the analog switch hits the Q non-terminal of the latch, and "1" is entered into the latch. ". Then Q non-output is 0, V2 is cut off. At the same time, the control line is 0 so that the AND gate output is 0 and V1 is turned off. Since both V1 and V2 are off, the pin is completely high impedance at the moment. As an input port, external data enters the internal bus through U6, as shown in Figure 22. (Equivalent to disconnecting all the two MOS transistors of the push-pull output.) At this time, since it exhibits high resistance, it is a true input pin. This explains why P0 is a true two-wire port.

When P0 is used for normal IO:
When P0 is used as a normal IO and as an output, the control signal is 0, so that V1 is always off. The analog switch is connected to the Q non-output. When used as an output, the input of the latch directly inputs 0 or 1. Q does not input the inverted signal to the input of V2. That is, when "0" is output, the V2 input terminal is "1", V2 is turned on, and the pin output is "0". When the output is "1", the V2 input terminal is "0", V2 is turned off, and the pin output is high impedance. . That is, when P0 operates in the normal IO mode, the output is an open-drain output, and there is no pull-up resistor inside.
When P0 is used as a normal IO and as an input, the control signal is 0, so that V1 is always off. The analog switch is connected to the Q non-output, and the CPU automatically writes 1 to the latch input. The V2 input is 0 and V2 is turned off. As before, as the address/data line, as the input, the two MOS tubes are all disconnected, and the pin is directly connected to the U6, which presents a high resistance to the outside. So it is also the real input pin.
In summary, P0 is true dual port IO no matter which mode it is working on.
P3 port of 51 single chip microcomputer
The internal structure of the other three ports of the 51 MCU is shown in Figure 23. Compared with P0, it is much simpler. There is no MOS tube at the top, and there is no option for address/data signals. As an output, it is an open-drain output with a pull-up resistor. When it is input, there is a pull-up resistor, so the input port is not high-resistance externally. This explains why P1 to P3 can only be quasi-bidirectional ports.
Что означает порт конфигурирования quasi bidirectional mode

IV. ПАРАЛЛЕЛЬНЫЕ ПОРТЫ ВВОДА/ВЫВОДА МК 8XC196KC/КD
Краткий функциональный обзор
Порты ввода/вывода обеспечивают механизм передачи информации между микроконтроллером и внешними устройствами. 8XC196KC/KD имеет пять 8-разрядных портов для приема и передачи данных, представленных в параллельном формате (P0, P1, P2, P3 и P4). Каждый разряд порта имеет внешний вывод PX.Y, где X — номер порта, а Y — номер разряда порта.
Порты ввода/вывода имеют разряды, которые предназначены:
— или только для приема данных (INPUT);
— или только для передачи данных (OUTPUT);
— квазидвунаправленные (Quasy-Bidirectional);
— двунаправленные с открытым стоком;
— или комбинация четырех перечисленных функций.
Почти все разряды параллельных портов выполняют альтернативные функции. Например, один из выводов порта может стать выходом широтно-импульсного модулятора (Pulse Width Modulator, PWM), в то время как другой может использоваться как аналоговый вход (Analog Channel, ACH0-ACH7). Каждый разряд порта имеет функцию по умолчанию. Однако функция вывода может изменяться при выборе альтернативной функции. Например, при выборе альтернативной функции квазидвунаправленный разряд порта становится выводом только для передачи данных. Конкретная функция порта ввода/вывода программируется в соответствующем управляющем регистре специальных функций (Special Funktion Register, SFR).
В любом случае разряд имеет базисный набор характеристик работы, связанных с данной конфигурацией. В таблице 4.1 приведены пять портов ввода/вывода (P0,P1,P2,P3,P4), их альтернативные функции и функции по умолчанию. Пятый столбец таблицы 4.1 указывает регистр специальных функций, который определяет, как функционирует разряд:
— или как вывод параллельного порта;
— или выполняет альтернативную функцию.
Некоторые разряды эксплуатируются и как выводы порта, и выполняют альтернативные функции одновременно (например, порт 0 и аналоговые входы). В этом случае пятый столбец таблицы 4.1 оставлен пустым.
Кроме стандартных портов дополнительные функции ввода/вывода могут обеспечивать модуль быстрого ввода (HSI) и модуль быстрого вывода (HSO).
Функции разрядов параллельных портов
| No разряда порта | Предназначение | Альтернативная функция | Предназначение по умолчанию | Регистр специальных функций |
| P0 | Input | ACH0-ACH7 | Input | — |
| P1.0, P1.1, P1.2 | Quasi-Bidirectional | None | — | — |
| P1.3, P1.4 | Quasi-Bidirectional | PWM1, PWM2 | Output | IOC3 |
| P1.5, P1.6 | Quasi-Bidirectional | BREQ , HLDA | Output | WSR |
| P1.7 | Quasi-Bidirectional | HOLD | Input | WSR |
| P2.0 | Output | TXD | Output | IOC1 |
| P2.1 | Input | RXD | Input or Output | SPCON |
| P2.2 | Input | EXTINT | Input | IOC1 |
| P2.3 | Input | T2CLK | Input | IOC0 |
| P2.4 | Input | T2RST | Input | IOC0 |
| P2.5 | Output | PWM0 | Output | IOC1 |
| P2.6 | Quasi-Bidirectional | T2UP-DN | Input | IOC2 |
| P2.7 | Quasi-Bidirectional | T2CAPTURE | Quasi-Bidirectional | — |
| P3, P4 | Open-Drain Bidirectional | AD0-AD15 | — | — |
Каждый параллельный порт рассматривается как регистр специальных функций, которому соответствует определенный адрес.
Разряды порта ввода
Любой разряд порта, предназначенный для приема данных, может только читаться. Любая операция записи игнорируется (или невозможна). Общая схема разряда порта ввода состоит из регистра-защелки и буфера чтения (см. рис. 4.1).
Рис. 4.1. Схема разряда порта ввода
Разряд порта выбирается за одно временное состояние до того, как разрешается чтение из буфера. Выборка и распознавание значения разряда (0 или 1) происходит в течение фазы 1 (пока CLKOUT=0) до того, как оно подается на внутреннюю шину. Если во время выборки происходят изменения значения разряда, новое значение может быть записано (а может и не записываться) во время чтения. Разряды порта ввода не имеют никаких выходных драйверов (формирователей, усилителей, устройств).
Разряды порта вывода
Разряд порта вывода состоит из регистра-защелки и схемы управления внешним выводом (Q1,Q2,Q3) (см. рис. 4.2). Новое значение разряда порта вывода защелкивается в течение фазы 1 (пока CLKOUT=0). Значение разряда остается устойчивым до того, пока его не изменит другая операция записи (или пока не произойдет сброс устройства). Разряды порта вывода не имеют схем выборки и схем чтения буфера. При чтении разряда его значение не определено и должно маскироваться. Поскольку нет никакого механизма чтения значения разряда порта вывода, то возможна только его установка или очистка. Если необходимо инвертировать значение разряда, его образ должен храниться в памяти. Этот образ в памяти используется при установке или очистке разряда.
Рис. 4.2. Схема разряда порта вывода
Разряды квазидвунаправленного порта
Квазидвунаправленные разряды могут использоваться как для ввода, так и для вывода (схемы управления направлением не требуется). На внешних выводах этих разрядов формируют сигнал с низким уровнем напряжения и с большой силой тока (сильноточный) или сигнал с высоким уровнем напряжения и с малой силой тока (слаботочный). Слаботочный сигнал высокого уровня можно внешне изменить (на 0), обеспечивая функции ввода. На рис. 4.3 приведена схема разряда квазидвунаправленного порта.
Подобно разряду порта ввода разряд квазидвунаправленного порта имеет регистр-защелку и буфер чтения. Подобно разряду порта вывода, он имеет регистр-защелку порта. Именно структура выходного драйвера (Q1,Q2,Q3,Q4) делает квазидвунаправленный контакт уникальным.
Рис. 4.3. Схема разряда квазидвунаправленного порта
Внешний вывод разряда контакта может иметь только два статических значения: сильноточное низкое (0) или слаботочное высокое (1).
Запись нуля в разряд порта разрешает работу сильноточного низкого драйвера (транзистор Q2 открыт), и поэтому изменить значение разряда с 0 на 1 невозможно.
Запись единицы в разряд порта отключает сильноточный низкий драйвер (транзистор Q2 закрыт) и открывает очень слаботочный драйвер высокого уровня сигнала (Q3). Для того, чтобы быстро получить вывод высокого значения, сильноточный высокий драйвер (Q1) допускается в течение одного временного состояния и затем блокируется (активным остается только Q3).
Способность перевозбуждать (изменять 1 на 0) слаботочный драйвер вывода — это то, что дает разряду квазидвунаправленного порта возможность ввода.
Так как разряд квазидвунаправленного порта имеет схему чтения, возможно непосредственно читать его значение (в отличие от разрядов порта вывода). Однако так как вывод порта может внешне изменяться на нуль, его чтение может ложно указать на то, что в разряд был записан нуль.
Внешний вывод разряда квазидвунаправленного порта также содержит нагрузочный драйвер (Q3), который включается всякий раз, когда в регистр-защелку разряда записывается единица. Этот нагрузочный драйвер обеспечивает очень маленький ток, который заставляет вывод из высокоимпедансного состояния переходить к высокому (единичному) значению.
Разряды двунаправленного порта c открытым стоком
Разряды двунаправленного порта с открытым стоком функционируют подобно разрядам квазидвунаправленного порта, за исключением того, что нет никаких сильноточных или слаботочных высоких драйверов. На рис. 4.4 приведена схема разряда двунаправленного порта с открытым стоком.
Рис. 4.4. Схема разряда двунаправленного порта с открытым стоком
Запись нуля в регистр-защелку порта допускает сильноточный низкий драйвер (Q1). Пока Q1 активен, невозможно извне перевозбудить нуль без того, чтобы не нарушить работу устройства. Единица, записанная в регистр-защелку порта, отключает Q1 и переводит вывод порта в высокоимпедансное состояние.
Внешне вывод порта может управляться высоким уровнем сигнала с помощью нагрузочного резистора или логического ключа.
3 open-drain mode explanation, 4 quasi-bidirectional mode explanation, Nuc140 series data sheet – Rainbow Electronics NUC140 User Manual

supports digital output function but only with sink current capability, an additional pull-up resister is
needed for driving high state. If the bit value in the corresponding bit [n] of GPIOx_DOUT is “0”, the pin
drive a “low” output on the pin. If the bit value in the corresponding bit [n] of GPIOx_DOUT is “1”, the
pin output drives high that is controlled by the internal pull-up resistor or the external pull high resistor.
Figure 5-9 Open-Drain Output
Quasi-bidirectional Mode Explanation
PMDn[1:0]) to 11b the GPIOx port [n] pin is in Quasi-bidirectional mode and the I/O
pin supports digital output and input function at the same time but the source current is only up to
hundreds uA. Before the digital input function is performed the corresponding bit in GPIOx_DOUT
must be set to 1. The quasi-bidirectional output is common on the 80C51 and most of its derivatives. If
the bit value in the corresponding bit [n] of GPIOx_DOUT is “0”, the pin drive a “low” output on the pin.
If the bit value in the corresponding bit [n] of GPIOx_DOUT is “1”, the pin will check the pin value. If
pin value is high, no action takes. If pin state is low, then pin will drive strong high with 2 clock cycles
on the pin and then disable the strong output drive and then the pin status is control by internal pull-up
resistor. Note that the source current capability in quasi-bidirectional mode is only about 200uA to
30uA for VDD is form 5.0V to 2.5V