1.STM32F103RCT6最小系统板
2.硬件相关信息参见
https://blog.csdn.net/zhenglu777999/article/details/124275752?spm=1001.2014.3001.5502
GB37-520电机 | GB37-520电机相连端子 | BTN7971B模块 电源电机侧 | BTN7971B模块 电源电机侧相连端子 | BTN7971B模块 单片机侧 | BTN7971B模块 单片机侧相连端子 | |
1 | M+ | OUT1 | M+ | 5V+ | ||
2 | M- | OUT2 | M- | IN1 | TIM8_CH1 PC6 | |
3 | GND | 单片机GND | VCC | 7.2V | IN2 | TIM8_CH2 PC7 |
4 | VCC | 3.3V | GND | 电源GND | GND | 单片机GND |
5 | B | TIM2_CH1 PA15 | ||||
6 | A | TIM2_CH2 PB3 |
3.STM32CubeIDE中CubeMX配置TIM2、TIM8和USART。
4.生成代码后,在Core->Src->tim.c文件inlcude代码沙盒中添加以下代码。
/* USER CODE BEGIN Includes */
#include
#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif
PUTCHAR_PROTOTYPE
{
HAL_UART_Transmit(&huart1 , (uint8_t *)&ch, 1 , 0xffff);
return ch;
}
#define LOG_ENABLE 1
#if LOG_ENABLE
#define log(format,...) printf(format"\r\n",##__VA_ARGS__)
#else
#define log(format,...)
#endif
/* USER CODE END Includes */
/* USER CODE BEGIN 2 */
HAL_TIM_Encoder_Start(&htim2,TIM_CHANNEL_1|TIM_CHANNEL_2);
HAL_TIM_PWM_Start(&htim8,TIM_CHANNEL_1);
//HAL_TIM_PWM_Start(&htim8,TIM_CHANNEL_2);
__HAL_TIM_SET_COMPARE(&htim8,TIM_CHANNEL_1,3000);
//__HAL_TIM_SET_COMPARE(&htim8,TIM_CHANNEL_2,3000);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
int rate=10;
float startTime = HAL_GetTick();
while (1)
{
//HAL_GPIO_TogglePin(GPIOD, GPIO_PIN_2);
//HAL_Delay(500);
if(HAL_GetTick()-startTime>(((float)1000)/rate))
{
startTime=HAL_GetTick();
short i = __HAL_TIM_GET_COUNTER(&htim2);
float c=((float)i)/2/2/13/30;
float speed=c*rate;
log("speed:%d",(int)speed*100);
__HAL_TIM_SET_COUNTER(&htim2, 0);
}
/* USER CODE END WHILE */
5.通过串口工具SSCOM,可以看到串口输出结果,负号是转速方向,单位为每分钟转速。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)