STM32F1 external interrupt method to read water flow sensor

The common Hall water flow sensor is shown in the figure below, the red is connected to the positive pole, the black is connected to the negative pole, and the yellow is connected to the pin used by the external interrupt (in this case, PB14). The STM32F103 minimum system is used for testing.

 The initialization sequence for external interrupts is

Clock initialization - GPIO initialization - AFIO interrupt pin selection - EXTI edge detection and control - NVIC initialization

Taking PB14 as an example, the initialization code is as follows, and the rising edge triggers an interrupt

void WaterFlow_Init(void)
    //GPIO和AFIO初始化
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
	
    //GPIO配置
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB, &GPIO_InitStructure);
	
    //
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource14);
	
	EXTI_InitTypeDef EXTI_InitStructure;
	EXTI_InitStructure.EXTI_Line = EXTI_Line14;
	EXTI_InitStructure.EXTI_LineCmd = ENABLE;
	EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
	EXTI_Init(&EXTI_InitStructure);
	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	
	NVIC_InitTypeDef NVIC_InitStructure;
	NVIC_InitStructure.NVIC_IRQChannel = EXTI15_10_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
	NVIC_Init(&NVIC_InitStructure);
}

PB14 is on the 14th external interrupt line, so the interrupt function uses EXTI15_10_IRQHandler, where WaterFlow_Count is a custom variable, and WaterFlow_Count is incremented by 1 every time an interrupt is entered

void EXTI15_10_IRQHandler(void)
{
	if (EXTI_GetITStatus(EXTI_Line14) == SET)
	{
		if (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_14) == 0)
		{
			WaterFlow_Count ++;
		}
		EXTI_ClearITPendingBit(EXTI_Line14);
	}
}

We call WaterFlow_Init(void) in the main function , and then read the value of WaterFlow_Count continuously

Advantages: relatively simple

Disadvantages: If the water flow rate of this method is too high, frequent interruptions will cause the detection method to be inaccurate

It is recommended to use TIM_ETR method to detect

Guess you like

Origin blog.csdn.net/snoopy_13579/article/details/131737480