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

#include "../hubolib.h"

using namespace HuboLib;

/*
Compile and link: 
	g++ AnalogInput2.cpp -L../ -lhubo -lpthread -lrt -o AnalogInput2.out
Run:
	sudo ./AnalogInput2.out
Purpose:
	Using oversampling in order to increase the resolution of an ADC sample value.
*/

int main(void)
{
	// Initialize the library once in your program.
	if (!Initialize())
	{
		printf ("Error: Initialize\n");
		return 1;
	}
	
	// Define channel 0 to be oversampled 4 times (set to 4) all other channels (set to 0) are not read from the ADC.
	unsigned short overSampling[MAX_MCP3x08_CHANNELS] = { 4, 0, 0, 0, 0, 0, 0, 0 };
	Set_MCP3x08_Oversampling (overSampling);
	
	int 			channel = 0;
	unsigned long 	adcCount; 
	double	 		volt;
	for (int i=0; i<20; i++)
	{
		// Read channel 0 and output its value.
		if (Get_AI_Channel (channel, adcCount, volt))
		{
			printf ("Channel=%d   ADC count=0x%02lX   Volts=%lf\n", channel, adcCount, volt);
			// Again - you'll see that you're getting the bufferd value a bit later.
			// As it can be seen from the adcCount - the value is about 4 times as high while the
			// voltage is still the same. Oversampled values are just added up, while the voltage
			// is averaged over the 4 samples. 
			// Also you'll notice that the time to get the averaged value has not increased
			// compared to the previouse example where no oversampling was used. This is why all
			// oversampling will be done in one and the same cycle time slice. 
		}
		else 
		{
			printf ("Error: Get_AI_Channel\n");
		}

		usleep(1000);
	}
	
	// Free library resources.
	Uninitialize();
	
	return 0;
}
