一、雾化片以及驱动电路
雾化片驱动需要产生108KHZ的PWM,占空比是1/2,预分频约为58左右,可以调出雾量大小
二、Cubemx的配置
SYS配置
RCC配置
时钟树配置
定时器设置,选择PWM输出通道,预分频60,计数10,占空比5/10
三、keil代码配置
首先我们要对tim.c中初始化函数修改
/* TIM3 init function */
void MX_TIM3_Init(uint16_t pre,uint16_t pol)//修改预分频,计数值
{
/* USER CODE BEGIN TIM3_Init 0 */
/* USER CODE END TIM3_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
/* USER CODE BEGIN TIM3_Init 1 */
/* USER CODE END TIM3_Init 1 */
htim3.Instance = TIM3;
htim3.Init.Prescaler = pre;//预分频
htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
htim3.Init.Period = pol;//计数值
htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
if (HAL_TIM_Base_Init(&htim3) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_Init(&htim3) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 5;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM3_Init 2 */
/* USER CODE END TIM3_Init 2 */
HAL_TIM_MspPostInit(&htim3);
}
tim.h
/* USER CODE BEGIN Private defines */
/* USER CODE END Private defines */
void MX_TIM3_Init(uint16_t pre,uint16_t pol);
void HAL_TIM_MspPostInit(TIM_HandleTypeDef *htim);
/* USER CODE BEGIN Prototypes */
/* USER CODE END Prototypes */
main.c
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_TIM3_Init(55,10);
MX_I2C1_Init();
/* USER CODE BEGIN 2 */
HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_2);
OLED_Clear();
OLED_Init();
/* USER CODE END 2 */
此时加湿器以很小的声音和雾量喷出,预分频设置64雾量最大
接下来修改模拟火山喷发
注释之前的初始化代码
while 中调节频率
for(uint8_t i=55;i<=64;i++){ //预分频从55-64
MX_TIM3_Init(i,10); //循环重新装载,并初始化
HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_2); //打开加湿器
HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_13); //翻转LED小灯
HAL_Delay(200); //加湿器开启200ms
HAL_TIM_PWM_Stop(&htim3,TIM_CHANNEL_2); //关闭加湿器
HAL_Delay(1000); //加湿器关闭1000ms
}
此代码实现了模仿火山喷发,并有小慢慢变大的状态,因为我的工程之前移植oled,影响加湿器启动需要注释掉。不然加湿器启动很慢,按以上步骤新建的不需要考虑这个问题。
humi
链接: https://pan.baidu.com/s/1HhGBNEkUJ95MbDaNMHLuyA?pwd=f9qc 提取码: f9qc