#include <stdio.h>
#include <unistd.h>

#include "../hubolib.h"

using namespace HuboLib;

/*
Compile and link: 
	g++ AnalogInput4.cpp -L../ -lhubo -lpthread -lrt -o AnalogInput4.out
Run:
	sudo ./AnalogInput4.out
Purpose:
	Check and - if required - adjust the reference voltage of the MCP3208.
	The reference voltage should only be adjusted once the TL431 reference voltage has been measured with a high 
	precision instrument.
*/

int main(void)
{
	// Initialize the library once in your program.
	if (!Initialize())
	{
		printf ("Error: Initialize\n");
		return 1;
	}
	
	// Define channel 0 to be oversampled 40 times (set to 40) all other channels (set to 0) are not read from the ADC.
	unsigned short overSampling[MAX_MCP3x08_CHANNELS] = { 1, 0, 0, 0, 0, 0, 0, 0 };
	Set_MCP3x08_Oversampling (overSampling);

	// Let the AD buffers get filled.
	usleep(100000);

	// Check the current setting of the reference voltage of the TL431.
	printf ("VRef=%lf\n", Get_VRef());
		
	int 			channel = 0;
	unsigned long 	adcCount; 
	double	 		volt;
	
	// Read channel 0 and output its count as well as it's voltage value.
	Get_AI_Channel (channel, adcCount, volt);
	printf ("Channel=%d   ADC count=0x%02lX   Volts=%lf\n", channel, adcCount, volt);

	// Latch some more values...
	usleep(1000000);

	// Usually the reference voltage would be around 2.51V +-2%. So this value would be entered here.
	// However, let's see what happens if we'd use a value that is twice as big as the actual reference voltage.
	Set_VRef (2*Get_VRef());
	printf ("VRef=%lf\n", Get_VRef());

	// Read channel 0 and output it's count as well as its voltage value.
	Get_AI_Channel (channel, adcCount, volt);
	printf ("Channel=%d   ADC count=0x%02lX   Volts=%lf\n", channel, adcCount, volt);

	// Conclusion: While adjusting the reference voltage directly impacts the output value of the calculated voltage it 
	// does of cause not impact the measured ADC count. Setting VRef also does not alter the buffered values.
	// Since the setting refers to the TL431 it does affect all of the analog channels.
	
	// Free library resources.
	Uninitialize();
	
	return 0;
}
