/**
 * Copyright (c) 2016 - 2018, Nordic Semiconductor ASA
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form, except as embedded into a Nordic
 *    Semiconductor ASA integrated circuit in a product or a software update for
 *    such product, must reproduce the above copyright notice, this list of
 *    conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *
 * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * 4. This software, with or without modification, must only be used with a
 *    Nordic Semiconductor ASA integrated circuit.
 *
 * 5. Any software provided in binary form under this license must not be reverse
 *    engineered, decompiled, modified and/or disassembled.
 *
 * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
/** @file
 * @defgroup fatfs_example_main main.c
 * @{
 * @ingroup fatfs_example
 * @brief FATFS Example Application main file.
 *
 * This file contains the source code for a sample application using FAT filesystem and SD card library.
 *
 */


#include "nrf.h"
#include "nrf_gpio.h"
#include "nrf_drv_rtc.h"
#include "nrf_drv_clock.h"
#include "nrf_drv_saadc.h"
#include "nrf_drv_ppi.h"
#include "nrf_drv_timer.h"
#include "nrf_drv_spi.h"
#include "boards.h"
#include "app_error.h"
#include "bsp.h"
#include "ff.h"
#include "diskio_blkdev.h"
#include "nrf_block_dev_sdc.h"
#include "nrf_delay.h"
#include "app_util_platform.h"

#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <math.h>

#define COMPARE_COUNTERTIME  (1UL)                                        /**< Get Compare event COMPARE_TIME seconds after the counter starts from 0. */

#define SPI_INSTANCE 0 /**< SPI instance index. */
static const nrf_drv_spi_t eh_spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */

static uint8_t  status;
//static uint8_t  test = false;
static uint8_t  button = false;

#define RTC_INSTANCE 0 /**< RTC instance index. */
const nrf_drv_rtc_t rtc = NRF_DRV_RTC_INSTANCE(RTC_INSTANCE); /**< Declaring an instance of nrf_drv_rtc for RTC0. */

#define TIMER_INSTANCE 0 /**< Timer instance index. */
static const nrf_drv_timer_t m_timer = NRF_DRV_TIMER_INSTANCE(TIMER_INSTANCE);


#define SAMPLES_IN_BUFFER 10 //per channel
#define ADC_CHANNEL_COUNT 3
#define SAADC_CALIBRATION_INTERVAL 5              //Determines how often the SAADC should be calibrated relative to NRF_DRV_SAADC_EVT_DONE event. E.g. value 5 will make the SAADC calibrate every fifth time the NRF_DRV_SAADC_EVT_DONE is received.

volatile uint8_t state = 1;

// resistance at 25 degrees C
#define THERMISTORNOMINAL 10000      
// temp. for nominal resistance (almost always 25 C)
#define TEMPERATURENOMINAL 25   
// how many samples to take and average, more takes longer
// but is more 'smooth'
#define NUMSAMPLES 5
// The beta coefficient of the thermistor (usually 3000-4000)
#define BCOEFFICIENT 3950
// the value of the 'other' resistor
#define SERIESRESISTOR 10000  

unsigned int battery_voltage_sum = 0;
float battery_voltage = 0.0;
unsigned int thermistor_1_sum = 0;
float thermistor_1 = 0.0;
float steinhart_1;
unsigned int thermistor_2_sum = 0;
float thermistor_2 = 0.0;
float steinhart_2;
unsigned int voltage_sum = 0;
float voltage = 0.0;

static nrf_saadc_value_t     m_buffer_pool[2][SAMPLES_IN_BUFFER];
static nrf_ppi_channel_t     m_ppi_channel_1;
static nrf_ppi_channel_t     m_ppi_channel_2;
static uint32_t              m_adc_evt_counter = 1;
static bool                  m_saadc_calibrate = false;  

/**
 * @brief  SDC block device definition
 * */
NRF_BLOCK_DEV_SDC_DEFINE(
        m_block_dev_sdc,
        NRF_BLOCK_DEV_SDC_CONFIG(
                SDC_SECTOR_SIZE,
                APP_SDCARD_CONFIG(SD_MOSI, SD_MISO, SD_CLK, SD_CS)
         ),
         NFR_BLOCK_DEV_INFO_CONFIG("Nordic", "SDC", "1.00")
);

static FATFS fs;
static DIR dir;
static FILINFO fno;
static FIL file;

uint32_t bytes_written;
FRESULT ff_result;
DSTATUS disk_state = STA_NOINIT;

