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)
2018-7-24 17:02 上傳
點擊文件名下載附件
跟隨運動
|