Files
cls_master/Application/BSP/BSP_ADC.c
2024-05-23 02:15:36 +02:00

92 lines
2.4 KiB
C

#include "main.h"
#include "BSP_ADC.h"
#include "adc.h"
#include "stdbool.h"
#define TOTAL_ADC_CHANNELS 4
#define ADC_HISTORY_SIZE 4
#define ADC_BUFFER_SIZE (TOTAL_ADC_CHANNELS * ADC_HISTORY_SIZE)
#define ADC_CONVERTED_DATA_BUFFER_SIZE ((uint32_t) ADC_BUFFER_SIZE) /* Size of array aADCxConvertedData[] */
ALIGN_32BYTES (static uint16_t aADCxConvertedData[ADC_CONVERTED_DATA_BUFFER_SIZE]);
#define ADC_CHANNEL_DIMMER 1
#define ADC_CHANNEL_BUS 3
static bool adcIsInitialized = false;
//start the ADC conversion
void BSP_ADC_Start()
{
if (HAL_ADCEx_Calibration_Start(&hadc1, ADC_CALIB_OFFSET_LINEARITY, ADC_SINGLE_ENDED) != HAL_OK)
{
Error_Handler();
}
if (HAL_ADC_Start_DMA(&hadc1,
(uint32_t *)aADCxConvertedData,
ADC_CONVERTED_DATA_BUFFER_SIZE
) != HAL_OK)
{
Error_Handler();
}
adcIsInitialized = true;
}
/**
* @brief Conversion complete callback in non-blocking mode
* @param hadc: ADC handle
* @retval None
*/
void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc)
{
/* Invalidate Data Cache to get the updated content of the SRAM on the first half of the ADC converted data buffer: 32 bytes */
//SCB_InvalidateDCache_by_Addr((uint32_t *) &aADCxConvertedData[0], ADC_CONVERTED_DATA_BUFFER_SIZE);
}
/**
* @brief Conversion DMA half-transfer callback in non-blocking mode
* @param hadc: ADC handle
* @retval None
*/
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
{
/* Invalidate Data Cache to get the updated content of the SRAM on the second half of the ADC converted data buffer: 32 bytes */
//SCB_InvalidateDCache_by_Addr((uint32_t *) &aADCxConvertedData[ADC_CONVERTED_DATA_BUFFER_SIZE/2], ADC_CONVERTED_DATA_BUFFER_SIZE);
}
float BSP_ADC_ReadValue( uint32_t channel, float factor) {
if (!adcIsInitialized) {
return 0;
}
// average the last 4 values of the dimmer ADC
uint32_t sum = 0;
for (int i = 0; i < ADC_HISTORY_SIZE; i++) {
sum += aADCxConvertedData[channel + i * TOTAL_ADC_CHANNELS];
}
//convert raw ADC value to voltage
float voltage = (float)sum / (float)ADC_HISTORY_SIZE / factor; // gemessan an sample pcb
return voltage;
}
float BSP_ADC_ReadDimmerValue() {
return BSP_ADC_ReadValue(ADC_CHANNEL_DIMMER, 4319.619048);
}
float BSP_ADC_ReadBusValue() {
return BSP_ADC_ReadValue(ADC_CHANNEL_BUS, 4046.87186);
}