一、实现代码
#include "main.h"
#include "adc.h"
#include "usart.h"
#include "gpio.h"
#include "stm32f1xx_hal.h"
#include <string.h>
#include <stdio.h>
void SystemClock_Config(void);
int main(void)
{
uint32_t adc_value; // ADC原始值(0-4095)
float voltage; // 电压值(0-3.3V)
char uart_buf[100]; // UART发送缓冲区
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_ADC1_Init();
MX_USART1_UART_Init();
while (1)
{
/* 启动ADC转换 */
if (HAL_ADC_Start(&hadc1) == HAL_OK) {
/* 等待转换完成(超时100ms) */
if (HAL_ADC_PollForConversion(&hadc1, 100) == HAL_OK) {
adc_value = HAL_ADC_GetValue(&hadc1); // 读取ADC值
voltage = (adc_value * 3.3f) / 4095.0f; // 转换为电压(3.3V参考)
/* 格式化基础信息 */
sprintf(uart_buf, "ST-5L5B (PC5): ADC=%d, Voltage=%.2fV | ", adc_value, voltage);
/* 判断红外光强度(阈值需实际校准) */
if (adc_value < 1000) {
strcat(uart_buf, "Weak infrared (low intensity)\r\n"); // 红外光弱
} else if (adc_value < 3000) {
strcat(uart_buf, "Moderate infrared intensity\r\n"); // 强度中等
} else {
strcat(uart_buf, "Strong infrared (high intensity)\r\n"); // 红外光强
}
/* 通过UART1发送数据 */
HAL_UART_Transmit(&huart1, (uint8_t*)uart_buf, strlen(uart_buf), 100);
}
}
HAL_ADC_Stop(&hadc1); // 停止ADC
HAL_Delay(1000); // 每500ms采集一次
}
}
int fputc(int ch, FILE *f)
{
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 500);
return ch;
}

原理图及参考手册:https://pan.baidu.com/s/1O9LNB4pi_CoMYQlFxnAu-w?pwd=xwud 提取码: xwud