银杏科技有限公司旗下技术文档发布平台 | |||
技术支持电话 | 0379-69926675-801 | ||
技术支持邮件 | Gingko@vip.163.com | ||
版本 | 日期 | 作者 | 修改内容 |
---|---|---|---|
V1.0 | 2020-07-11 | gingko | 初次建立 |
DAC_output=V_REF×DOR/4096
1、主函数
int main(void) { /* MCU配置 */ /* 重置所有外设, 初始化Flash接口和Systick. */ HAL_Init(); /* 系统时钟配置 */ SystemClock_Config(); /* 初始化所有已配置的外设 */ MX_GPIO_Init(); MX_DAC_Init(); LED_GREEN_ON; HAL_DAC_Start(&hdac, DAC_CHANNEL_1); //开启DAC通道1 dac1.set_voltage(2.0); while (1) { } }
2、DAC初始化
/* DAC初始化函数*/ void MX_DAC_Init(void) { DAC_ChannelConfTypeDef sConfig; /** DAC初始化 */ hdac.Instance = DAC; if (HAL_DAC_Init(&hdac) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } /**DAC 通道1配置 */ 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(__FILE__, __LINE__); } }
HAL_StatusTypeDef HAL_DAC_Init(DAC_HandleTypeDef* hdac) { /* 检查DAC句柄 */ if(hdac == NULL) { return HAL_ERROR; } /* 检查参数*/ assert_param(IS_DAC_ALL_INSTANCE(hdac->Instance)); if(hdac->State == HAL_DAC_STATE_RESET) { /* 分配锁资源并对其进行初始化 */ hdac->Lock = HAL_UNLOCKED; /* 初始化底层硬件 */ HAL_DAC_MspInit(hdac); } /* 初始化DAC状态*/ hdac->State = HAL_DAC_STATE_BUSY; /* 将DAC错误代码设置为none */ hdac->ErrorCode = HAL_DAC_ERROR_NONE; /* 初始化DAC状态*/ hdac->State = HAL_DAC_STATE_READY; /*返回函数状态 */ return HAL_OK; }
3、使能DAC转换通道
HAL_StatusTypeDef HAL_DAC_Start(DAC_HandleTypeDef* hdac, uint32_t Channel)//第一个参数是DAC句柄,第二个用来设置DAC 通道 { uint32_t tmp1 = 0, tmp2 = 0; /* 检查参数 */ assert_param(IS_DAC_CHANNEL(Channel)); /* 锁定进程 */ __HAL_LOCK(hdac); /* 更改DAC状态 */ hdac->State = HAL_DAC_STATE_BUSY; /* 使能外设 */ __HAL_DAC_ENABLE(hdac, Channel); if(Channel == DAC_CHANNEL_1) { tmp1 = hdac->Instance->CR & DAC_CR_TEN1; tmp2 = hdac->Instance->CR & DAC_CR_TSEL1; /* 检查是否启用了软件触发器*/ if((tmp1 == DAC_CR_TEN1) && (tmp2 == DAC_CR_TSEL1)) { /* 启用选定的DAC软件转换 */ hdac->Instance->SWTRIGR |= (uint32_t)DAC_SWTRIGR_SWTRIG1; } } else { tmp1 = hdac->Instance->CR & DAC_CR_TEN2; tmp2 = hdac->Instance->CR & DAC_CR_TSEL2; /* 检查是否启用了软件触发器*/ if((tmp1 == DAC_CR_TEN2) && (tmp2 == DAC_CR_TSEL2)) { /* 启用选定的DAC软件转换*/ hdac->Instance->SWTRIGR |= (uint32_t)DAC_SWTRIGR_SWTRIG2; } } /* 更改DAC状态 */ hdac->State = HAL_DAC_STATE_READY; /* 进程解锁 */ __HAL_UNLOCK(hdac); /* 返回函数状态 */ return HAL_OK; }
4、设置DAC的输出值
void set_voltage(double voltage) { unsigned short int temp; temp = voltage * 4095 / 2.5; HAL_DAC_SetValue(&hdac, DAC_CHANNEL_1, DAC_ALIGN_12B_R, temp); } /* 设置DAC通道的指定数据保持寄存器值 */ HAL_StatusTypeDef HAL_DAC_SetValue(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Alignment, uint32_t Data) { __IO uint32_t tmp = 0; /* 检查参数 */ assert_param(IS_DAC_CHANNEL(Channel)); assert_param(IS_DAC_ALIGN(Alignment)); assert_param(IS_DAC_DATA(Data)); tmp = (uint32_t)hdac->Instance; if(Channel == DAC_CHANNEL_1) { tmp += DAC_DHR12R1_ALIGNMENT(Alignment); } else { tmp += DAC_DHR12R2_ALIGNMENT(Alignment); } /*设置DAC通道1选择的数据保持寄存器 */ *(__IO uint32_t *) tmp = Data; /* 返回函数状态 */ return HAL_OK; }