uint8_t rtcCounter = 0;
uint8_t measDone = 0;
uint8_t test = 0;

// Initialize FATFS disk I/O interface by providing the block device.
static diskio_blkdev_t drives[] =
{
	DISKIO_BLOCKDEV_CONFIG(NRF_BLOCKDEV_BASE_ADDR(m_block_dev_sdc, block_dev), NULL)
};


void moutSDCard (void)
{
	diskio_blockdev_register(drives, ARRAY_SIZE(drives));

	NRF_LOG_INFO("Initializing disk 0 (SDC)...");
	for (uint32_t retries = 3; retries && disk_state; --retries)
	{
			disk_state = disk_initialize(0);
	}
	if (disk_state)
	{
			NRF_LOG_INFO("Disk initialization failed.");
			return;
	}

	uint32_t blocks_per_mb = (1024uL * 1024uL) / m_block_dev_sdc.block_dev.p_ops->geometry(&m_block_dev_sdc.block_dev)->blk_size;
	uint32_t capacity = m_block_dev_sdc.block_dev.p_ops->geometry(&m_block_dev_sdc.block_dev)->blk_count / blocks_per_mb;
	NRF_LOG_INFO("Capacity: %d MB", capacity);

	NRF_LOG_INFO("Mounting volume...");
	ff_result = f_mount(&fs, "", 0);
	if (ff_result)
	{
			NRF_LOG_INFO("Mount failed.");
			return;
	}
	
	NRF_LOG_INFO("\r\n Listing directory: /");
	ff_result = f_opendir(&dir, "/");
	if (ff_result)
	{
			NRF_LOG_INFO("Directory listing failed!");
			return;
	}

	do
	{
			ff_result = f_readdir(&dir, &fno);
			if (ff_result != FR_OK)
			{
					NRF_LOG_INFO("Directory read failed.");
					return;
			}

			if (fno.fname[0])
			{
					if (fno.fattrib & AM_DIR)
					{
							NRF_LOG_RAW_INFO("   <DIR>   %s \n",(uint32_t)fno.fname);
					}
					else
					{
							NRF_LOG_RAW_INFO("%9lu  %s \n", fno.fsize, (uint32_t)fno.fname);
					}
			}
	}
	while (fno.fname[0]);
	NRF_LOG_RAW_INFO("");
}



void saadc_sampling_event_init(void)
{
    ret_code_t err_code;

    err_code = nrf_drv_ppi_init();
    APP_ERROR_CHECK(err_code);

		/*
    nrf_drv_timer_config_t timer_cfg = NRF_DRV_TIMER_DEFAULT_CONFIG;
    timer_cfg.bit_width = NRF_TIMER_BIT_WIDTH_32;
    err_code = nrf_drv_timer_init(&m_timer, &timer_cfg, timer_handler);
    APP_ERROR_CHECK(err_code);

    // setup m_timer for compare event every 400ms 
    uint32_t ticks = nrf_drv_timer_ms_to_ticks(&m_timer, 100);
    nrf_drv_timer_extended_compare(&m_timer,
                                   NRF_TIMER_CC_CHANNEL0,
                                   ticks,
                                   NRF_TIMER_SHORT_COMPARE0_CLEAR_MASK,
                                   false);
    nrf_drv_timer_enable(&m_timer);
		*/
    uint32_t rtc_compare_event_addr = nrf_drv_rtc_event_address_get(&rtc, NRF_RTC_EVENT_COMPARE_0);//nrf_drv_timer_compare_event_address_get(&m_timer, NRF_TIMER_CC_CHANNEL0);
    uint32_t saadc_sample_task_addr   = nrf_drv_saadc_sample_task_get();

    /* setup ppi channel so that timer compare event is triggering sample task in SAADC */
    err_code = nrf_drv_ppi_channel_alloc(&m_ppi_channel_1);
    APP_ERROR_CHECK(err_code);
		//err_code = nrf_drv_ppi_channel_alloc(&m_ppi_channel_2);
    //APP_ERROR_CHECK(err_code);

    err_code = nrf_drv_ppi_channel_assign(m_ppi_channel_1,
                                          rtc_compare_event_addr,
                                          saadc_sample_task_addr);
																					
    APP_ERROR_CHECK(err_code);
		
		//err_code = nrf_drv_ppi_channel_assign(m_ppi_channel_2, nrf_saadc_event_address_get(NRF_SAADC_EVENT_END), nrf_saadc_task_address_get(NRF_SAADC_TASK_START));
		//APP_ERROR_CHECK(err_code);
		
	  //err_code = nrf_drv_ppi_channel_enable(m_ppi_channel_2);
    //APP_ERROR_CHECK(err_code);
}


