// ***********************************************************
// Project:  Loadcell to RS232 Interface via HX711,
//           Micrometer dial to RS232 via hex interface
// Author: Dr. Simon Schroedle
// Module description: Standalone to run on ATMEGA8-16PU;
//  data are transmitted as HEX values
//  W: load cell data
//  D: dial data
// ***********************************************************


// configuration
#define F_CPU				7372800
#define HX711_CLOCK_PIN		C,0
#define HX711_DATA_PIN		C,1

#define DIAL_CLOCK_PIN D,2  //INT0 input
#define DIAL_DATA_PIN C,2

#include <avr/io.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>


#define BAUD      115200UL
#define UBRR_BAUD   ((F_CPU/(16UL*BAUD))-1)

#define UBRR_VAL ((F_CPU+BAUD*8)/(BAUD*16)-1)   // clever runden
#define BAUD_REAL (F_CPU/(16*(UBRR_VAL+1)))     // Reale Baudrate
#define BAUD_ERROR ((BAUD_REAL*1000)/BAUD) // Fehler in Promille, 1000 = kein Fehler.

#if ((BAUD_ERROR<990) || (BAUD_ERROR>1010))
  #error Systematischer Fehler der Baudrate grösser 1% und damit zu hoch!
#endif


/// Set the specified pin high.
#define AVRPIN_SET(x)			__AVRPIN_SET(x)
#define __AVRPIN_SET(p,b)		PORT##p |= 1<<b
/// Clear the specified pin, set it low.
#define AVRPIN_CLR(x)			__AVRPIN_CLR(x)
#define __AVRPIN_CLR(p,b)		PORT##p &= ~(1<<b)
/// Set the specified pin to the given value.
#define AVRPIN_SET_VALUE(x,v)	if(v) __AVRPIN_SET(x); else __AVRPIN_CLR(x)
/// Configure the specified pin to output.
#define AVRPIN_MKOUT(x)			__AVRPIN_MKOUT(x)
#define __AVRPIN_MKOUT(p,b)		DDR##p |= 1<<b
/// Configure the specified pin to output.
#define AVRPIN_MKIN(x)			__AVRPIN_MKIN(x)
#define __AVRPIN_MKIN(p,b)		DDR##p &= ~(1<<b)
/// Read the current input pin value (PIN).
#define AVRPIN_PIN(x)			__AVRPIN_PIN(x)
#define __AVRPIN_PIN(p,b)		(PIN##p & (1<<b))

/// The DDR register of the specified pin.
#define AVRPORT_DDR(p)			__AVRPORT_DDR(p)
#define __AVRPORT_DDR(p)		(DDR##p)
/// The PIN register of the specified pin.
#define AVRPORT_PIN(p)			__AVRPORT_PIN(p)
#define __AVRPORT_PIN(p)		(PIN##p)
/// The PORT register of the specified pin.
#define AVRPORT_PORT(p)			__AVRPORT_PORT(p)
#define __AVRPORT_PORT(p)		(PORT##p)


uint8_t ihex[]={0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66};

static uint8_t hx711_last_timeh;  //timer1 high register
static uint8_t hx711_last_timel;  // ... low register
	
	
int hx711_read_32( int32_t* pvalue )
{
	int32_t value = 0;
	uint8_t i;

	if( AVRPIN_PIN( HX711_DATA_PIN ) )
	{
		return 0;
	}

   hx711_last_timel = TCNT1L;  //store timestamp
   hx711_last_timeh = TCNT1H;
	
	// clock out the bits
	for( i=0; i<24; i++ )
	{
		AVRPIN_SET( HX711_CLOCK_PIN );
		asm("nop");
		asm("nop");
		AVRPIN_CLR( HX711_CLOCK_PIN );
		value <<= 1;
		if( AVRPIN_PIN( HX711_DATA_PIN ) )
		{
			value |= 1;
		}
     asm("nop");
     asm("nop");
	}

	// select the channel and the gain for the next conversion
	AVRPIN_SET( HX711_CLOCK_PIN );
	asm("nop");
	asm("nop");
	AVRPIN_CLR( HX711_CLOCK_PIN );
   asm("nop");
   asm("nop");
	*pvalue = value;
	return 1;
}


static int32_t dial_bitmask;
static int32_t dial_result;


static uint8_t dial_last_timeh;  //timer1 high register for time stamp
static uint8_t dial_last_timel;  // ... low register
	
	

