STM32G031 输出正弦波代码
时间: 2023-06-26 11:10:32 浏览: 165
STM32G031x4x6x8 数据手册.pdf
以下是基于STM32G031的DAC实现正弦波输出的代码示例:
```
#include "stm32g0xx_hal.h"
#include <math.h>
#define DAC_RESOLUTION 4096 // DAC 分辨率
#define PI 3.14159265f // 圆周率
DAC_HandleTypeDef hdac1;
float sineTable[360]; // 正弦波表
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DAC1_Init(void);
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_DAC1_Init();
// 生成正弦波表
for(int i = 0; i < 360; i++){
sineTable[i] = sin(i * PI / 180.0f) * (DAC_RESOLUTION / 2 - 1) + DAC_RESOLUTION / 2;
}
while (1)
{
// 输出正弦波
for(int i = 0; i < 360; i++){
HAL_DAC_SetValue(&hdac1, DAC_CHANNEL_1, DAC_ALIGN_12B_R, (uint32_t)sineTable[i]);
HAL_Delay(1);
}
}
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
__HAL_RCC_SYSCFG_CLK_ENABLE();
__HAL_RCC_PWR_CLK_ENABLE();
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL6;
RCC_OscInitStruct.PLL.PLLDIV = RCC_PLL_DIV3;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
| RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
{
Error_Handler();
}
}
static void MX_DAC1_Init(void)
{
DAC_ChannelConfTypeDef sConfig = {0};
__HAL_RCC_DAC1_CLK_ENABLE();
hdac1.Instance = DAC1;
if (HAL_DAC_Init(&hdac1) != HAL_OK)
{
Error_Handler();
}
sConfig.DAC_Trigger = DAC_TRIGGER_NONE;
sConfig.DAC_OutputBuffer = DAC_OUTPUTBUFFER_ENABLE;
if (HAL_DAC_ConfigChannel(&hdac1, &sConfig, DAC_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
}
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
__HAL_RCC_GPIOA_CLK_ENABLE();
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_RESET);
GPIO_InitStruct.Pin = GPIO_PIN_4;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
```
代码中生成了一个包含360个正弦波采样值的表,然后在主循环中输出正弦波。每个采样值都通过HAL_DAC_SetValue函数写入DAC并延迟1毫秒,以保证输出的正弦波频率为1kHz。你可以根据需要调整正弦波频率,方法是改变延迟时间或修改正弦波表。
另外,代码中使用了HAL库进行初始化和控制DAC输出。如果你不习惯使用HAL库,也可以直接操作相关寄存器。
阅读全文