#include "main.h"
#include "options.h"
#include "register.h"
              
     
#define SH_SET rFIO0SET|=(1<<8)   //
#define SH_CLR rFIO0CLR|=(1<<8)   // shift

#define ST_SET rFIO0SET|=(1<<7)   //
#define ST_CLR rFIO0CLR|=(1<<7)   // store
    
#define DS_SET rFIO0SET|=(1<<6)   //
#define DS_CLR rFIO0CLR|=(1<<6)   // data

#ifdef SC8v7_ADRF5040
#define PWR_PIN_EN       rFIO0SET|=(1<<9)   // enable power
#define PWR_PIN_DS       rFIO0CLR|=(1<<9)   // disable power
#endif

int InitRegister( void )
{
        
   rPINSEL0 &= ~((1<<12)|(1<<13)|(1<<14)|(1<<15)|(1<<16)|(1<<17)|(1<<18)|(1<<19)); // GPIO 

   rPINMODE0 = (rPINMODE0 & (~((1<<12)|(1<<13)|(1<<14)|(1<<15)|(1<<16)|(1<<17)|(1<<18)|(1<<19)))) | ((1<<13)|(1<<15)|(1<<17)|(1<<19)); // Without pull-resistors

   rPINMODE_OD0 = rPINMODE_OD0 & (~((1<<6)|(1<<7)|(1<<8)|(1<<9)));  // Turn off Open Drain mode

   rFIO0DIR |= (1<<6)|(1<<7)|(1<<8)|(1<<9); // Output     
   
   rFIO0CLR |= (1<<6)|(1<<7)|(1<<8)|(1<<9); // Zeros
   
   #ifdef SC8v7_ADRF5040
   PWR_PIN_EN;           // enable RF-Board power via MCU-PIN
   #endif
   return 1;
}   


   
static void Wait( int count )
{
  while(count--);
}    

static void WaitShift(  void  )
{
  // тактовая частота 12МГц    ----> 100KHz
  Wait(12);
}  

static void WaitSet(  void  )
{
  // тактовая частота 12МГц    ----> 100KHz
  Wait(12);
}     

  
static void ShiftChar( char a )
{    
  for(int i = 7;i>=0; i-- )
  {    
    SH_CLR;
    if( a & (1<<i) )
      DS_SET;
    else
      DS_CLR; 
    WaitSet();  // wait for setup DATA on DS line
    SH_SET;
    WaitShift();   
  }
}

static void Store( void )
{
  ST_SET; 
  Wait(12);
  ST_CLR;
}            
  
static void Idle( void )
{
  SH_CLR;
  ST_CLR; 
  DS_CLR;
}   

void ShiftRegisterOutData( char * data, int count )
{   
  Idle();
  while( count -- ) ShiftChar( *data++ );
  Store(); 
  Idle();
}        