//Interrupt INT0 handler
ISR(INT0_vect)
{
   uint8_t dialbit;

   dialbit= (AVRPIN_PIN(DIAL_DATA_PIN)); //get the data anyway


if (!(dial_result&0x80000000L)) // check if read clear
{
   //check for timer overflow prior to the edge
   if  (TIFR & (1 << TOV0) )
   {
        TIFR |= (1 << TOV0);             // reset overflow flag   	

       dial_last_timel = TCNT1L;  //store timestamp
       dial_last_timeh = TCNT1H;


        dial_bitmask=0x01L;
        dial_result=0x0f000000L; //mark as new transmission

       if (dialbit)
       {
         dial_result |=dial_bitmask;
       }


   }  else
   {
     if (dial_bitmask!=0x00800000L)
     {
       dial_bitmask<<=1;
       if (dialbit)
       {
         dial_result |=dial_bitmask;
       }
     } else
     {
        dial_result|=0x10000000L; //too many bits or half transmission etc

     }
   }

     if (dial_bitmask==0x00800000L)//last bit of transmission received
     {
       dial_result|=0x80000000L; //32th bit set: new data received OK
     }

}

   TCNT0=0; //reset timer0 with each rising pulse      	
}	

int dial_read_32( int32_t* pvalue ) //1: new value available, 0: no value available
{
   int32_t value;

   if (dial_result&0x80000000L) //new value available
   {
     value=(dial_result&0x00ffffffL);
     dial_result=0x00L; //clear result
    	*pvalue = value;
   	return 1;

   } else
   {
      return 0;
   }

}


// USART initialisieren
void uart_init(void)
{
//set baud rate
    UBRRH = (uint8_t) (UBRR_BAUD>>8);
    UBRRL = (uint8_t) (UBRR_BAUD & 0x0ff);

   UCSRB = (1<<TXEN);

    // Einstellen des Datenformats: 8 Datenbits, 1 Stoppbit
    UCSRC = (1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);
}

void usend(uint8_t data)
{
        while ( !( UCSRA & (1<<UDRE)) )
            ;
        UDR = data;
}



int main(void) {
	int32_t value;

   uart_init();
   usend ('%');
   usend ('%');

//set up timestap timer: 7.3728 mhz:1024, each tick is 0.1388889 ms
//note: load cell time stamp may be inaccurate, if not polled frequently
//usually, less than 20 microsecond jitter....

   TCCR1B = (1 << CS12) |(1 << CS10);


// hx711_init
	AVRPIN_SET_VALUE( HX711_CLOCK_PIN, 0 );
	AVRPIN_MKOUT( HX711_CLOCK_PIN );
	AVRPIN_MKIN( HX711_DATA_PIN );
	

//dial readout init
   AVRPIN_MKIN( DIAL_CLOCK_PIN);
   AVRPIN_MKIN( DIAL_DATA_PIN);
 //  AVRPIN_SET( DIAL_CLOCK_PIN);
 //  AVRPIN_SET( DIAL_DATA_PIN); //pull up resistors if needed



   TCCR0 |= (1 << CS02); //:256 prescaler, overflow every ~8.85ms

   MCUCR |= (1<<ISC01)|(1<<ISC00); //ext INT0 on rising edge of dial clock
   GICR |= (1<<INT0); //enable INT0

   sei(); //enable global interrupts

	while( 1 )  //this loop for plain data out
	{
		if ( hx711_read_32( &value ) )
		{
			usend ('W');		
			usend (ihex[(value>>20)&0x0fL]);
		   usend (ihex[(value>>16)&0x0fL]);
    		usend (ihex[(value>>12)&0x0fL]);	
      	usend (ihex[(value>>8)&0x0fL]);
			usend (ihex[(value>>4)&0x0fL]);	
      	usend (ihex[value&0x0fL]);
		
   		usend ('T');		
   		usend (ihex[(hx711_last_timeh>>4)&0x0f]);
   		usend (ihex[hx711_last_timeh&0x0f]);
   		usend (ihex[(hx711_last_timel>>4)&0x0f]);
   		usend (ihex[hx711_last_timel&0x0f]);
   		
   		

   			
		}

     if( dial_read_32( &value ) )
		{
			usend ('D');		
			usend (ihex[(value>>8)&0x0fL]);
			usend (ihex[(value>>4)&0x0fL]);
			usend (ihex[value&0x0fL]);
			
			usend (ihex[(value>>20)&0x0fL]); //stats and sign
			
    		usend ('T');		
   		usend (ihex[(dial_last_timeh>>4)&0x0f]);
    		usend (ihex[dial_last_timeh&0x0f]);
   		usend (ihex[(dial_last_timel>>4)&0x0f]);
    		usend (ihex[dial_last_timel&0x0f]);


   			
		}
	}


}





