peripheral/adc/main.c

/*******************************************************************************
* # License
* Copyright 2019 Silicon Laboratories Inc. www.silabs.com
*******************************************************************************
*
* The licensor of this software is Silicon Laboratories Inc. Your use of this
* software is governed by the terms of Silicon Labs Master Software License
* Agreement (MSLA) available at
* www.silabs.com/about-us/legal/master-software-license-agreement. This
* software is distributed to you in Source Code format and is governed by the
* sections of the MSLA applicable to Source Code.
*
******************************************************************************/
/* Documentation for this app is available online.
* See https://docs.silabs.com/gecko-os/4/standard/latest/sdk/examples/peripheral/adc
*/
#include "gos.h"
#define PLATFORM_ADC_MAX_RESOLUTION 12
#define ADC_SAMPLE_PERIOD_MS (1000)
#define APPLICATION_START_LINE "Starting ADC app"
#if PLATFORM_ADC_MAX_RESOLUTION == 12
#define LUT_FILENAME "lut_12bit.csv"
#else
#define LUT_FILENAME "lut_10bit.csv"
#endif
static gos_adc_lut_t adc_lut;
static const gos_adc_config_t adc_config =
{
.resolution = 12
};
/*************************************************************************************************/
void gos_app_init(void)
{
GOS_LOG(APPLICATION_START_LINE);
gos_result_t result;
if (GOS_FAILED(result, gos_adc_init(PLATFORM_STD_ADC, &adc_config)))
{
GOS_LOG("Failed to initialise ADC!");
return;
}
GOS_LOG("Preparing lookup table: %s", LUT_FILENAME);
if (GOS_FAILED(result, gos_adc_prepare_lut(LUT_FILENAME, &adc_lut)))
{
GOS_LOG("Failed to prepare lookup table! Error code %d", result);
return;
}
result = gos_event_register_periodic(sample_loop, NULL, ADC_SAMPLE_PERIOD_MS, GOS_EVENT_FLAG_RUN_NOW);
if (result == GOS_SUCCESS)
{
GOS_LOG("Taking direct samples");
return;
}
else
{
GOS_LOG("Failed to setup periodic sampling events");
}
}
/*************************************************************************************************/
void gos_app_deinit(void)
{
gos_result_t result;
GOS_LOG("Removing lookup table...");
if (GOS_FAILED(result, gos_adc_destroy_lut(adc_lut)))
{
GOS_LOG("Failed to remove lookup table! Error code %d", result);
}
else
{
GOS_LOG("Finished");
}
}
/*************************************************************************************************/
static void sample_loop(void *unused)
{
gos_result_t result;
uint16_t adc_raw = 0;
float adc_converted;
if (GOS_FAILED(result, gos_adc_sample(PLATFORM_STD_ADC, &adc_raw, GOS_ADC_SAMPLE_TYPE_RAW)))
{
GOS_LOG("Failed to read direct sample! Error code %d", result);
}
if (GOS_FAILED(result, gos_adc_sample_and_convert(PLATFORM_STD_ADC, adc_lut, &adc_converted)))
{
GOS_LOG("Failed to read converted sample! Error code %d", result);
}
else
{
char number_str[32];
GOS_LOG("ADC value is %s (0x%X)", float_to_str(adc_converted, number_str, 4), adc_raw);
}
}