BearPi Std 板从入门到放弃 - 引气入体篇(9)(DAC->ADC)
简介
结合 BearPi Std 板从入门到放弃 - 引气入体篇(7)(DAC) 和 BearPi Std 板从入门到放弃 - 引气入体篇(8)(ADC) 这两篇, 实现 D -> A -> D 的转换, 也就是DAC -> ADC;
开发板 : Bearpi Std(小熊派标准板)
主芯片: STM32L431RCT6
LED : PC13 \ 推挽输出即可 \ 高电平点亮
串口: Usart1
KEY1 : PB2 \ 上拉 \ 按下下降沿触发(一次)\ 用于增值
KEY2 : PB3 \ 上拉 \ 按下下降沿触发(一次) \ 用于减值
DAC1: PA5
ADC1: PC2
步骤
- 创建工程及初始化相关功能;
- 生成项目BearPi_DAC1_ADC1
- 添加用户代码
int main()
{
/* USER CODE BEGIN 1 */
int16_t adcValue = 0;
int16_t dacValue = 0;
float voltage = 0.0;
/* USER CODE END 1 */
...
/* USER CODE BEGIN 2 */
HAL_DAC_Start(&hdac1, DAC_CHANNEL_2); // 开启DAC通道
HAL_ADC_Start_DMA(&hadc1, (uint32_t*)&adcValue, 1); // 开启ADC
/* USER CODE END 2 */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
if (HAL_GPIO_ReadPin(USER_KEY1_GPIO_Port, USER_KEY1_Pin) == GPIO_PIN_RESET)
{
HAL_Delay(100); //
if (HAL_GPIO_ReadPin(USER_KEY1_GPIO_Port, USER_KEY1_Pin) == GPIO_PIN_RESET)
{
dacValue += 10;
if(dacValue > 4095)
{
dacValue = 4095;
}
HAL_DAC_SetValue(&hdac1, DAC_CHANNEL_2, DAC_ALIGN_12B_R, dacValue);
voltage = adcValue*3.3/4095;
printf(" KEY1+ DACvalue: %d, ADCValue: %d, Voltage:%3.3f\r\n", dacValue, adcValue, voltage);
}
}
if (HAL_GPIO_ReadPin(USER_KEY2_GPIO_Port, USER_KEY2_Pin) == GPIO_PIN_RESET)
{
HAL_Delay(100); //
if (HAL_GPIO_ReadPin(USER_KEY2_GPIO_Port, USER_KEY2_Pin) == GPIO_PIN_RESET)
{
dacValue -= 10;
if (dacValue < 0)
{
dacValue = 0;
}
HAL_DAC_SetValue(&hdac1, DAC_CHANNEL_2, DAC_ALIGN_12B_R, dacValue);
voltage = adcValue*3.3/4095;
printf(" KEY2- DACvalue: %d, ADCValue: %d, Voltage:%3.3f\r\n", dacValue, adcValue, voltage);
}
}
HAL_Delay(100);
}
/* USER CODE END 3 */
}
- 打开串口软件进行监控, 排线连接PC2 和 PA5
- 按键控制实现设置D值(DAC)与读取D值(ADC)的变化;
BearPi_DAC1_ADC1 完整项目代码