STM32—项目二(感应开关盖垃圾桶)

目录

一、需用到的元器件

1.sg90舵机

2.超声波

3.传感器

4.蜂鸣器

二、配置

三、main.c代码


一、需用到的元器件

1.sg90舵机

        PWM波的频率不能太高,大约50HZ,即周期=1/频率=1/50=0.02s,20ms左右。

选择周期为20ms,则 PSC=7199,ARR=199

        角度控制:(高电平占空比越大角度越大)

        0.5ms-------------0度; 2.5% 对应函数中CCRx为5   

        CCRx为5是因为:0.5/20ms=CRRx5/ARR200(32内部PWM设置),比例相等,占空比相等

        1.0ms------------45度; 5.0% 对应函数中CCRx为10

        1.5ms------------90度; 7.5% 对应函数中CCRx为15

        2.0ms-----------135度; 10.0% 对应函数中CCRx为20

        2.5ms-----------180度; 12.5% 对应函数中CCRx为25

2.超声波

引脚Trig、Echo

         1.怎么让它发送波

        给Trig端口发送至少10us的高电平。

        发送出去的超声波

        2.怎么知道超声波开始发了

        Echo信号,由低电平跳转到高电平,表示开始发送波。

        3.怎么知道返回波回来了

        Echo,由高电平跳转回低电平,表示波回来了。

        4.怎么算时间

        (1)Echo引脚维持高电平的时间!

        (2)波发出去的那一刻,启动定时器 ,波回来的那一刻,停止定时器,计算出中间经过多少时间。

        5.怎么计算距离

        距离 = 速度 (340m/s)* 时间/2

3.传感器

         模块上的DO口,传感器不震动:输出高电平。传感器震动:输出低电平,绿色指示灯亮。

4.蜂鸣器

            蜂鸣器收到低电平响,高电平不响。

二、配置

1.GPIO引脚接线  

        其中PA6中断要在NVIC打开EXTI中断

        添加:1.PA0按钮中断控制开关盖,下降沿触发中断,打开NVIC中断

                2.把PA0、PA6的中断优先级设置为2

 2.时钟72MHz

2.定时器TIM2

3.定时器TIM4_CH4通道(PB9 接舵机黄线PWM信号)

三、main.c代码

        功能:超声波测距小于10、传感器被触碰、按钮被按下,然后舵机控制开盖,并且亮灯、蜂鸣器响。

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "tim.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
#define OPEN 1//标志位 防止一直距离小于10时 一直滴滴响============================
#define CLOSE 0

char flag = CLOSE;
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

//使用TIM2来做us级延时函数======================================================================
void TIM2_Delay_us(uint16_t n_us)//计算一个数所需时间1 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);
}

//超声波测距,返回距离============================================================
float get_distance()
{
	int cnt;
	float distance;
	
		//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.计算距离
	distance = cnt*340/2*0.000001*100; // 距离 = 速度 (340m/s)* 时间/2(计数1次表示1us)
	
	return distance;
}

//舵机==================================================================
void initSG90_0()
{
	HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_4);//启动定时器(产生PWM)

}
void openDusbin()
{
	if(flag == CLOSE){//如果是关闭就打开
		flag = OPEN;
	__HAL_TIM_SetCompare(&htim4, TIM_CHANNEL_4, 15);//90度
	HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET);//蜂鸣器响
	HAL_Delay(100);
	HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET);//蜂鸣器不响
	}
	HAL_Delay(2000);

}
void closeDusbin()
{
	__HAL_TIM_SetCompare(&htim4, TIM_CHANNEL_4, 5);//0度

	HAL_Delay(100);
	flag = CLOSE;
}

//LED灯============================================================
void openLED()
{
	HAL_GPIO_WritePin(GPIOB, GPIO_PIN_8, GPIO_PIN_RESET);
}
void closeLED()
{
  HAL_GPIO_WritePin(GPIOB, GPIO_PIN_8, GPIO_PIN_SET);

}
	
//传感器中断及按钮中断===============================================
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
	if(GPIO_Pin == GPIO_PIN_0 || GPIO_Pin == GPIO_PIN_6){
		if(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0) == GPIO_PIN_RESET || //按键
				HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_6) == GPIO_PIN_RESET){//传感器
			openLED();
			openDusbin();
		}
	}


}

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
	

	
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_TIM2_Init();
  MX_TIM4_Init();
  /* USER CODE BEGIN 2 */
	
	//=======================================================================
	closeDusbin();//初始关盖状态
	initSG90_0();//启动定时器tim4 
	HAL_NVIC_SetPriority(SysTick_IRQn,0,0);//提高滴答定时器的优先级为0
	
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */


  while (1)
  {
    /* USER CODE END WHILE */
		if(get_distance() < 10)//判断超声波测得的距离
		{
			openLED();
			openDusbin();
		}else{
			closeLED();
			closeDusbin();
		}
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wlkq~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值