#include "adc.h" #include "main.h" #include "network.h" #include "led.h" #include #include ADC_HandleTypeDef hadc1; void adcInit(void) { ADC_ChannelConfTypeDef sConfig = {0}; hadc1.Instance = ADC1; hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE; hadc1.Init.ContinuousConvMode = DISABLE; hadc1.Init.DiscontinuousConvMode = DISABLE; hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START; hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT; hadc1.Init.NbrOfConversion = 1; if (HAL_ADC_Init(&hadc1) != HAL_OK) Error_Handler(); sConfig.Channel = ADC_CHANNEL_0; sConfig.Rank = ADC_REGULAR_RANK_1; sConfig.SamplingTime = ADC_SAMPLETIME_1CYCLE_5; if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK) Error_Handler(); } uint16_t getAdc(void) { uint16_t adc_value = 0; HAL_ADC_Start(&hadc1); if (HAL_ADC_PollForConversion(&hadc1, 10) == HAL_OK) { adc_value = HAL_ADC_GetValue(&hadc1); } HAL_ADC_Stop(&hadc1); return adc_value; } void update_batter(void) { static _Bool powoff = 0; float batter_valtage; uint16_t adc_value; adc_value = getAdc(); batter_valtage = adc_value * (3.3 / 4096.0); batter_valtage = batter_valtage * 11.0; batter_valtage += 0.6; batter_valtage = 100 * (batter_valtage - 10.8) / (12.6 - 10.8); if (batter_valtage < 10 && powoff == 0) { log_info("> Low battery: %d%%", (int)batter_valtage); powoff = 1; NET_publish_power(0); } /* LED1: 低电量时常亮 */ if (powoff) LED1_ON; else LED1_OFF; }