写一个基于STM32F103ZE的霍尔传感器测转速显示库函数代码
时间: 2024-01-23 08:03:42 浏览: 84
以下是一个基于STM32F103ZE的霍尔传感器测转速显示库函数代码:
首先,需要定义一些宏定义和变量:
```c
#include "stm32f10x.h"
#define HALL_PIN GPIO_Pin_0
#define HALL_PORT GPIOA
#define HALL_RCC RCC_APB2Periph_GPIOA
#define TIMER_RCC RCC_APB1Periph_TIM2
#define TIMER TIM2
#define TIMER_IRQ TIM2_IRQn
volatile uint16_t hall_count = 0;
volatile uint16_t rpm = 0;
```
接下来,需要初始化GPIO和定时器:
```c
void hall_sensor_init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStruct;
RCC_APB2PeriphClockCmd(HALL_RCC, ENABLE);
RCC_APB1PeriphClockCmd(TIMER_RCC, ENABLE);
GPIO_InitStructure.GPIO_Pin = HALL_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(HALL_PORT, &GPIO_InitStructure);
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = 72 - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIMER, &TIM_TimeBaseStructure);
TIM_ITConfig(TIMER, TIM_IT_Update, ENABLE);
NVIC_InitStruct.NVIC_IRQChannel = TIMER_IRQ;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct);
TIM_Cmd(TIMER, ENABLE);
}
```
接下来,需要实现定时器的中断处理函数,每次中断计算转速并显示:
```c
void TIM2_IRQHandler(void)
{
if (TIM_GetITStatus(TIMER, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIMER, TIM_IT_Update);
hall_count = TIM_GetCounter(TIMER);
TIM_SetCounter(TIMER, 0);
rpm = hall_count * 60 / 7;
// 显示rpm的代码这里省略
}
}
```
最后,在主函数中调用初始化函数即可:
```c
int main(void)
{
hall_sensor_init();
while(1)
{
// 主函数代码这里省略
}
}
```
阅读全文