shuichan_old/V1.4-Chinese/STM32F103_App1/HardWare/ADC/adc.c

76 lines
2.3 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "adc.h"
#include "main.h"
#include "network.h"
#include "led.h"
#include "reset_log.h"
#include <string.h>
#include <stdio.h>
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;
static uint8_t low_cnt = 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);
/* 限幅 0~100%:法拉电容放电时 3.3V 基准下跌ADC 读数失真可能算出负数 */
if (batter_valtage < 0) batter_valtage = 0;
if (batter_valtage > 100) batter_valtage = 100;
/* 连续 3 次低于 10% 才判定(去抖),防止单次采样毛刺误判 */
if (batter_valtage < 10) {
if (low_cnt < 3) low_cnt++;
} else {
low_cnt = 0;
}
if (low_cnt >= 3 && powoff == 0) {
powoff = 1;
log_info("> 电量低: %d%%", (int)batter_valtage);
NET_publish_power(0);
/* 电量 <10% 基本等同外部 12V 断开(法拉电容续航约 30s
* 立即写断电记录(含当前运行时长),随后复位:
* BootLoader 会检测主电源12V 未恢复前不跳 APP防止外设没上电时程序乱跑 */
reset_log_power_loss();
HAL_Delay(200);
NVIC_SystemReset();
}
/* LED1: 低电量时常亮 */
if (powoff) LED1_ON; else LED1_OFF;
}