#include "ch.h" // needs for all ChibiOS programs
#include "hal.h" // hardware abstraction layer header
#include "useAdc.h"
// Lets configure our ADC first
// ADCConfig structure for stm32 MCUs is empty
static ADCConfig adccfg = {};
// Create buffer to store ADC results. This is
// one-dimensional interleaved array
#define ADC_BUF_DEPTH 2 // depth of buffer
#define ADC_CH_NUM 2 // number of used ADC channels
static adcsample_t samples_buf[ADC_BUF_DEPTH * ADC_CH_NUM]; // results array
// Fill ADCConversionGroup structure fields
static ADCConversionGroup adccg = {
// this 3 fields are common for all MCUs
// set to TRUE if need circular buffer, set FALSE otherwise
TRUE,
// number of channels
(uint16_t)(ADC_CH_NUM),
// callback function, set to NULL for begin
NULL,
// error callback function
NULL,
// Resent fields are stm32 specific. They contain ADC control registers data.
// Please, refer to ST manual RM0008.pdf to understand what we do.
// CR1 register content, set to zero for begin
0,
// CR2 register content, set to zero for begin
0,
// SMRP1 register content, set to zero for begin
0,
// SMRP2 register content, set to zero for begin
0,
// SQR1 register content. Set channel sequence length
((ADC_CH_NUM - 1) << 20),
// SQR2 register content, set to zero for begin
0,
// SQR3 register content. We must select 2 channels
// For example 2nd and 3rd channels. Refer to the
// pinout of your MCU to select other pins you need.
// On STM32-P103 board they connected to PA2 and PA3 contacts
(2 | (3 << 5)),
};
// Thats all with configuration
void useAdc(void)
{
// Following 3 functions use previously created configuration
// to initialize ADC block, start ADC block and start conversion.
// &ADCD1 is pointer to ADC driver structure, defined in the depths of HAL.
// Other arguments defined ourself earlier.
adcStart(&ADCD1, &adccfg);
adcStartConversion(&ADCD1, &adccg, &samples_buf[0], ADC_BUF_DEPTH);
// samples in to buffer
}
adcsample_t getAdc(uint8_t chan)
{
return(samples_buf[chan & 1]);
}