新手入门
- 积分
- 15
- 金钱
- 15
- 注册时间
- 2022-12-21
- 在线时间
- 7 小时
|
求助!求助!求助!我想利用超声波模块测量面前人体的距离,从而通过改变PWM对电机实现不同距离不同转速,但是现在烧录代码后,如果电机信号线不接入单片机GPIO输出,电机转动,但是一接入电机都不转了。
#include "stm32f10x.h"
#include "stdio.h"
#define TRIG_PIN GPIO_Pin_0
#define ECHO_PIN GPIO_Pin_1
#define MOTOR_PIN GPIO_Pin_6
void TIM2_PWM_Init(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
GPIO_InitStructure.GPIO_Pin = MOTOR_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
TIM_TimeBaseStructure.TIM_Period = 999;
TIM_TimeBaseStructure.TIM_Prescaler = 719;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC3Init(TIM2, &TIM_OCInitStructure);
TIM_OC3PreloadConfig(TIM2, TIM_OCPreload_Enable);
TIM_Cmd(TIM2, ENABLE);
}
void GPIO_Init_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = TRIG_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = ECHO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void delay_us(uint32_t us)
{
us *= 8;
while (us--)
;
}
void HCSR04_Trigger(void)
{
GPIO_SetBits(GPIOA, TRIG_PIN);
delay_us(10);
GPIO_ResetBits(GPIOA, TRIG_PIN);
}
float HCSR04_GetDistance(void)
{
uint32_t count = 0;
float distance = 0;
while (!GPIO_ReadInputDataBit(GPIOA, ECHO_PIN))
;
while (GPIO_ReadInputDataBit(GPIOA, ECHO_PIN))
{
delay_us(1);
count++;
}
distance = (float)count * 0.01715; // ?????????340m/s,?????????2
return distance;
}
int main(void)
{
float distance = 0;
uint16_t pwm = 0;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_Init_Config();
TIM2_PWM_Init();
while (1)
{
HCSR04_Trigger();
distance = HCSR04_GetDistance();
if (distance < 10)
{
pwm = 100;
}
else if (distance < 20)
{
pwm = 500;
}
else if (distance < 30)
{
pwm = 800;
}
else
{
pwm = 1000;
}
TIM_SetCompare3(TIM2, pwm);
delay_us(50000); // ????????????????PWM
}
}
|
|