赞
踩
超声波模块:
Trig – PB6
Echo – PB7
sg90舵机:
PWM – PB9
按键:
KEY1 – PA0
LED灯:
LED1 – PB8
震动传感器:
D0 – PB5
VCC – 5V
蜂鸣器:
IO – PB4
VCC – 3V3
#include "main.h" #include "tim.h" #include "gpio.h" #define OPEN 1 #define CLOSE 0 uint8_t flag = CLOSE; //使用TIM2来做us级延时函数 void TIM2_Delay_us(uint16_t n_us) { /* 使能定时器2计数 */ __HAL_TIM_ENABLE(&htim2); __HAL_TIM_SetCounter(&htim2, 0); while(__HAL_TIM_GetCounter(&htim2) < ((1 * n_us)-1) ); /* 关闭定时器2计数 */ __HAL_TIM_DISABLE(&htim2); } double get_distance() { uint16_t cnt = 0; double dis = 0; //1. Trig ,给Trig端口至少10us的高电平 HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_SET);//拉高 TIM2_Delay_us(20); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_RESET);//拉低 //2. echo由低电平跳转到高电平,表示开始发送波 //波发出去的那一下,开始启动定时器 while(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_7) == GPIO_PIN_RESET);//等待输入电平拉高 HAL_TIM_Base_Start(&htim2); __HAL_TIM_SetCounter(&htim2,0); //3. 由高电平跳转回低电平,表示波回来了 while(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_7) == GPIO_PIN_SET);//等待输入电平变低 //波回来的那一下,我们开始停止定时器 HAL_TIM_Base_Stop(&htim2); //4. 计算出中间经过多少时间 cnt = __HAL_TIM_GetCounter(&htim2); //5. 距离 = 速度 (340m/s)* 时间/2(计数1次表示1us) dis = cnt*340/2*0.000001*100; //单位:cm return dis; } void openStateLight() { //点亮LED1 HAL_GPIO_WritePin(GPIOB,GPIO_PIN_8,GPIO_PIN_RESET); } void closeStateLight() { //关闭LED1 HAL_GPIO_WritePin(GPIOB,GPIO_PIN_8,GPIO_PIN_SET); } void initSg90() { HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_1);//启动定时器3的第一个通道用于产生pwm __HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_4, 5);//将舵机置为0度 } void openDustbin() { if(flag == CLOSE){ flag = OPEN; __HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1,15);//将舵机置为90度 HAL_GPIO_WritePin(GPIOB,GPIO_PIN_4, GPIO_PIN_RESET);//蜂鸣器响一声 HAL_Delay(100); HAL_GPIO_WritePin(GPIOB,GPIO_PIN_4, GPIO_PIN_SET); } HAL_Delay(2000); } void closeDustbin() { __HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, 5);//将舵机置为0度 flag = CLOSE; HAL_Delay(150); } void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)//重写中断服务函数 { if(GPIO_Pin == GPIO_PIN_0 || GPIO_Pin == GPIO_PIN_5){//当中断源来自PA0,按键1被按下;来自PB5,震动传感器被震动 if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_0) == GPIO_PIN_RESET || HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_5) == GPIO_PIN_RESET){//检测是否为下降沿触发 openStateLight(); openDustbin();//开盖 } } } int main(void) { double distance = 0;//距离 HAL_Init(); SystemClock_Config(); MX_GPIO_Init(); MX_TIM2_Init(); MX_TIM3_Init(); /* USER CODE BEGIN 2 */ initSg90(); HAL_NVIC_SetPriority(SysTick_IRQn, 0,0);//提高滴答计时器的中断优先级 while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ distance = get_distance(); if(distance < 10){ //代开LED1 openStateLight(); //开盖 openDustbin(); }else{ //关闭LED1 closeStateLight(); //关盖 closeDustbin(); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。