/*
 * Copyright(C) Paul und Scherer (mct.de/mct.net)
 *
 * This example demonstrates how to...
 *
 *  ... use the ADC as die thermometer.
 *
 *  ... read the RTC temperature sensor.
 */

#include <stdio.h>
#include <stdlib.h>
#include <target.h>
#include "../iic.h"
#include "../delay.h"

#define RTC	0x9e				// RTC IIC bus address

/*
 * Read the RTC temperature sensor.
 *
 * Return temperature string in the
 * form "+/-ddd.d".
 */
static char *
getts(void)
{
	static char s[7];			// temp. string
	signed char t[2];			// temp. (integral/fraction val)

	if (iic_write(RTC, "\xee", 1)		// start convert T cmd
	 || iic_write(RTC, "\xaa", 1)		// read temperature cmd

	 || iic_read (RTC, t, 2)) puts("Reading temperature failed!"), abort();

	/*
	 * If the fraction value is non-zero the temperature is
	 * 0.5 degree higher. This means, the integral value is
	 * one degree higher, in case it is negative.
	 */
	sprintf(s, "%+4d.%d", t[1] && *t < 0? *t+1: *t, t[1]? 5: 0);
	return s;
}

/*
 * One ADC digit equals Vref (=2500mV)/4096.
 * The ADC value x represents x*2500mV/4096.
 *
 * At 25 degree Celsius, 780mV are delivered
 * from the temperature sensor. With delta U
 * = -1.3mV/degree, the temperature is:
 *
 *  T = U[mV]*-10/13[degree Celsius/mV]
 *              +625[degree Celsius]
 *
 *  where U is x*2500mV/4096.
 */
#define T(x)	((long)(x)*2500*-10/4096/13+625)

/*
 * The program displays
 *
 *  - the die temperature, Tdie (from the ADC temp. sensor), and
 *  - the RTC temperature, TRTC (from the RTC temp. sensor).
 */
int
main(void)
{
	iic_init();				// initialize IIC bus interface

	/*
	 * Reference voltage
	 *
	 * Setting refcon to 1 activates the internal
	 * reference and connects it to the Vref pin.
	 *
	 * Note: A 0.47uF capacitor is required (from
	 * Vref to GND) for proper operation!
	 */
	Intern_refcon = 1;

	Intern_adccp  = 0x10;			// select temp. sensor
	Intern_adccon = 0xa4;			// continuous conversion

	while (1) {
		delay(1000);			// pause to smooth output
		while (!Intern_adcsta) ;	// wait for result ready

		printf("Tdie: %+4ld   [degree Celsius]\n"
		       "TRTC: %s [degree Celsius]\n\n",
			T((Intern_adcdat>>16)&0xfff),
			getts()
		);
	}
}

