cancel
Showing results for 
Search instead for 
Did you mean: 

Toggle led using external interrupt from push button

NNana.1
Associate

I want to toggle a led when an external interrupt happened. But I could not.

That's my code using keil mdk for stm32f103c8t6

Any help, please?

 

#include "stm32f10x.h"
void GPIO_Config (void)
{
	RCC->APB2ENR |=  (1<<2);  // Enable GPIOA clock
	GPIOA->CRL &= ~(0xf<<4);  // clear bits (7:6:5:4)
	GPIOA->CRL |= (8<<4);  // Bits (7:6:5:4) = 1:0:0:0  --> PA1 in Input Mode in Pull-up/ Pull-down mode
	GPIOA->ODR |= (1<<1);  //  --> PA1 is in Pull UP mode
}
void EXTI1_IRQHandler(void)
{
	if (EXTI->PR & (1<<1))    // If the PA1 triggered the interrupt
	{
		EXTI->PR |= (1<<1);  // Clear the interrupt flag by writing a 1 
		toggle_GP(PC,13);
	}
}
void Interrupt_Config (void)
{
	RCC->APB2ENR |= (1<<0);  // Enable AFIO CLOCK
	AFIO->EXTICR[0] &= ~(0xf<<4);  // Bits[7:6:5:4] = (0:0:0:0)  -> configure EXTI1 line for PA1
	EXTI->IMR |= (1<<1);  // Bit[1] = 1  --> Disable the Mask on EXTI 1
	EXTI->RTSR |= (1<<1);  // Enable Rising Edge Trigger for PA1
	EXTI->FTSR &= ~(1<<1);  // Disable Falling Edge Trigger for PA1
	NVIC_SetPriority (EXTI1_IRQn, 1);  // Set Priority
	NVIC_SetVector(EXTI1_IRQn, (uint32_t)&EXTI1_IRQHandler);
	NVIC_EnableIRQ (EXTI1_IRQn);  // Enable Interrupt
}
int main()
{
	GPIO_Config();
	init_GP(PC,13,OUT50,O_GP_PP); // initialize PC13 as output for toggle
	toggle_GP(PC,13);
	Interrupt_Config();
}

 

7 REPLIES 7
KnarfB
Principal III

Yes, you can.

Yes, but it didn't work

S.Ma
Principal

Seems to be the old 2007 STM32F103 with blue pill and std lib?

gbm
Lead III

Rule #1: Do not use external interrupts with buttons. (Of course, there are exceptions to this rule.)

Use timer interrupt - SysTick is a good candidate. Check the state of the button every, say, 20 ms. Record the previous state and compare it with the current state. If there is a change, react. Then record the current state as the prevoius one to be used during the next check.

If you want to use external interrupt, then you also must use time interrupt. So, the timer interrupt must be used anyway.

My STM32 stuff on github - compact USB device stack and more: https://github.com/gbm-ii/gbmUSBdevice
MM..1
Chief II

Generate your code with wizard or read reference manuals. APB2 isnt only one control required...

Try CubeMX

KnarfB
Principal III
Karl Yamashita
Lead III

This video shows how to use EXTI interrupt to debounce a button and even count button presses.

https://youtu.be/o0qhmXR5LD0

If smoke escapes your device, put the smoke back in. It'll still work as a conversation piece. If you find my answers useful, click the Accept as Solution button so that way others can see the solution.