Toggle LED with Push Button (Debouncing)

Toggle LED with Push Button (Debouncing)


#include "stm32f1xx.h"


int main(void)
{
//Setup Reset and Clock Control Register
  RCC->APB2ENR |= RCC_APB2ENR_IOPCEN;  //Enable clock to Port C
RCC->APB2ENR |= RCC_APB2ENR_IOPBEN;  //Enable clock to Port B

//Setup GPIO Registers of Port C
GPIOC->CRH |= GPIO_CRH_MODE13; //Port C13 in Output Mode, 50 MHz
GPIOC->CRH &= ~(GPIO_CRH_CNF13); //Port C13 in General Purpose output, Push Pull

//Setup GPIO Registers of Port B
GPIOB->CRL &= ~(GPIO_CRL_MODE1); //Port B1 in Input Mode
GPIOB->CRL |= GPIO_CRL_CNF1_0; //Port B1 in Floating State determined by CNF1[1:0]
GPIOB->CRL &= ~(GPIO_CRL_CNF1_1);

volatile char ButtonPressed = 0;
GPIOC->BSRR |= GPIO_BSRR_BS13; //Turn OFF LED
volatile unsigned int ButtonPressedConfidenceLevel = 0;  // Determines time for which button is kept pressed
volatile unsigned int ButtonReleasedConfidenceLevel = 0; // Determines time for which button is kept released
volatile unsigned int ConfidenceThreshold = 50000;
volatile char LEDState=0;

    while(1)
    {
    if(GPIOB->IDR & GPIO_IDR_IDR1)
    {
    if (ButtonPressedConfidenceLevel > ConfidenceThreshold)
    {
    if (LEDState == 0)
    {
LEDState = 1;
GPIOC->BRR |= GPIO_BRR_BR13; // Turn on LED
ButtonPressedConfidenceLevel=0; //Reset timer for button pressed
}
    else
    {
    LEDState = 0;
    GPIOC->BSRR |= GPIO_BSRR_BS13; //Turn OFF LED
    ButtonPressedConfidenceLevel=0; //Reset timer for button pressed
}
}
    else
    {
    ButtonPressedConfidenceLevel++;
    ButtonReleasedConfidenceLevel=0;
}
     }
    else
    {
if (ButtonReleasedConfidenceLevel > ConfidenceThreshold)
{
ButtonReleasedConfidenceLevel=0; //Reset timer for button released
}
else
{
ButtonReleasedConfidenceLevel++;
ButtonPressedConfidenceLevel=0;
}
}
  }
}


Comments

Popular posts from this blog

HackRF with srsLTE and openlte

Blinking a LED in STM32F103C8T6 (Blue Pill) Board

Read Continuously from Serial Port in QT