void saadc_sampling_event_enable(void)
{
    ret_code_t err_code = nrf_drv_ppi_channel_enable(m_ppi_channel_1);

    APP_ERROR_CHECK(err_code);
}

void saadc_sampling_event_disable(void)
{
    ret_code_t err_code = nrf_drv_ppi_channel_disable(m_ppi_channel_1);

    APP_ERROR_CHECK(err_code);
}


void saadc_callback(nrf_drv_saadc_evt_t const * p_event)
{
		int value = 0;
		int i;
		ret_code_t err_code;
	
		/*
		if (p_event->type == NRF_SAADC_EVENT_STARTED)
    {
			value = 1;
		}
		*/
	
		//Event is triggered when buffer is full! Not when one conversion is done!
		////https://devzone.nordicsemi.com/f/nordic-q-a/14777/ble_app_proximity-saadc-channel-data#post-id-85497
		
		//In this mode, the RESULTDONE event signals has the same meaning as DONE when no oversampling takes place. 
		//Note that both events may occur before the actual values have been transferred into RAM by EasyDMA.
		//-->Therefore nrf_drv_saadc_buffer_convert should be executed after STARTED event (Datasheet --> SAADC --> EasyDMA)
    if (p_event->type == NRF_DRV_SAADC_EVT_DONE)
    {
				nrf_gpio_pin_toggle(LED);
			
				if((m_adc_evt_counter % SAADC_CALIBRATION_INTERVAL) == 0)       //Evaluate if offset calibration should be performed. Configure the SAADC_CALIBRATION_INTERVAL constant to change the calibration frequency
        {
            nrf_drv_saadc_abort();                                      // Abort all ongoing conversions. Calibration cannot be run if SAADC is busy
            m_saadc_calibrate = true;                                   // Set flag to trigger calibration in main context when SAADC is stopped
        }
        
        NRF_LOG_INFO("ADC event number: %d", (int)m_adc_evt_counter);
				
				for (i = 0; i < ADC_CHANNEL_COUNT; i++)
				{
					NRF_LOG_INFO("%d", p_event->data.done.p_buffer[i]);
					switch(i%4)
					{
						//case 0: battery_voltage_sum = battery_voltage_sum + p_event->data.done.p_buffer[i];
						//				break;
						case 0: thermistor_1_sum = p_event->data.done.p_buffer[i];
										break;
						case 1: thermistor_2_sum = p_event->data.done.p_buffer[i];
										break;	
						case 2: voltage_sum = p_event->data.done.p_buffer[i];
										break;	
					}
				}
				
				if(m_saadc_calibrate == false)
        {
          err_code = nrf_drv_saadc_buffer_convert(p_event->data.done.p_buffer, ADC_CHANNEL_COUNT); //Set buffer so the SAADC can write to it again. This is either "buffer 1" or "buffer 2"
					APP_ERROR_CHECK(err_code);
					
					measDone = 1;
        }
				
				m_adc_evt_counter++;
				
				//stop sampling until Compare 1 Event of RTC
				//saadc_sampling_event_disable();
				nrf_gpio_pin_clear(THERMISTOR_VREF);
    }
		
		else if (p_event->type == NRF_DRV_SAADC_EVT_CALIBRATEDONE)
    {
				//nrfx_saadc_abort();
			
        err_code = nrf_drv_saadc_buffer_convert(m_buffer_pool[0], ADC_CHANNEL_COUNT);             //Set buffer so the SAADC can write to it again. 
        APP_ERROR_CHECK(err_code);
        err_code = nrf_drv_saadc_buffer_convert(m_buffer_pool[1], ADC_CHANNEL_COUNT);             //Need to setup both buffers, as they were both removed with the call to nrf_drv_saadc_abort before calibration.
        APP_ERROR_CHECK(err_code);
        
        NRF_LOG_INFO("SAADC calibration complete !");                                              //Print on UART        
    }
}

