- Preface
This time we will introduce a relatively simple IO port input and output operation
- Prepare
hardware: The development board
uses GPIO input status change to control the LED on and off. From the schematic diagram, we can find that the button is at PB4
According to the button circuit, it is externally pulled up, and the IO port is low when pressed.
The control pins of the LED are as follows, namely PB0, PB3, PB5, and PB7. We will take the green PB3 of the demo code as an example.
Software: MPLAB X, MCC, GPIO demo code
- The program
opens the demo code in the following path through File->Open Project...
- Code analysisFirst
, the main function under the main file performs SYS init initialization
System initialization function
GPIO initialization, where GPIOB_REGS->GPIO_TRISCLR = 0x8U; sets PB3 to output as the output control of the green LED, and GPIOB_REGS->GPIO_ANSELCLR = 0x18U; configures PB3 and PB4 to digital mode
You can also use the following button and LED IO macro definitions to initialize and control the IO port, such as LED_OutputEnable() to configure the IO port as output, while LED_Set() and LED_Clear() are used to output high and low levels. The input configuration of the button can be configured using SWITCH_InputEnable(), and the level value of the button can be directly obtained through SWITCH_PIN
[attach]726129 [/attach]
Going back to the main function, you can see that the button state is read through if (SWITCH_Get() == SWITCH_PRESSED_STATE). According to the definition of SWITCH_PRESSED_STATE, it is 0, which means the light is on when the level is low, and the low level is the button pressed state. Then output LED_Set or LED_Clear according to the state, that is, the on and off state.
[attach]726130 [/attach]
- Program Modification
If you want to change it to control the red LED, just change the IO pin number to 0, that is, PB0
Then change the GPIO_Inintialize function as follows
After compiling and downloading, you can use the button to control the red LED.