dev_beta_adcTest #2

Merged
klassents merged 2 commits from dev_beta_adcTest into dev_beta 2024-09-12 06:46:32 +03:00
3 changed files with 47 additions and 4 deletions

View File

@ -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");

View File

@ -16,6 +16,13 @@ extern "C" {
*/
uint32_t analogRead(uint32_t PinNumber);
/*
* \brief Set the resolution of adc results. Default is 10 bits (range from 0 to 1023).
*
* \param resolution 1...32
*/
void analogReadResolution(uint8_t resolution);
/*
* \brief Writes an analog value (PWM wave) to a pin.
*

View File

@ -71,6 +71,7 @@ volatile uint32_t* portInputRegister(GPIO_TypeDef* GPIO_x);
#define SERIAL_PORT_QTY 2
// ADC
#define MCU_ADC_RESOLUTION 12 // bits
// determines the ADC channel number by the board pin number
uint32_t analogInputToChannelNumber(uint32_t PinNumber);