void saadc_init(void)
{
		//Source for battery measurement: 
		//https://devzone.nordicsemi.com/nordic/nordic-blog/b/blog/posts/measuring-lithium-battery-voltage-with-nrf52
		//Sampling frequeny should be 1Hz-10Hz for high saadc input resistance value! Otherwise voltage devider will be affected by the input reistance!
	
		//Total time < Sum(CH[x].tACQ+tCONV), x=0..enabled channels (Source: Datasheet)
		//Total time < #Channels*(40us + 2us)
		//3 Channels: 126us --> max sampling rate = 1/126uS = 7.94kHz --> set RTC Compare Event (PPI) to this frequency
	
	  ret_code_t err_code;

		//Configure SAADC
		nrf_drv_saadc_config_t  config = NRF_DRV_SAADC_DEFAULT_CONFIG;
		config.resolution = NRF_SAADC_RESOLUTION_14BIT;  
    config.oversample = SAADC_OVERSAMPLE_OVERSAMPLE_Over256x;
	  //config.low_power_mode = true; 

		//Initialize SAADC
    err_code = nrf_drv_saadc_init(&config, saadc_callback);                       
    APP_ERROR_CHECK(err_code);
	
		//enable int for STARTED
		//nrf_saadc_int_enable(NRF_SAADC_INT_STARTED);
		//NRF_SAADC ->INTEN = 0x00000003 ; //enable int for end
		//NVIC_EnableIRQ(SAADC_IRQn);

		//Configure SAADC channel 0
		//nrf_saadc_channel_config_t channel_config = NRF_DRV_SAADC_DEFAULT_CHANNEL_CONFIG_SE(NRF_SAADC_INPUT_AIN7);
		//channel_config.gain = NRF_SAADC_GAIN1_4;
		//channel_config.acq_time = SAADC_CH_CONFIG_TACQ_3us; //needed for maximum source resistance of 800kOhm (Datasheet) --> 40us. With additional C --> 3us
		//channel_config.burst = NRF_SAADC_BURST_ENABLED;
	                                        
		//Initialize SAADC channel 0
    //err_code = nrf_drv_saadc_channel_init(0, &channel_config);
    //APP_ERROR_CHECK(err_code);
	
	  //Configure SAADC channel 1
		nrf_saadc_channel_config_t channel_config = NRF_DRV_SAADC_DEFAULT_CHANNEL_CONFIG_SE(NRF_SAADC_INPUT_AIN0);
	 	channel_config.reference = NRF_SAADC_REFERENCE_VDD4;
		channel_config.gain = NRF_SAADC_GAIN1_4;
		channel_config.acq_time = SAADC_CH_CONFIG_TACQ_40us;
		channel_config.burst = NRF_SAADC_BURST_ENABLED;

		//Initialize SAADC channel 1
    err_code = nrf_drv_saadc_channel_init(0, &channel_config);
    APP_ERROR_CHECK(err_code);
		
		//Configure SAADC channel 2
		channel_config.pin_p = NRF_SAADC_INPUT_AIN1;
		channel_config.acq_time = SAADC_CH_CONFIG_TACQ_40us;

		//Initialize SAADC channel 2
    err_code = nrf_drv_saadc_channel_init(1, &channel_config);
    APP_ERROR_CHECK(err_code);
		
		//Configure SAADC channel 3
		channel_config.pin_p = NRF_SAADC_INPUT_AIN2;
		channel_config.reference = NRF_SAADC_REFERENCE_INTERNAL;
		channel_config.gain = NRF_SAADC_GAIN4;
		channel_config.acq_time = SAADC_CH_CONFIG_TACQ_40us;

		//Initialize SAADC channel 3
    err_code = nrf_drv_saadc_channel_init(2, &channel_config);
    APP_ERROR_CHECK(err_code);

		//Set SAADC buffer 1. The SAADC will start to write to this buffer
    err_code = nrf_drv_saadc_buffer_convert(m_buffer_pool[0], ADC_CHANNEL_COUNT);
    APP_ERROR_CHECK(err_code);

		//Set SAADC buffer 2. The SAADC will write to this buffer when buffer 1 is full. This will give the applicaiton time to process data in buffer 1.
    err_code = nrf_drv_saadc_buffer_convert(m_buffer_pool[1], ADC_CHANNEL_COUNT);
    APP_ERROR_CHECK(err_code);
}

/** @brief: Function for handling the RTC0 interrupts.
 * Triggered on TICK and COMPARE0 match.
 */
