如何讓STM32的PWM DAC輸出幅值在0-5V的
- #include "stm32f10x.h"
- //DAC通道1輸出初始化
- void Dac1_Init(void)
- {
- GPIO_InitTypeDef GPIO_InitStructure;
- DAC_InitTypeDef DAC_InitType;
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE ); //使能PORTA通道時鐘
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_DAC, ENABLE ); //使能DAC通道時鐘
- 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) ;//PA.4 輸出高
- DAC_InitStruct.DAC_Trigger = DAC_Trigger_Software; //觸發方式改為軟件觸發
- DAC_InitType.DAC_Trigger=DAC_Trigger_None; //不使用觸發功能 TEN1=0
- DAC_InitType.DAC_WaveGeneration=DAC_WaveGeneration_None;//不使用波形發生
- DAC_InitType.DAC_LFSRUnmask_TriangleAmplitude=DAC_LFSRUnmask_Bit0;//屏蔽、幅值設置
- DAC_InitType.DAC_OutputBuffer=DAC_OutputBuffer_Disable ; //DAC1輸出緩存關閉 BOFF1=1
- //DAC_InitType.DAC_OutputBuffer=DAC_OutputBuffer_Enable;
- DAC_Init(DAC_Channel_1,&DAC_InitType); //初始化DAC通道1
- DAC_Cmd(DAC_Channel_1, ENABLE); //使能DAC1
- DAC_SetChannel1Data(DAC_Align_12b_R, 0); //12位右對齊數據格式設置DAC值
- DAC_SoftwareTriggerCmd(DAC_Channel_1,ENABLE);
- }
- //設置通道1輸出電壓
- //vol:0~3300,代表0~3.3V
- void Dac1_Set_Vol(u16 vol)
- {
- float temp=vol;
- temp/=1000;
- temp=temp*4095/3.3;
- DAC_SetChannel1Data(DAC_Align_12b_R,temp);//12位右對齊數據格式設置DAC值
- DAC_SoftwareTriggerCmd(DAC_Channel_1,ENABLE);
- }
- int main()
- {
- Dac1_Init();
- while(1)
- {
- int NUM=0;
- Dac1_Set_Vol(3300);
- DAC_SoftwareTriggerCmd(DAC_Channel_1,ENABLE);
- NUM=DAC_GetDataOutputValue(DAC_Channel_1);
- }
- }
- /**
- * @brief Inserts a delay time.
- * @param nCount: specifies the delay time length.
- * @retval None
- */
- void Delay(__IO uint32_t nCount)
- {
- for(; nCount != 0; nCount--);
- }
- #ifdef USE_FULL_ASSERT
- /**
- * @brief Reports the name of the source file and the source line number
- * where the assert_param error has occurred.
- * @param file: pointer to the source file name
- * @param line: assert_param error line source number
- * @retval None
- */
- void assert_failed(uint8_t* file, uint32_t line)
- {
- /* User can add his own implementation to report the file name and line number,
- ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
- /* Infinite loop */
- while (1)
- {
- }
- }
- #endif
復制代碼 |