/*
 * Copyright (c) 2020 Nordic Semiconuctor ASA
 * SPDX-License-Identifier: Apache-2.0
 */

#include <stdio.h>
#include <zephyr.h>
#include <sys/printk.h>
#include <drivers/adc.h>


#define ADC_RESOLUTION			12
#define ADC_GAIN				ADC_GAIN_1
#define ADC_REFERENCE			ADC_REF_INTERNAL
#define ADC_ACQUISITION_TIME	ADC_ACQ_TIME_DEFAULT

#define ADC_CHANNEL_ID		7

static uint16_t adc_raw;
static const struct device * dev_adc;

struct adc_channel_cfg channel_cfg = {
	.gain 				= ADC_GAIN,
	.reference 			= ADC_REFERENCE,
	.acquisition_time 	= ADC_ACQUISITION_TIME,
	.differential 		= 0,
	.channel_id			= ADC_CHANNEL_ID,
	.input_positive 	= SAADC_CH_PSELP_PSELP_AnalogInput7,
};


void main(void)
{
	int err;
	int32_t mV;
	
	dev_adc = device_get_binding("ADC_0");
	if (!device_is_ready(dev_adc)) {
		printk("ADC device not found\n");
		return;
	}
	err = adc_channel_setup(dev_adc, &channel_cfg);
	if (err) {
		printk("adc_channel_setup() failed with error: %d\n", err);
	}
	struct adc_sequence sequence = {
		.channels    = BIT(channel_cfg.channel_id),
		.buffer      = &adc_raw,
		.buffer_size = sizeof(adc_raw),
		.resolution  = ADC_RESOLUTION,
	};

	while (true) {
		err = adc_read(dev_adc, &sequence);
		if (err) {
			printk("ADC reading failed with error %d.\n", err);
			return;
		}

		mV = (int16_t)adc_raw;
		err = adc_raw_to_millivolts(adc_ref_internal(dev_adc), channel_cfg.gain,
					   sequence.resolution, &mV);
		if (err) {
			printk("ADC conversion failed: %d\n", err);
			return;
		}
		printf("ADC raw %d => %d mV\n", (int16_t)adc_raw, mV);					   
		k_sleep(K_MSEC(1000));
	}
}