// Temperature.c
// 08/02/05

#include "Temperature.h"

// Converts a DS temperature to a temperature
void DSToTemperature(UInt8 lsb, UInt8 msb, UInt8 *sign, UInt8 *tvalue, UInt8 *treste) {
  UInt16 temp;
  *sign=0;
  *tvalue=0;
  *treste=0;
  temp = ((UInt16) msb << 8) | lsb; // 16 bits words computed

  if (msb & 0x80) {
    *sign=1; // Negative
    temp ^= 0xFFFF;
    temp +=1;
  }

  *treste = temp & 0x0F;
  *tvalue = (temp >> 4) & 0x7F;
}

void TemperatureToBCD (UInt8 sign, UInt8 tvalue, UInt8 treste, UInt8 *bcdvalue) {
  UInt8 h, l, v;
  
  // Ajustement decimal
  l = tvalue; // contient seulement la partie entiere et sans le signe
  h = 0;
  while (l > 9) {
    l -=10;
    h++;
  } 
  l += '0'; // Dizaines en BCD ASCII
  h += '0'; // Unites en BCD ASCII
  v = treste & 0x08; // 1 seule decimale : 0 correspond a .0, 1 correspond a .5

  if (sign) bcdvalue[0] = '-';
  else bcdvalue[0] = '+';

  bcdvalue[1]=h;
  bcdvalue[2]=l;
  bcdvalue[3]='.';
  if (v) bcdvalue[4]='5';
  else bcdvalue[4]='0';
  bcdvalue[5]='\0';

  // printf ("TemperatureToBCD (%02X:%02X:%02X) => %s\n", sign, tvalue, treste, bcdvalue);
}
 
// Convert a DS1822 temperature to a sample value
UInt8 TemperatureToSample (UInt8 sign, UInt8 tvalue, UInt8 treste) {
  UInt16 tmp;
  UInt16 sample;

  tmp = tvalue;

  if (sign==0) {
    if (tvalue >= 35) sample = 0;
    else sample = 28 - ((tmp << 2) / 5);
  }
  else {
    if (tvalue >= 14) sample = 39;
    else sample = 28 + ((tmp << 2) / 5);
  }

  // printf ("TemperatureToSample (%02X:%02X:%02X) => %d\n", sign, tvalue, treste, sample);

  return (UInt8) sample;
}

// End of file
