STM32f103EZ 系列
超声波 通过定时器来测量,PWM调速 控制车速 小车可以实现设定距离之间的 运动 ,实现跟随运动
具体的 源程序 如下 :
- #include "stm32f10x.h"
- #include "bsp_usart1.h"
- #include "bsp_length.h"
- #include "bsp_tick.h"
- # include "motor.h"
- # include "pwm_motor.h"
- #define CLI() __set_PRIMASK(1) /* 关闭总中断 */
- #define SEI() __set_PRIMASK(0) /*开总中断*/
- void Delay(unsigned short int time); //粗略的延时函数
- float ChangeDistance(unsigned int cout1); //时间转为距离函数
- //ECHO PA4
- //TRIG PA5
- int main(void)
- {
- unsigned int count=0; // 计数
- float distance=0; // 距离
-
- /* USART1 config 115200 8-N-1 */
- USART1_Config();
- Distance_Config(); //测距模块对应的引脚初始化
- CLI() ;//关闭总中断
- SEI(); //开总中断
- Tim3_Config(); //定时器的初始化
- Motor_Config();
- TIM_Mode_Config(); //PWM 调速
-
- GPIO_ResetBits(GPIOA,GPIO_Pin_5); //先拉低电平
-
- while(1)
- {
- printf(" 超声波初始化完成!! \r \n");
- printf(" 测距开始 \r \n");
- GPIO_SetBits(GPIOA,GPIO_Pin_5); //拉高电平
- Delay(30); //延时20个微秒
- // Delay(20);
- // Delay(20);
- GPIO_ResetBits(GPIOA,GPIO_Pin_5); //拉低电平
- TIM3->CNT=0; //TIM3的计数器清0
- while(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_4) == 0); //等待ECHO的高电平
-
- TIM_Cmd(TIM3,ENABLE); //运行TIM3进行计时
-
- while((GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_4) == 1) && (TIM3->CNT < TIM3->ARR-10))
- {
-
- TIM_Cmd(TIM3,DISABLE);
-
- count++;
- }
- printf("count=%d",count);
- distance=ChangeDistance(count);
- printf(" 当前距离为:%f\n",distance);
- Delay(20000);
- Delay(20000);
-
- if(distance>10)
- Go_forward();
- else
- Go_back();
- while(1);
-
-
- }
- }
- void Delay(unsigned short int time) //粗略的延时函数
- {
- unsigned char i=0;
- while(time--)
- {
- i=10;
- while(i--);
- }
- }
- float ChangeDistance(unsigned int cout1)
- {
- float distance=0;
- printf("cou1=%d\n",cout1);
- distance=cout1/58.0;
-
- return distance;
- }
- /*********************************************END OF FILE**********************/
复制代码
全部资料51hei下载地址:
超声波+PWM调速 小车.rar
(318.71 KB, 下载次数: 45)
|