在項目中偶爾會使用DA轉換器,我使用的MCU是STM8L151G6U6。我是用的是PB4作爲DA輸出管腳,查閱該芯片的Reference manual手冊可知,PB4是屬於DAC_OUT1,即DAC通道一。
再查閱PB4輸入輸出控制,PB4對應的是開關15。
下面是我用軟件觸發模式使用的DAC配置代碼。
dac.h頭文件代碼如下:
#ifndef __DAC_H__
#define __DAC_H__
#ifdef __cplusplus
extern "C"{
#endif
#include "stm8l15x.h"
/* DAC_OUT ---> PB4(DAC_OUT) */
#define DAC_OUT_PORT (GPIOB)
#define DAC_OUT_PIN (GPIO_Pin_4)
/* Function prototype */
void DAC_Init(void);
#ifdef __cplusplus
}
#endif
#endif /* End define macro __DAC_H__ */
dac.c源文件代碼如下:
#include "dac.h"
/*
** @ Brief: Init DAC
** @ Parameter: None
** @ Return: None
**/
void DAC_Init(void)
{
/* Configure DAC GPIO pin */
GPIO_Init(DAC_OUT_PORT, DAC_OUT_PIN, GPIO_Mode_In_FL_No_IT);
/* Enable comparator clock */
CLK_PeripheralClockConfig(CLK_Peripheral_COMP,ENABLE);
/* Enable DAC Clock */
CLK_PeripheralClockConfig(CLK_Peripheral_DAC, ENABLE);
/* Enable PB4 input output switch */
SYSCFG_RIIOSwitchConfig(RI_IOSwitch_15, ENABLE);
/* Init DAC channel 1 output and enable output buffer */
DAC_DeInit();
DAC_Init(DAC_Channel_1, DAC_Trigger_Software, DAC_OutputBuffer_Enable);
/* Enable the selected DAC channel wave generation */
DAC_WaveGenerationCmd(DAC_Channel_1, DAC_Wave_Triangle, ENABLE);
/* Select DAC Triangle Wave Generation Amplitude according to the specified parameters */
DAC_SetTriangleWaveAmplitude(DAC_Channel_1, DAC_TriangleAmplitude_4095);
/* Enables the specified DAC channel. */
DAC_Cmd(DAC_Channel_1, ENABLE);
}
在main.c中,使用DAC轉換器的代碼如下;
#include "dac.h"
void main(void)
{
uint16_t DACData = 0;
DAC_Init();
while(1)
{
for(DACData = 0; DACData < 4096; DACData++)
{
DAC_SetChannel1Data(DAC_Align_12b_R, DACData);
DAC_SoftwareTriggerCmd(DAC_Channel_1, ENABLE);
}
}
}
用示波器測量PB4會發現,電壓值從小到大循環往復。轉換關係爲:
輸出電壓 = DACData * 參考電壓 / 4096;
其中4096爲DAC觸發振幅,由初始化參數DAC_TriangleAmplitude_4095設定,可以更改;DACData爲輸入的需要轉換的值,範圍0~觸發振幅(這裏爲4096);參考電壓一般爲板子工作的所需的正常電壓,我的爲3.3V。