Skip to content

Commit

Permalink
Add optional conversion complete callback to AdcHandle::Start()
Browse files Browse the repository at this point in the history
  • Loading branch information
TheSlowGrowth committed Jul 25, 2024
1 parent 8d106a2 commit 4fdf54c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
24 changes: 21 additions & 3 deletions src/per/adc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,8 @@ struct dsy_adc
ADC_HandleTypeDef hadc1;
DMA_HandleTypeDef hdma_adc1;
bool mux_used; // flag set when mux is configured
AdcHandle::ConversionCompleteCallbackFunctionPtr complete_callback;
void* complete_callback_context;
};

// Static Functions
Expand Down Expand Up @@ -350,6 +352,10 @@ void AdcHandle::Init(AdcChannelConfig* cfg,
{
adc.hadc1.Init.OversamplingMode = DISABLE;
}

adc.complete_callback = nullptr;
adc.complete_callback_context = nullptr;

// Init ADC
if(HAL_ADC_Init(&adc.hadc1) != HAL_OK)
{
Expand Down Expand Up @@ -421,8 +427,12 @@ void AdcHandle::Init(AdcChannelConfig* cfg,
}
}

void AdcHandle::Start()
void AdcHandle::Start(ConversionCompleteCallbackFunctionPtr callback,
void* callback_context)
{
adc.complete_callback = callback;
adc.complete_callback_context = callback_context;

HAL_ADCEx_Calibration_Start(
&adc.hadc1, ADC_CALIB_OFFSET_LINEARITY, ADC_SINGLE_ENDED);
HAL_ADC_Start_DMA(&adc.hadc1, (uint32_t*)adc.dma_buffer, adc.channels);
Expand Down Expand Up @@ -580,9 +590,17 @@ extern "C"

void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
{
if(hadc->Instance == ADC1 && adc.mux_used)
if(hadc->Instance == ADC1)
{
adc_internal_callback();
if(adc.mux_used)
{
adc_internal_callback();
}

if(adc.complete_callback)
{
adc.complete_callback(adc.complete_callback_context);
}
}
}

Expand Down
14 changes: 12 additions & 2 deletions src/per/adc.h
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,9 @@ class AdcHandle
OVS_LAST, /**< & */
};

/** A callback to be executed after a conversion is completed. */
typedef void (*ConversionCompleteCallbackFunctionPtr)(void *context);

AdcHandle() {}
~AdcHandle() {}
/**
Expand All @@ -117,8 +120,15 @@ class AdcHandle
void
Init(AdcChannelConfig *cfg, size_t num_channels, OverSampling ovs = OVS_32);

/** Starts reading from the ADC */
void Start();
/** Starts reading from the ADC.
\param callback an optional callback to be called when a conversion is
complete on all ADC channels. Note that if a mux is used on
a ADC channel, only one of the muxed inputs will have a new
value when this callback is called.
\param callback_context a context pointer that will be handed to the callback
*/
void Start(ConversionCompleteCallbackFunctionPtr callback = nullptr,
void *callback_context = nullptr);

/** Stops reading from the ADC */
void Stop();
Expand Down

0 comments on commit 4fdf54c

Please sign in to comment.