模块介绍:
接线:
VCC -- 3.3V 不能接5V,否则遮挡一次会触发3次中断
OUT -- PB14
测速原理:
cubeMX设置:
PB14设置为gpio中断
打开定时器2,时钟来源设置为内部时钟,设置溢出时间1s,计算公式为(psc+1)*(ARR+1)/72M。
打开定时器2中断,串口1中断和外部中断线(PB14).
main.c
#include "main.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "motor.h"
#include "stdio.h"
/* USER CODE END Includes *//* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD *//* USER CODE END PTD *//* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD *//* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM *//* USER CODE END PM *//* Private variables ---------------------------------------------------------*//* USER CODE BEGIN PV */
extern uint8_t buf;
/* USER CODE END PV *//* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP *//* USER CODE END PFP *//* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
unsigned int speedCnt = 0;void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) //GPIO口中断(外部中断),下降沿触发
{if(GPIO_Pin == GPIO_PIN_14 ) if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_14) == GPIO_PIN_RESET) {speedCnt++; }
}void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) //定时器中断服务函数,1s
{printf("speed:%d \r\n",speedCnt);speedCnt=0;
}
/* USER CODE END 0 *//*** @brief The application entry point.* @retval int*/
int main(void)
{/* USER CODE BEGIN 1 *//* USER CODE END 1 *//* MCU Configuration--------------------------------------------------------*//* Reset of all peripherals, Initializes the Flash interface and the Systick. */HAL_Init();/* USER CODE BEGIN Init *//* USER CODE END Init *//* Configure the system clock */SystemClock_Config();/* USER CODE BEGIN SysInit *//* USER CODE END SysInit *//* Initialize all configured peripherals */MX_GPIO_Init();MX_USART1_UART_Init();MX_TIM2_Init();/* USER CODE BEGIN 2 */HAL_UART_Receive_IT(&huart1, &buf, 1);HAL_TIM_Base_Start_IT(&htim2); //开启定时器中断/* USER CODE END 2 *//* Infinite loop *//* USER CODE BEGIN WHILE */while (1){/* USER CODE END WHILE *//* USER CODE BEGIN 3 */}/* USER CODE END 3 */
}