STM32之DAC例程

#include "stm32f10x.h"

/* RCC时钟配置 */
void RCC_config()
{ 
	ErrorStatus HSEStartUpStatus;

	/* RCC寄存器设置为默认配置 */
	RCC_DeInit();
	/* 打开外部高速时钟 */
	RCC_HSEConfig(RCC_HSE_ON);
	/* 等待外部高速时钟稳定 */
	HSEStartUpStatus = RCC_WaitForHSEStartUp();
	if(HSEStartUpStatus == SUCCESS) 
	{ 
		/* 设置HCLK = SYSCLK */
		RCC_HCLKConfig(RCC_SYSCLK_Div1);
		/* 设置PCLK2 = HCLK */
		RCC_PCLK2Config(RCC_HCLK_Div1);
		/* 设置PCLK1 = HCLK / 2 */
		RCC_PCLK1Config(RCC_HCLK_Div2);
//		/* 设置FLASH代码延时 */
//		FLASH_SetLatency(FLASH_Latency_2);
//		/* 使能预取址缓存 */
//		FLASH_PrefetchBufferCmd(FLASH_PrefetchBuffer_Enable);
		/* 设置PLL时钟源为HSE倍频9 72MHz */
		RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9);
		/* 使能PLL */
		RCC_PLLCmd(ENABLE);
		/* 等待PLL稳定 */
		while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET);
		/* 设置PLL为系统时钟源 */
		RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
		/* 等待系统时钟源切换到PLL */
		while(RCC_GetSYSCLKSource() != 0x08);
	}
}

/* GPIO配置 */
void GPIO_config()
{
	GPIO_InitTypeDef GPIO_InitStructure;

	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
 	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
 	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
 	GPIO_Init(GPIOA, &GPIO_InitStructure);
	GPIO_SetBits(GPIOA, GPIO_Pin_4);
}

/* DAC配置 */
void DAC_cofig(void)
{
	DAC_InitTypeDef DAC_InitType;

	/* 时钟初始化 */
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_DAC, ENABLE);
	
	/* 不使用触发功能 */
	DAC_InitType.DAC_Trigger = DAC_Trigger_None;
	/* 不使用波形发生器 */
	DAC_InitType.DAC_WaveGeneration = DAC_WaveGeneration_None;
	/* 屏蔽、幅值设置 */
	DAC_InitType.DAC_LFSRUnmask_TriangleAmplitude = DAC_LFSRUnmask_Bit0;
	/* 禁止输出缓冲区 */
	DAC_InitType.DAC_OutputBuffer = DAC_OutputBuffer_Disable;
	/* 初始化ADC通道 */
	DAC_Init(DAC_Channel_1, &DAC_InitType);

	/* ADC通道1使能 */
	DAC_Cmd(DAC_Channel_1, ENABLE);

	/* DAC值初始化为0 */
	DAC_SetChannel1Data(DAC_Align_12b_R, 0);
}

/* 毫秒延时 */
void delay_ms(uint16_t time)
{    
	uint16_t i = 0;

	while(time--)
	{
		i = 12000;
		while(i--);
	}
}

int main()
{
	uint16_t data = 2048;
	
	/* 时钟配置 */
	RCC_config();

	/* GPIO配置 */
	GPIO_config();

	/* DAC配置 */
	DAC_cofig();

	while(1)
	{
		DAC_SetChannel1Data(DAC_Align_12b_R, data);
		delay_ms(1000);
	}
}

猜你喜欢

转载自blog.csdn.net/lushoumin/article/details/87369883