/*
   C-Language example for the 
   Crandun Technologies CTI-AR4000 software library.
   Copyright (c) 2001, Crandun Technologies Inc.

   This example shows how to set a higher sampling rate 
   than the factory default, and how to collect sample
   data with extended information (low-level sensor outputs)
*/

#include "CTI_AR4000.h"	/* required header */
#include <stdio.h>

#define MAXSAMPLES 200

/* A helper macro for checking return codes */
#define CHK_RETURN_VALUE(retCode, fnName) \
if (retCode < 0) { \
		printf("ERROR: " #fnName " returned error code: %ld\n", rc); \
		setCommClosed(sensorHandle); \
		printf("Please enter any character to exit: "); \
		scanf("%c", &c); \
		return (-1); \
} 

int main()
{
	char c;
	long i;
	long rc;
	AR4000_DATA_PT	extRangeData[MAXSAMPLES];

	long numSkipped;

	long sensorHandle;

	printf("Crandun Technologies CTI-AR4000 Demonstration program.\n");
	sensorHandle = -1;
	sensorHandle = getNewCTIAR4000();

	if (sensorHandle < 0) {
		printf("ERROR: getNewCTIAR4000 returned error code %ld\n", sensorHandle);
		printf("Please enter any character to exit: "); \
		scanf("%c", &c); \
		return -1;
	}
	
	printf("Opening the serial port...\n");
	rc = setCommOpen(sensorHandle, "COM1:", 9600);
	CHK_RETURN_VALUE(rc, setCommOpen)
	printf("Successfully opened the serial port!\n");

	/* Set sampling rate to 10 samples per second */
	printf("Setting sample rate to 10 samples/second.\n");
	rc = setSamplesPerSec(sensorHandle, 10);
	CHK_RETURN_VALUE(rc, setSamplesPerSec)
	printf("Successfully set the sample rate!\n");

	printf("Setting extended outputs on.\n");
	rc = setLowLevelOutputOn(sensorHandle);
	CHK_RETURN_VALUE(rc, setSamplesPerSec)
	printf("Successfully set extended outputs on!\n");

	printf("Reading samples from sensor...\n");
	rc = getExtSamples(sensorHandle, extRangeData, 5, 3);
	CHK_RETURN_VALUE(rc, getExtSamples)

	printf("Read %ld range samples from the sensor.\n", rc);
	for (i = 0; i < rc; i++) {
		printf("Range %d is %8.3f inches \n", i, extRangeData[i].range );
		printf("     Raw range is     %ld \n", extRangeData[i].rawRange );
		printf("     Sensor temp. is  %6.2f deg. F. \n", extRangeData[i].temperature );
		printf("     Ambient light is %ld \n", extRangeData[i].ambient );
		printf("     Amplitude is     %ld \n", extRangeData[i].amplitude );
	}

	numSkipped = getNumBytesSkipped(sensorHandle);
	printf("%ld bytes of data were skipped.\n", numSkipped);
	
	setCommClosed(sensorHandle);

	printf("Please enter any character to exit: "); \
	scanf("%c", &c); \
	return 0;
}
