#define TEN_LED	PIN_A1
#define ONE_LED	PIN_A2

#define LED		pin_a1
#define ANEMOMETER	pin_b0
#define DS1820		pin_a6
#define RAIN_IN		pin_a7

#define SER_RX	PIN_A3
#define SER_TX	PIN_A0

#define EE_SDA	PIN_A6
#define EE_SCL	PIN_A7

/* One wire data in buffer[], number of bytes in num_vals. 
Retruns zero if CRC is okay.
Found at:
http://www.pic-c.com/forum/general/posts/148.html
*/
byte calc_dallas_crc(int *buff, int num_vals) {
	int shift_reg=0;
	int data_bit;
	int sr_lsb;
	int fb_bit;
	int i;
	int j;
	
	for ( i=0 ; i<num_vals ; i++ ) {
		for ( j=0 ; j<8 ; j++ ) {
			data_bit = (buff[i] >> j ) & 0x01;
			sr_lsb = shift_reg & 0x01;
			fb_bit = ( data_bit ^ sr_lsb ) & 0x01;
			shift_reg = shift_reg >> 1;
			
			if ( fb_bit )
				shift_reg = shift_reg ^ 0x8c;
		}				
	}
	return shift_reg;
}

void printAprsTemp() {
	signed long temperature;
	bit negative;
	int ok;
	signed int t;
	
	byte scratchpad[9];
	int i;
	int again=0;


		
tagain:
	again++;

	disable_interrupts(GLOBAL);

	ok = initialise1_wire_with_error_check(); // initialise DS1820.
	send1_wire(0xCC); // send 'Skip ROM' command to DS1820.
	send1_wire(0x44); // send 'Convert T' command to DS1820.
	enable_interrupts(GLOBAL);
	
	/* provide power for the DS18S20 */
	output_high(W_DATA);
	/* must provide power for maximum conversion time, 750ms */
	delay_ms(750); 
	
	
	disable_interrupts(GLOBAL);

	ok += initialise1_wire_with_error_check(); // initialise DS1820.
	send1_wire(0xCC); // send 'Skip ROM' command to DS1820.
	send1_wire(0xBE); // send 'Read Scratchpad' command to DS1820.
	
	/* read the memory from the DS18S20 */
	for ( i=0 ; i<9 ; i++ ) {
		scratchpad[i] = read1_wire();
	}
	enable_interrupts(GLOBAL);

	/* if the temperature sensor isn't found then we give up after 5 tries */
	if ( again > 5 ) {
		printf("...");
		temptensdigit=13;	// the bottom most segment
		temponesdigit=13;	// the bottom most segment
		return;
	} else if ( 2 != ok ) {
		goto tagain;
	}

		
	if ( calc_dallas_crc(scratchpad, 9) ) {
		goto tagain;
	}

#if 0
	putchar('<');
	for ( i=0 ; i<9 ; i++ ) {
		print_hex(scratchpad[i]);	
		if ( i != 8 )
			putchar(',');
		
	}
	putchar('>');
#endif

	temperature= (signed long) scratchpad[0];
	
	if (bit_test(scratchpad[1],1)) {  // check MSB for negative temperature.
		bit_set(temperature,15);
		bit_set(temperature,14);
		bit_set(temperature,13);
		bit_set(temperature,12);
		bit_set(temperature,11);
		bit_set(temperature,10);
		bit_set(temperature,9);
		bit_set(temperature,8);
		negative=true;
	} else {
		negative=false;
	}

//	printf("a%lda",temperature);

	/* C to F */
	temperature *= 115;
	
//	printf("b%ldb",temperature);


	/* shift the whole thing seven bits over */
	shift_right(&temperature,2,negative);
	shift_right(&temperature,2,negative);
	shift_right(&temperature,2,negative);
	shift_right(&temperature,2,negative);
	shift_right(&temperature,2,negative);
	shift_right(&temperature,2,negative);
	shift_right(&temperature,2,negative);

//	printf("c%ldc",temperature);

	temperature += 32;
	
	temperature = temperature TEMP_OFFSET;

//	printf("(%ld)",temperature);

	t = (signed int) temperature;
	print_temp(t);	
}



#ifndef hi
#define hi(x)  (*(&x+1))
#endif

#use i2c(master,sda=EE_SDA, scl=EE_SCL)
#define EEPROM_ADDRESS long int
#define EEPROM_SIZE   32768

void init_ext_eeprom()
{
    int i;

   output_float(ee_scl);
   output_float(ee_sda);
   delay_us(4);
   for (i=0;i<3;i++) {
     i2c_start();
     i2c_write(0xa0);
     i2c_write(0xff);
     i2c_write(0xff);
     if(i==2)
       i2c_write(0x2);
     else
       i2c_write(0x2+i);
     i2c_stop();
  }
}


void write_ext_eeprom(long int address, byte data) {
	disable_interrupts(GLOBAL);
	i2c_start();
	i2c_write(0xa0);
	i2c_write( hi(address) );
	i2c_write( (byte) address );
	i2c_write(data);
	i2c_stop();
	delay_ms(5);	// 5ms according to 24LC256 datasheet
	enable_interrupts(GLOBAL);
}


byte read_ext_eeprom(long int address) {
	byte data;
	
	disable_interrupts(GLOBAL);
	
	i2c_start();
	i2c_write(0xa0);	
	i2c_write( hi(address) );
	i2c_write( (byte) address );
	i2c_start();
	i2c_write(0xa1);
	data = i2c_read(0);
	i2c_stop();
	
	enable_interrupts(GLOBAL);
	
	return(data);
}

/** Put the datalogger into lowest possible power consumption */
void shutdown() {

	/* disable voltage reference, already done in main */

	/* all I/O pins should be either at VDD, or VSS, with no external 
	circuitry drawing current from the I/O pin and the comparators and
	VREF should be disabled */

	/* shut off LED dispalys */
	output_low(ONE_LED);
	output_low(TEN_LED);
	port_b=255;
	
	/* port_b pullups are already off */
	output_low(SER_TX);

	output_float(EE_SDA);	// pulled high externaly
	output_float(EE_SCL);	// pulled high externaly

	/* go to sleep */
	sleep();
}

void write_int_ulong(byte address, unsigned long value) {

	write_int_eeprom(address,hi(value));
	write_int_eeprom(address+1,value);

}

unsigned long read_int_ulong(byte address) {
	unsigned long value;
	
	value = read_int_eeprom(address);
	value = value << 8;
	value += read_int_eeprom(address+1);
	
	return value;
}

#if 0
void ee_test() {

   byte value,cmd;
   EEPROM_ADDRESS address;

   init_ext_eeprom();

   do {
      do {
         printf("\r\nRead, Write, Quit: ");
         cmd=getc();
         cmd=toupper(cmd);
         putc(cmd);
      } while ( (cmd!='R') && (cmd!='W') && (cmd!='Q') );

	if ( cmd == 'Q' )
		break;	

      printf("\n\rLocation: ");

#if sizeof(EEPROM_ADDRESS)==1
      address = gethex();
#else
#if EEPROM_SIZE>0xfff
      address = gethex();
#else
      address = gethex1();
#endif
      address = (address<<8)+gethex();
#endif

      if(cmd=='R')
         printf("\r\nValue: %X\r\n",READ_EXT_EEPROM( address ) );

      if(cmd=='W') {
         printf("\r\nNew value: ");
         value = gethex();
         printf("\n\r");
         WRITE_EXT_EEPROM( address, value );
      }
   } while (TRUE);
	puts("");
}
#endif
