/*
	ADCTEMPS.C

	Read temperature from an ADC4 board using a thermistor.

	Default is logical address 0 and channel 0.

	The ADC4 board must be configured for ratiometric mode on a conditioned
	channel with a 10 kOhm excitation resistor and a 0 to 5 volt input range.
	Thus set jumpers J1 and J2 pins 2 to 3 and install a 10 kOhm resistor
	pack in RP2, a 4.64 kOhm gain resistor in R1 and a 4.87 kOhm bias resistor
	in R2.
	
	Additionally, the thermistor coefficients used in this example correspond
	to a 10 kOhm BAPI thermistor (available from Z-World).
*/

#use thermadc.lib // Include thermistor-specific functions

char unit;

int counts, channel, address;

float volts, ohms, temp;

struct ThermCoef thermCoef;
struct plcADC4parms adcparms;
struct adc4coeff adc4conv1;

main()
{
	// Initialize thermistor coefficients
	
	thermCoef.a = 2.775e-3;
	thermCoef.b = 2.468e-4;
	thermCoef.c = 1.771e-6;
	thermCoef.d = 9.536e-7;

	// Initialize conditioned-ratiometric voltage divider
	// ADC4 expansion board coefficients.

	adcparms.Rref  = 10.0; // in kOhms
	adcparms.Vref  = 4.97; // in volts
	adcparms.Rbias = 4.87; // in kOhms
	adcparms.Rp    = 10.0; // in kOhms

	unit = 'F'; // Display in degrees Fahrenheit

	// Prepare to read the ADC4 board

	address = 0x00C0; // ADC4 board 0 of 4   (C0,C1,C2,C3)
	channel = 0;      // ADC4 channel 0 of 4 (0,1,2,3)
	
	reset_pbus();
	reset_pbus_wait();

	if( !adc4_init(address) ) {

		printf("ADC4 PLCBus Expansion Board %d Not Found!\n\n", address-0x00c0);
		exit(-1);
	}

	adc4_readcoeff(address, channel, &adc4conv1);

	// Continuously monitor channel zero of the ADC4 board and
	// convert to temperature.
		
	printf("counts  volts   kOhms  degrees\n");

	while(1) {

		hitwd();
	
		counts = adc4_read( address, channel);
			
		volts = adc4_convert( counts, &adc4conv1);

		ohms = ADC4ohms( volts, &adcparms);

		temp = thermOhm2Temp( ohms, &thermCoef, unit);

		printf("%5d %7.3f %7.3f %7.3f %c\r", counts, volts, ohms/1000, temp, unit);
	}
}