How to: A/D Converter

Analog to digital converter can measure the voltage on the one of the six inputs A0 to A5 and return measured value. The result can be 16 bit value or float number in volts.

Channels and sampling types

The ADC subsystem has to be initialized by calling twr_adc_init(). Each channel can be configured to different resolution and oversampling. Sampling can be synchronous and asynchronous. No matter what resolution you choose (6, 8, 10, 12) the result is always scaled to 16 bit value 0-65535. In asynchronous mode you can also get value directly in volts in the float data type.

Synchronous sampling

During the synchronous measurement, the code is blocked until the measurement is over.

 1#include <application.h>
 2
 3void application_init(void)
 4{
 5    twr_log_init(TWR_LOG_LEVEL_DEBUG, TWR_LOG_TIMESTAMP_OFF);
 6
 7    twr_adc_init();
 8}
 9
10void application_task()
11{
12    uint16_t adc;
13
14    twr_adc_get_value(TWR_ADC_CHANNEL_A2, &adc);
15    twr_log_debug("%d", adc);
16
17    twr_scheduler_plan_current_relative(200);
18}

Asynchronous sampling

Asynchronous sampling is not blocked and is running in the background. When the result is ready, your callback function is called. It is possible to start multiple channels, the scheduler samples each channel and calls the callback for each channel separately.

 1#include <application.h>
 2
 3static void _adc_event_handler(twr_adc_channel_t channel, twr_adc_event_t event, void *param)
 4{
 5    (void) channel;
 6    (void) param;
 7
 8    if (event == TWR_ADC_EVENT_DONE)
 9    {
10        uint16_t adc;
11        twr_adc_async_get_value(TWR_ADC_CHANNEL_A2, &adc);
12        twr_log_debug("%d", adc);
13
14    //float voltage;
15    //twr_adc_get_result_voltage(TWR_ADC_CHANNEL_A2, &voltage);
16    //twr_log_debug("%f", voltage);
17    }
18}
19
20void application_init(void)
21{
22    twr_log_init(TWR_LOG_LEVEL_DEBUG, TWR_LOG_TIMESTAMP_OFF);
23
24    twr_adc_init();
25    twr_adc_set_event_handler(TWR_ADC_CHANNEL_A2, _adc_event_handler, NULL);
26    twr_adc_resolution_set(TWR_ADC_CHANNEL_A2, TWR_ADC_RESOLUTION_12_BIT);
27    twr_adc_oversampling_set(TWR_ADC_CHANNEL_A2, TWR_ADC_OVERSAMPLING_256);
28}
29
30void application_task()
31{
32    twr_adc_async_measure(TWR_ADC_CHANNEL_A2);
33
34    twr_scheduler_plan_current_relative(200);
35}