static void rtc_handler(nrf_drv_rtc_int_type_t int_type)
{
		static int i = 2;
    if (int_type == NRF_DRV_RTC_INT_COMPARE0)
    {
				nrf_gpio_pin_set(THERMISTOR_VREF);
        //nrf_gpio_pin_toggle(LED);
				nrf_drv_rtc_counter_clear(&rtc);
				//reactivate compare irq! 
				nrf_drv_rtc_cc_set(&rtc,0,COMPARE_COUNTERTIME * 8,true);
    }
		
		/*
		else if (int_type == NRF_DRV_RTC_INT_COMPARE1)
    {
        nrf_gpio_pin_toggle(LED);
				nrf_drv_rtc_counter_clear(&rtc);
				//reactivate compare irq! 
				nrf_drv_rtc_cc_set(&rtc,0,COMPARE_COUNTERTIME * 1,true);
				nrf_drv_rtc_cc_set(&rtc,1,COMPARE_COUNTERTIME * 100,true);
				i = 2;
				nrf_gpio_pin_set(THERMISTOR_VREF);
				saadc_sampling_event_enable();
    }
		*/
		
    else if (int_type == NRF_DRV_RTC_INT_TICK)
    {
        rtcCounter++;
    }
		
}

/** @brief Function starting the internal LFCLK XTAL oscillator.
 */
static void lfclk_config(void)
{
    ret_code_t err_code = nrf_drv_clock_init();
    APP_ERROR_CHECK(err_code);

    nrf_drv_clock_lfclk_request(NULL);
}

/** @brief Function initialization and configuration of RTC driver instance.
 */
static void rtc_config(void)
{
	uint32_t err_code;

	//Initialize RTC instance
	nrf_drv_rtc_config_t config = NRF_DRV_RTC_DEFAULT_CONFIG;
	//config.prescaler = 327; // fRTC [kHz] = 32.768 / (PRESCALER + 1 ) = 100Hz
	//config.prescaler = 32; // fRTC [kHz] = 32.768 / (PRESCALER + 1 ) = 1kHz
	config.prescaler = 4095; // fRTC [kHz] = 32.768 / (PRESCALER + 1 ) --> 8Hz (minimum because prescsaler is 12bit)
	err_code = nrf_drv_rtc_init(&rtc, &config, rtc_handler);
	APP_ERROR_CHECK(err_code);

	//Enable tick event & interrupt
	nrf_drv_rtc_tick_enable(&rtc,true);

	//Set compare channel 0 to trigger interrupt after COMPARE_COUNTERTIME seconds
	err_code = nrf_drv_rtc_cc_set(&rtc,0,COMPARE_COUNTERTIME * 8,true); //1Hz
	APP_ERROR_CHECK(err_code);

	//Set compare channel 1 to trigger interrupt after COMPARE_COUNTERTIME seconds
	//err_code = nrf_drv_rtc_cc_set(&rtc,1,COMPARE_COUNTERTIME * 100,true); //1Hz
	//APP_ERROR_CHECK(err_code);

	//Power on RTC instance
	nrf_drv_rtc_enable(&rtc);
}

void timer_handler(nrf_timer_event_t event_type, void * p_context)
{

}


/**
 * @brief Function for main application entry.
 */
