Messing With Stm32 Discovery Pin_state_reading
In the last exciting episode of Messing with stm32 Discovery we managed to get a not 1, not 2 and not even 3 but 4 HA HA HA HA, 4 LEDs flashing. So that means we now know how to manipulate stm32 pins and output stuff. But microcontrollers are also useful cause they can read a state of the pin. The Discovery board comes with a push button connected to pin 0 on the GPIOA port. Below I will show the code needed to initialize and read the pin state. Just add it to the code from the LED flash tutorial in previous post. Again, i believe that the comments are more than enough to understand what the code is doing. So the gpio.c will need this:
/* GPIOA Periph clock enable */
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
/* and GPIOA pin 0 as input*/
GPIOA->MODER &= ~GPIO_MODER_MODER0;
/* max speed */
GPIOA->OSPEEDR |= GPIO_OSPEEDER_OSPEEDR0;
/* GPIOA pull-down enabled
We do this because button press
pulls the pin to the Vdd
*/
GPIOA->PUPDR |= GPIO_PUPDR_PUPDR0_1;
/* returns the pin state */
int qc_gpio_pin_get(GPIO_TypeDef *GPIOPort, uint16_t pin){
int ret = 0;
if(GPIOPort->IDR & pin){
/* wait for the pin state to settle */
kg_delay(10000);
if(GPIOPort->IDR & pin){
ret = 1;
}
}
return ret;
}
And that is it. That is all you need to to be able set a pin/port to the input mode and read its status. So just to wrap it up in main you can do this:
int main(){
/* initialize the port config */
qc_gpio_init();
while(1){
/* flash slower */
qc_gpio_basic_flash(500000);
/* while button pressed flash faster *
while(qc_gpio_pin_get(GPIOA, GPIO_PIN_0)){
qc_gpio_basic_flash(100000);
}
}
return 0;
}
And again, its as simple as that. Just type in make to create the .elf file using the Makefile from last tutorial and load it to the stm32. Now, in the next post we will investigate you how to set the pin to generate the interrupt.