You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
95 lines
2.1 KiB
95 lines
2.1 KiB
#include "zadc.hpp"
|
|
#ifdef HAL_ADC_MODULE_ENABLED
|
|
using namespace iflytop;
|
|
#define TAG "ADC"
|
|
|
|
zmutex g_adc_mutex = {"G_ADC_MUTEX"};
|
|
|
|
void ZADC::initialize(const char* name, ADC_HandleTypeDef* hadc1, int32_t channel, int32_t samplingTime) {
|
|
if (!hadc1) return;
|
|
m_hadc1 = hadc1;
|
|
m_channel = channel;
|
|
m_samplingTime = samplingTime;
|
|
inited = true;
|
|
m_name = name;
|
|
m_mutex.init();
|
|
if (!g_adc_mutex.isInit()) {
|
|
g_adc_mutex.init();
|
|
}
|
|
}
|
|
|
|
int32_t ZADC::get_adc_value() {
|
|
if (!inited) return 0;
|
|
zlock_guard lck(g_adc_mutex);
|
|
|
|
ADC_ChannelConfTypeDef sConfig = {0};
|
|
sConfig.Channel = m_channel; /* 通道 */
|
|
sConfig.Rank = 1;
|
|
sConfig.SamplingTime = m_samplingTime; /* 采样时间 */
|
|
|
|
if (HAL_ADC_ConfigChannel(m_hadc1, &sConfig) != HAL_OK) {
|
|
ZLOGE(TAG, "%s HAL_ADC_ConfigChannel failed", m_name);
|
|
return -1;
|
|
}
|
|
if (HAL_ADC_Start(m_hadc1) != HAL_OK) {
|
|
ZLOGE(TAG, "%s HAL_ADC_Start failed", m_name);
|
|
return -1;
|
|
}
|
|
HAL_ADC_PollForConversion(m_hadc1, 10);
|
|
uint16_t adcv = HAL_ADC_GetValue(m_hadc1);
|
|
HAL_ADC_Stop(m_hadc1);
|
|
|
|
// ZLOGI(TAG, "%s ADC Value: %d", m_name, adcv);
|
|
return adcv;
|
|
}
|
|
|
|
int32_t ZADC::get_adc_af_filter() {
|
|
if (!inited) return 0;
|
|
|
|
int32_t adc_value[14] = {0};
|
|
|
|
for (int i = 0; i < 14; i++) {
|
|
adc_value[i] = get_adc_value();
|
|
osDelay(1);
|
|
}
|
|
|
|
// 排序
|
|
for (int i = 0; i < 14; i++) {
|
|
for (int j = 0; j < 14 - i - 1; j++) {
|
|
if (adc_value[j] > adc_value[j + 1]) {
|
|
int temp = adc_value[j];
|
|
adc_value[j] = adc_value[j + 1];
|
|
adc_value[j + 1] = temp;
|
|
}
|
|
}
|
|
}
|
|
|
|
// 求平均
|
|
int sum = 0;
|
|
for (int i = 2; i < 12; i++) {
|
|
sum += adc_value[i];
|
|
}
|
|
return sum / 10;
|
|
}
|
|
|
|
void ZADC::setCacheVal(int32_t val) {
|
|
if (!inited) return;
|
|
{
|
|
zlock_guard lck(m_mutex);
|
|
m_cacheVal = val;
|
|
}
|
|
}
|
|
int32_t ZADC::getCacheVal() {
|
|
if (!inited) return 0;
|
|
{
|
|
zlock_guard lck(m_mutex);
|
|
return m_cacheVal;
|
|
}
|
|
}
|
|
|
|
void ZADC::updateAdcValToCache() {
|
|
if (!inited) return;
|
|
setCacheVal(get_adc_af_filter());
|
|
}
|
|
|
|
#endif
|