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

#include "../hubolib.h"

using namespace HuboLib;

/*
Compile and link: 
	g++ AnalogInput1.cpp -L../ -lhubo -lpthread -lrt -o AnalogInput1.out
Run:
	sudo ./AnalogInput1.out
Purpose:
	Simple definition and reading of the analog inputs.
	First we define which channels to be read, then we read their value.
*/

int main(void)
{
	// Initialize the library once in your program.
	if (!Initialize())
	{
		printf ("Error: Initialize\n");
		return 1;
	}
	
	// Define channel 0 to be read (set to 1) 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);
	
	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);
			// Since ADC channels are buffered your'e referring to the buffered values instead of directly  
			// reading them from the ADC. The buffer might need some time to first get filled before you get a true
			// result of a measuring value. Here the call to Initialize() is too close in time for a first 
			// usage of the Get_AI_Channel() call. That's why the first few samples will show "0".
		}
		else 
		{
			printf ("Error: Get_AI_Channel\n");
		}

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