众所周知熟练使用HAL库可以帮你解决不少stm32的开发难题,但是是谁让你陷入了这些难题,别问。
如上图所示,正常初始化这个模块后生成代码如下图所示;
* DAC init function */
void MX_DAC_Init(void)
{/* USER CODE BEGIN DAC_Init 0 *//* USER CODE END DAC_Init 0 */DAC_ChannelConfTypeDef sConfig = {0};/* USER CODE BEGIN DAC_Init 1 *//* USER CODE END DAC_Init 1 *//** DAC Initialization*/hdac.Instance = DAC;if (HAL_DAC_Init(&hdac) != HAL_OK){Error_Handler();}/** DAC channel OUT1 config*/sConfig.DAC_Trigger = DAC_TRIGGER_NONE;sConfig.DAC_OutputBuffer = DAC_OUTPUTBUFFER_ENABLE;if (HAL_DAC_ConfigChannel(&hdac, &sConfig, DAC_CHANNEL_1) != HAL_OK){Error_Handler();}/* USER CODE BEGIN DAC_Init 2 *//* USER CODE END DAC_Init 2 */}
但在这种情况下我们直接使用HAL_DAC_SetValue函数来配置通道输出模拟信号是无效的,因为既没有使GPIO引脚进入模拟输出状态,也没有开启外设通道,解决方法是添加这些代码
/* USER CODE BEGIN DAC_Init 0 */HAL_DAC_MspInit(&hdac);/* USER CODE END DAC_Init 0 */
/* USER CODE BEGIN DAC_Init 2 */HAL_DAC_Start(&hdac,DAC_CHANNEL_1);HAL_DAC_Start(&hdac,DAC_CHANNEL_2);/* USER CODE END DAC_Init 2 */