tips:可以不用开启过采样
adc读取函数
float adc_read(ADC_HandleTypeDef *hadc)
{uint16_t adc_val;float adc_f;HAL_ADC_Start (hadc);adc_val = HAL_ADC_GetValue(hadc);adc_f = adc_val*3.3f/4096.0f;return adc_f;
}
setup()初始化
HAL_ADCEx_Calibration_Start(&hadc2 ,ADC_SINGLE_ENDED);//ADC自动校准
调用函数并显示
float adc_data_PB15;adc_data_PB15 = adc_read(&hadc2);sprintf(text," PB15:%.4f V ",adc_data_PB15);LCD_DisplayStringLine(Line4,(uint8_t *)text);
all.c
#include "all.h"uint8_t led_sta=0x20;//LED初始化参数
extern struct Bkeys bkey[];//按键存储
char text[30]; //存放显示文本void LED_Disp(uint8_t dsLED)//LED控制
{HAL_GPIO_WritePin(GPIOC,GPIO_PIN_All,GPIO_PIN_SET);//所有LED熄灭HAL_GPIO_WritePin(GPIOC,dsLED<<8,GPIO_PIN_RESET);//左移8位。控制C8~C15引脚,值为1的点亮HAL_GPIO_WritePin(GPIOD,GPIO_PIN_2,GPIO_PIN_SET);//开锁存器HAL_GPIO_WritePin(GPIOD,GPIO_PIN_2,GPIO_PIN_RESET);//关锁存器
}
void LED_Chg(uint8_t num,uint8_t sta)//单独控制一个LED
{uint8_t pos = 0x01<<(num-1);led_sta =(led_sta&(~pos))|(pos*sta);LED_Disp(led_sta);
}float adc_read(ADC_HandleTypeDef *hadc)
{uint16_t adc_val;float adc_f;HAL_ADC_Start (hadc);adc_val = HAL_ADC_GetValue(hadc);adc_f = adc_val*3.3f/4096.0f;return adc_f;
}void setup()
{HAL_TIM_Base_Start_IT(&htim6);//开启TIMHAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_2);//产生PWMHAL_TIM_IC_Start(&htim15,TIM_CHANNEL_1);//打开pwm捕获HAL_TIM_IC_Start(&htim15,TIM_CHANNEL_2);//打开pwm捕获HAL_ADCEx_Calibration_Start(&hadc2 ,ADC_SINGLE_ENDED);//ADC自动校准//LED初始状态LED_Disp(0x00);//LCD初始化LCD_Init();LCD_Clear(Black );LCD_SetBackColor(Black);LCD_SetTextColor(White);
}void loop()
{//PWM捕获float frq1 = 0;float duty1 = 0;frq1 = 1000000.0f/(HAL_TIM_ReadCapturedValue(&htim15,TIM_CHANNEL_1)+1);//获取频率duty1 = ((HAL_TIM_ReadCapturedValue(&htim15,TIM_CHANNEL_2)+1)*100.f/(HAL_TIM_ReadCapturedValue(&htim15,TIM_CHANNEL_1)+1));//获取占空比sprintf(text," FQR:%.2f Hz ",frq1);LCD_DisplayStringLine(Line2,(uint8_t *)text);sprintf(text," DUTY:%.2f %% ",duty1);LCD_DisplayStringLine(Line3,(uint8_t *)text);//ADCfloat adc_data_PB15;adc_data_PB15 = adc_read(&hadc2);sprintf(text," PB15:%.4f V ",adc_data_PB15);LCD_DisplayStringLine(Line4,(uint8_t *)text);if(bkey[1].short_flag==1){LED_Chg(1,1);sprintf(text," down! ");LCD_DisplayStringLine(Line1,(uint8_t *)text);bkey[1].short_flag = 0;}if(bkey[1].long_flag==1){LED_Chg(2,1);sprintf(text," long_down! ");LCD_DisplayStringLine(Line1,(uint8_t *)text);}}void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)//按键服务
{if(htim->Instance == TIM6)key_serv();}