int main(void)
{
		/* Configure board. */
    bsp_board_init(BSP_INIT_LEDS);
		bsp_board_leds_on();
	  bsp_board_init(BSP_INIT_BUTTONS);

    APP_ERROR_CHECK(NRF_LOG_INIT(NULL));
    NRF_LOG_DEFAULT_BACKENDS_INIT();
	
		NRF_POWER->DCDCEN = 1;	//Enabling the DCDC converter for lower current consumption

    NRF_LOG_INFO("XXX successfuly started...");
								
		moutSDCard();

		lfclk_config();
		rtc_config();
		
		nrf_gpio_cfg_output(THERMISTOR_VREF);
		nrf_gpio_pin_set(THERMISTOR_VREF);
		
	  saadc_init();
		saadc_sampling_event_init();
    saadc_sampling_event_enable();
		
		while(1)
    {	
			
				if(m_saadc_calibrate == true)
				{
					// Disable the PPI triggering of the sample task
					saadc_sampling_event_disable();
						
					NRF_SAADC->EVENTS_STOPPED = 0;
					NRF_SAADC->TASKS_STOP;
					while(!NRF_SAADC->EVENTS_STOPPED);
					NRF_SAADC->EVENTS_STOPPED = 0;

					NRF_LOG_INFO("SAADC calibration starting...");    //Print on UART
					while(nrf_drv_saadc_calibrate_offset() != NRF_SUCCESS); //Trigger calibration task
					while(!NRF_SAADC->EVENTS_CALIBRATEDONE);
					NRF_SAADC->EVENTS_CALIBRATEDONE = 0;
					
					NRF_SAADC->EVENTS_STOPPED = 0;
					NRF_SAADC->TASKS_STOP;
					while(!NRF_SAADC->EVENTS_STOPPED);
					NRF_SAADC->EVENTS_STOPPED = 0;
					
					NRF_SAADC->EVENTS_STARTED = 0;
					NRF_SAADC->TASKS_START;
					while(!NRF_SAADC->EVENTS_STARTED);
					NRF_SAADC->EVENTS_STARTED = 0;
					
					// Enable the PPI triggering of the sample task
					saadc_sampling_event_enable();
					
					m_saadc_calibrate = false;
				}
			
				if(measDone == 1)
				{
					//battery_voltage = (battery_voltage_sum * (0.6 / 0.25)) / 16383;
					//battery_voltage = battery_voltage / 10 * (10 + 5);
					//NRF_LOG_INFO("Battery: %d --> " NRF_LOG_FLOAT_MARKER "V", battery_voltage_sum, NRF_LOG_FLOAT(battery_voltage));
					
					if(voltage_sum < 16383)
					{
						voltage = (voltage_sum * (0.6 / 4)) / 16383;
						voltage = voltage * 1000;
						NRF_LOG_INFO("TEG Voltage: %d --> " NRF_LOG_FLOAT_MARKER "mV", voltage_sum, NRF_LOG_FLOAT(voltage));
					}
					else
					{
						NRF_LOG_INFO("TEG Voltage: %d --> " NRF_LOG_FLOAT_MARKER "mV", (0), NRF_LOG_FLOAT(0.0000));
					}
					
					//R = 10K * ((4095/ADC) - 1) 
					//Source: https://learn.adafruit.com/thermistor/using-a-thermistor
					//thermistor_1 = ((thermistor_1_sum / SAMPLES_IN_BUFFER) * (0.6 / 0.25)) / 4095;
					thermistor_1 = THERMISTORNOMINAL * ((16383 / (float)(thermistor_1_sum)) - 1);
					steinhart_1 = thermistor_1 / THERMISTORNOMINAL;     // (R/Ro)
					steinhart_1 = log(steinhart_1);                  // ln(R/Ro)
					steinhart_1 /= BCOEFFICIENT;                   // 1/B * ln(R/Ro)
					steinhart_1 += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
					steinhart_1 = 1.0 / steinhart_1;                 // Invert
					steinhart_1 -= 273.15;                         // convert to C
					NRF_LOG_INFO("Thermistor 1: %d --> " NRF_LOG_FLOAT_MARKER "°C", thermistor_1_sum, NRF_LOG_FLOAT(steinhart_1));
					
					//R = 10K * ((4095/ADC) - 1) 
					//Source: https://learn.adafruit.com/thermistor/using-a-thermistor
					//thermistor_1 = ((thermistor_1_sum / SAMPLES_IN_BUFFER) * (0.6 / 0.25)) / 4095;
					thermistor_2 = THERMISTORNOMINAL * ((16383 / (float)(thermistor_2_sum)) - 1);
					steinhart_2 = thermistor_2 / THERMISTORNOMINAL;     // (R/Ro)
					steinhart_2 = log(steinhart_2);                  // ln(R/Ro)
					steinhart_2 /= BCOEFFICIENT;                   // 1/B * ln(R/Ro)
					steinhart_2 += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
					steinhart_2 = 1.0 / steinhart_2;                 // Invert
					steinhart_2 -= 273.15;                         // convert to C
					NRF_LOG_INFO("Thermistor 2: %d --> " NRF_LOG_FLOAT_MARKER "°C", thermistor_2_sum, NRF_LOG_FLOAT(steinhart_2));
					
					//thermistor_2 = ((thermistor_2_sum / SAMPLES_IN_BUFFER) * (0.6 / 0.25)) / 4095;
					//battery_voltage = battery_voltage / 10 * (10 + 5);
					//NRF_LOG_INFO("Thermistor 2: %d --> " NRF_LOG_FLOAT_MARKER "°C", (thermistor_2_sum / SAMPLES_IN_BUFFER), NRF_LOG_FLOAT(thermistor_2));
					
					battery_voltage_sum = 0;
					voltage_sum = 0;
					thermistor_1_sum = 0;
					thermistor_2_sum = 0;
					
										
					//nrf_gpio_pin_toggle(LED);
					measDone = 0;
				}
        //__SEV();
        //__WFE();
        //__WFE();
				//nrf_pwr_mgmt_run();

    }

    

    while (true)
    {
        __WFE();
    }
}

/** @} */
