STM32F303RE GPIO Digital input example - register level program
Development board used : Nucleo - STM32F303RE
1. Firmware - Digital input (one pin of the switch connected to PORT A PIN 6 and other pin of the switch connected to ground. )
When a button connected to PORT A PIN 6 is pressed A built-in LED connected to the PORT A PIN 5 is controlled.
Steps:
a) Enable the PORT A PIN 5 as output pin , PORT A PIN 6 as input
To Enable a port pin as output, set corresponding GPIOx_MODER register
Here in our case GPIOA_MODER is the register for PORT A
For each port pin, there are 2 bits reserved in this register
So for pin 5, the bits are 10,11
To set pin 5 as output pin, set 10th bit as 1 (refer the below details for register bits)
it can be done with below code
GPIOA->MODER |= 1<<10;
To make PORT A PIN 6 as input pin, set the GPIOA_MODER 12,13 bit to 0 (By default set to 0 , so not necessary)
GPIOA->MODER |= 0<<12;
To enable the pull-up resistor for PORT A PIN 6 use register GPIOA_PUPDR (See the register details below)
GPIOA->PUPDR |= 1<<12;
b) Monitor the state of PORT A pin 6 (which is connected to switch)
To check the state of PORT A pin 6 use GPIOx_IDR
Check the state of PORTA pin 6 by :
(GPIOA->IDR)&(1<<6) => if this is TRUE, then the pin is connected to the +ve 5V through the pull up resistor
So make the LED off -> make the port A 5th pin LOW , set 21st bit of GPIOA_BSRR (Refere above register details)
if (GPIOA->IDR)&(1<<6) is false, which means pin 6 is connected to ground through the switch,so turn on the LED by setting PORTA 5th pin to HIGH , set 5th bit of GPIOA_BSRR
GPIOA->BSRR |= 1<<5; <--------- Make Port A 5th pin HIGH
GPIOA->BSRR |= 1<<21; <--------- Make PORT A 5th pin LOW.
Comments