|
|
|
@@ -11,6 +11,11 @@ extern "C" {
|
|
|
|
|
extern void ErrorMsgHandler(const char * msg);
|
|
|
|
|
|
|
|
|
|
// -------------------------- Analog read -------------------------- //
|
|
|
|
|
#define ADC_SAMPLES_QTY 10 // samples quantity for averaging adc results
|
|
|
|
|
#define ADC_DEFAULT_RESOLUTION 10 // resolution for arduino compatibility
|
|
|
|
|
|
|
|
|
|
uint8_t currentResolution = ADC_DEFAULT_RESOLUTION; // resolution used for output results
|
|
|
|
|
|
|
|
|
|
// structure for ADC channel initialization. Only the channel number
|
|
|
|
|
// changes, everything else is the same
|
|
|
|
|
static ADC_HandleTypeDef hadc =
|
|
|
|
@@ -21,6 +26,16 @@ static ADC_HandleTypeDef hadc =
|
|
|
|
|
.Init.Sel = 0
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
void analogReadResolution(uint8_t resolution)
|
|
|
|
|
{
|
|
|
|
|
// resolution limits
|
|
|
|
|
if (resolution > 32) resolution = 32;
|
|
|
|
|
if (resolution < 1) resolution = 1;
|
|
|
|
|
|
|
|
|
|
// save new resolution
|
|
|
|
|
currentResolution = resolution;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// initialize the channel, run a single measurement, wait for the result
|
|
|
|
|
uint32_t analogRead(uint32_t PinNumber)
|
|
|
|
|
{
|
|
|
|
@@ -44,11 +59,31 @@ uint32_t analogRead(uint32_t PinNumber)
|
|
|
|
|
hadc.Init.Sel = adcChannel;
|
|
|
|
|
HAL_ADC_Init(&hadc);
|
|
|
|
|
|
|
|
|
|
// start the conversion twice in case another channel was polled before
|
|
|
|
|
// start the dummy conversion in case another channel was polled before
|
|
|
|
|
HAL_ADC_SINGLE_AND_SET_CH(hadc.Instance, adcChannel);
|
|
|
|
|
value = HAL_ADC_WaitAndGetValue(&hadc);
|
|
|
|
|
HAL_ADC_Single(&hadc);
|
|
|
|
|
value = HAL_ADC_WaitAndGetValue(&hadc);
|
|
|
|
|
HAL_ADC_WaitAndGetValue(&hadc);
|
|
|
|
|
|
|
|
|
|
// accumulate results
|
|
|
|
|
uint32_t acc = 0;
|
|
|
|
|
for (uint8_t i = 0; i<ADC_SAMPLES_QTY; i++)
|
|
|
|
|
{
|
|
|
|
|
HAL_ADC_Single(&hadc);
|
|
|
|
|
acc += HAL_ADC_WaitAndGetValue(&hadc);
|
|
|
|
|
}
|
|
|
|
|
// get value by averaging with MCU_ADC_RESOLUTION
|
|
|
|
|
value = acc/ADC_SAMPLES_QTY;
|
|
|
|
|
|
|
|
|
|
// map value to selected resolution
|
|
|
|
|
if (currentResolution > MCU_ADC_RESOLUTION)
|
|
|
|
|
{
|
|
|
|
|
// extra least significant bits are padded with zeros
|
|
|
|
|
value = (value << (currentResolution - MCU_ADC_RESOLUTION));
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
// extra least significant bits read from the ADC are discarded
|
|
|
|
|
value = (value >> (MCU_ADC_RESOLUTION - currentResolution));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
ErrorMsgHandler("analogRead(): invalid analog pin number");
|
|
|
|
|