功能描述:配置STM32F405RGT6的DAC,在PA5引脚每隔2秒分别输出1V、2V、3V的电压。
- main.c文件内容如下
#include "stm32f4xx.h" // Device header #include "Delay.h" #include "MyDAC.h" int main(void) { MyDAC_Init(); //初始化DAC while(1) { MyDAC_SetData(DAC_Channel_2, DAC_Align_12b_R, 1241); //设置DAC通道2输出1V电压 MyDAC_SoftwareTrigger(DAC_Channel_2); //软件触发DAC通道2 Delay_s(2); MyDAC_SetData(DAC_Channel_2, DAC_Align_12b_R, 2482); //设置DAC通道2输出2V电压 MyDAC_SoftwareTrigger(DAC_Channel_2); //软件触发DAC通道2 Delay_s(2); MyDAC_SetData(DAC_Channel_2, DAC_Align_12b_R, 3723); //设置DAC通道2输出3V电压 MyDAC_SoftwareTrigger(DAC_Channel_2); //软件触发DAC通道2 Delay_s(2); } }
-
MyDAC.c文件内容如下
#include "MyDAC.h" /** * @摘要 初始化DAC * @参数 无 * @返回值 无 * @说明 无 */ void MyDAC_Init(void) { //开启GPIOA时钟 RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); //定义GPIO初始化结构体 GPIO_InitTypeDef GPIO_InitStructure; //初始化上述结构体 GPIO_StructInit(&GPIO_InitStructure); //配置GPIO模式为模拟模式 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN; //配置GPIO的速度为高速100MHZ GPIO_InitStructure.GPIO_Speed = GPIO_High_Speed; //指定GPIO引脚为Pin5 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5; //初始化对应的GPIO GPIO_Init(GPIOA, &GPIO_InitStructure); //开启DAC时钟 RCC_APB1PeriphClockCmd(RCC_APB1Periph_DAC, ENABLE); //定义DAC初始化结构体 DAC_InitTypeDef DAC_InitStruct; //初始化上述结构体 DAC_StructInit(&DAC_InitStruct); //配置DAC的触发源为软件触发 DAC_InitStruct.DAC_Trigger = DAC_Trigger_Software; //配置生成波形为不生成 DAC_InitStruct.DAC_WaveGeneration = DAC_WaveGeneration_None; //波形生成幅度(此处无用) DAC_InitStruct.DAC_LFSRUnmask_TriangleAmplitude = DAC_LFSRUnmask_Bit0; //开启输出缓冲器 DAC_InitStruct.DAC_OutputBuffer = DAC_OutputBuffer_Enable; //初始化DAC DAC_Init(DAC_Channel_2, &DAC_InitStruct); //使能DAC DAC_Cmd(DAC_Channel_2, ENABLE); } /** * @摘要 设置DAC的输出电压 * @参数 DAC_Channel:指定DAC通道 * @参数 DAC_Align:指定数据对齐方式 * 可以为下列这些值 * @arg DAC_Align_8b_R: 8bit right data alignment selected * @arg DAC_Align_12b_L: 12bit left data alignment selected * @arg DAC_Align_12b_R: 12bit right data alignment selected * @参数 Data:写入保持寄存器的数据 * @返回值 无 * @说明 无 */ void MyDAC_SetData(uint32_t DAC_Channel, uint32_t DAC_Align, uint16_t Data) { if(DAC_Channel == DAC_Channel_1) DAC_SetChannel1Data(DAC_Align, Data); else if(DAC_Channel == DAC_Channel_2) DAC_SetChannel2Data(DAC_Align, Data); } /** * @摘要 软件触发DAC * @参数 无 * @返回值 无 * @说明 无 */ void MyDAC_SoftwareTrigger(uint32_t DAC_Channel) { DAC_SoftwareTriggerCmd(DAC_Channel, ENABLE); }
- MyDAC.h文件内容如下
#ifndef __MYDAC_H #define __MYDAC_H #include "stm32f4xx.h" // Device header void MyDAC_Init(void); void MyDAC_SetData(uint32_t DAC_Channel, uint32_t DAC_Align, uint16_t Data); void MyDAC_SoftwareTrigger(uint32_t DAC_Channel); #endif