#include <rgb_lcd.h>
#include <si5351.h>

char version[] = "v0.1";

const long bandStart = 5000000;    // 
const long bandEnd = 30000000;      // 

volatile long freq = 10144000;         // this is a variable (changes) - set it to the beginning of the band
volatile long radix = 1000;           // how much to change the frequency by, clicking the rotary encoder will change this.
volatile long oldfreq = 0;

const long cwoffset = 700;

volatile long currentfreq = 0;
volatile int updatedisplay = 0;

// Rotary encoder pins and other inputs
static const int rotAPin = 2;
static const int rotBPin = 3;
static const int pushSwPin = 4;


// Rotary encoder v(designing for a 50 ohm impedanceariables, used by interrupt routines
volatile int rotState = 0;
volatile int rotAval = 1;
volatile int rotBval = 1;

volatile int Even_Divisor = 0;
volatile int oldEven_Divisor = 0;

int digit1 = 0;
int digit2 = 0;
int digit3 = 0;
int digit4 = 0;   
int digit5 = 0;
int digit6 = 0;
int digit7 = 0;
int digit8 = 0;

// Instantiate the Objects
rgb_lcd lcd;
Si5351 si5351;

void setup()
{
  // Set up frequency and radix switches
  pinMode(rotAPin, INPUT_PULLUP);
  pinMode(rotBPin, INPUT_PULLUP);
  pinMode(pushSwPin, INPUT_PULLUP);
  

  // Set up interrupt pins
  attachInterrupt(digitalPinToInterrupt(rotAPin), ISRrotAChange, CHANGE);
  attachInterrupt(digitalPinToInterrupt(rotBPin), ISRrotBChange, CHANGE);

  // Initialize the display
  lcd.begin(16, 2);

  lcd.cursor();

  // Initialize the Si5351
  si5351.init(SI5351_CRYSTAL_LOAD_8PF, 0, 0);
  si5351.set_correction(-39750, SI5351_PLL_INPUT_XO);
  si5351.set_pll(SI5351_PLL_FIXED, SI5351_PLLA);
  si5351.drive_strength(SI5351_CLK0, SI5351_DRIVE_8MA);
  si5351.drive_strength(SI5351_CLK2, SI5351_DRIVE_8MA);
  
  // Update display and send start frequency
  UpdateDisplay();
  SendFrequency();
}


void loop()
{
  // Check to see if the freq has changed
  currentfreq = getfreq();                    // Interrupt safe method to get the current frequency

  if (currentfreq != oldfreq)
  {
    UpdateDisplay();
    SendFrequency();
    oldfreq = currentfreq;
  }

  // Check the rotary encoder (radix) swith
  if (digitalRead(pushSwPin) == LOW)           // Read the rotary encoder switch
  {
    delay(10);
    while (digitalRead(pushSwPin) == LOW)
    {
      if (updatedisplay == 1)
      {
        UpdateDisplay();
        updatedisplay = 0;
      }
    }
    delay(50);
  }

  
}


long getfreq()
{
  long temp_freq;
  cli();
  temp_freq = freq;
  sei();
  return temp_freq;
}


// Interrupt routines
void ISRrotAChange()
{
  if (digitalRead(rotAPin))
  {
    rotAval = 1;
    UpdateRot();
  }
  else
  {
    rotAval = 0;
    UpdateRot();
  }
}


void ISRrotBChange()
{
  if (digitalRead(rotBPin))
  {
    rotBval = 1;
    UpdateRot();
  }
  else
  {
    rotBval = 0;
    UpdateRot();
  }
}


// Determine which way the rotary encoder is rotating and action as required
void UpdateRot()
{
  switch (rotState)
  {
    case 0:                                         // Idle state, look for direction
      if (!rotBval)
        rotState = 1;                               // CW 1
      if (!rotAval)
        rotState = 11;                              // CCW 1
      break;

    case 1:                                         // CW, wait for A low while B is low
      if (!rotBval)
      {
        if (!rotAval)
        {
          // either increment the radix or freq
          if (digitalRead(pushSwPin) == LOW)
          {
            updatedisplay = 1;
            if (radix == 10000000)
              radix = 1000000;
            else if (radix == 1000000)
              radix = 100000;
            else if (radix == 100000)
              radix = 10000;
            else if (radix == 10000)
              radix = 1000;
            else if (radix == 1000)
              radix = 100;
            else if (radix == 100)
              radix = 10;
        //    else if (radix == 10)
        //      radix = 1;
            else
              radix = 10000000;
          }
          else
          {
            freq = (freq + radix);
            
            if (freq > bandEnd)
              freq = bandEnd;
          }
          rotState = 2;                             // CW 2
        }
      }
      else if (rotAval)
        rotState = 0;                               // It was just a glitch on B, go back to start
      break;

    case 2:                                         // CW, wait for B high
      if (rotBval)
        rotState = 3;                               // CW 3
      break;

    case 3:                                         // CW, wait for A high
      if (rotAval)
        rotState = 0;                               // back to idle (detent) state
      break;

    case 11:                                        // CCW, wait for B low while A is low
      if (!rotAval)
      {
        if (!rotBval)
        {
          // either decrement the radix or freq
          if (digitalRead(pushSwPin) == LOW)
          {
            updatedisplay = 1;
            //if (radix == 1)
            //  radix = 10;
            if (radix == 10)
              radix = 100;
            else if (radix == 100)
              radix = 1000;
            else if (radix == 1000)
              radix = 10000;
            else if (radix == 10000)
              radix = 100000;
            else if (radix == 100000)
              radix = 1000000;
            else if (radix == 1000000)
              radix = 10000000;
            else
              radix = 10;
          }
          else
          {
            freq = (freq - radix);
            
            if (freq < bandStart)
              freq = bandStart;
          }
          rotState = 12;                            // CCW 2
        }
      }
      else if (rotBval)
        rotState = 0;                               // It was just a glitch on A, go back to start
      break;

    case 12:                                        // CCW, wait for A high
      if (rotAval)
        rotState = 13;                              // CCW 3
      break;

    case 13:                                        // CCW, wait for B high
      if (rotBval)
        rotState = 0;                               // back to idle (detent) state
      break;
  }
}


void UpdateDisplay()
{

  
    digit1 = (freq%10);
    digit2 = ((freq/10)%10);
    digit3 = ((freq/100)%10);
    digit4 = ((freq/1000)%10);   
    digit5 = ((freq/10000)%10);
    digit6 = ((freq/100000)%10);
    digit7 = ((freq/1000000)%10);
    digit8 = ((freq/10000000)%10);
   
    
  lcd.setCursor(0,0);
  lcd.print(digit8);
  
  lcd.setCursor(1,0);
  lcd.print(digit7);
  
  lcd.setCursor(2,0);
  lcd.print(",");
  
  lcd.setCursor(3,0);
  lcd.print(digit6);
  
  lcd.setCursor(4,0);
  lcd.print(digit5);
  
  lcd.setCursor(5,0);
  lcd.print(digit4);
  
  lcd.setCursor(6,0);
  lcd.print(".");
  
  lcd.setCursor(7,0);
  lcd.print(digit3);
  
  lcd.setCursor(8,0);
  lcd.print(digit2);

 // lcd.setCursor(9,0);
 // lcd.print(digit1);
  
lcd.setCursor(0,1);
lcd.print("5-30MHz CW");

lcd.setCursor(12,1);
lcd.print(version);

lcd.setCursor(9,0);
lcd.print("kHz IQ");

 if (radix == 1)
    lcd.setCursor(9, 0);
  if (radix == 10)
    lcd.setCursor(8, 0);
  if (radix == 100)
    lcd.setCursor(7, 0);
  if (radix == 1000)
    lcd.setCursor(5, 0);
  if (radix == 10000)
    lcd.setCursor(4, 0);
  if (radix == 100000)
    lcd.setCursor(3, 0);
  if (radix == 1000000)
    lcd.setCursor(1, 0);
  if (radix == 10000000)
    lcd.setCursor(0, 0);


  
}





void EvenDivisor()
{
  if (freq < 6850000)
  {
    Even_Divisor = 126;
  }
  if ((freq >= 6850000) && (freq < 9500000))
  {
    Even_Divisor = 88;
  }
  if ((freq >= 9500000) && (freq < 13600000))
  {
    Even_Divisor = 64;
  }
  if ((freq >= 13600000) && (freq < 17500000))
  {
    Even_Divisor = 44;
  }
  if ((freq >= 17500000) && (freq < 25000000))
  {
    Even_Divisor = 34;
  }
  if ((freq >= 25000000) && (freq < 36000000))
  {
    Even_Divisor = 24;
  }
  if ((freq >= 36000000) && (freq < 45000000)) {
    Even_Divisor = 18;
  }
  if ((freq >= 45000000) && (freq < 60000000)) {
    Even_Divisor = 14;
  }
  if ((freq >= 60000000) && (freq < 80000000)) {
    Even_Divisor = 10;
  }
  if ((freq >= 80000000) && (freq < 100000000)) {
    Even_Divisor = 8;
  }
  if ((freq >= 100000000) && (freq < 146600000)) {
    Even_Divisor = 6;
  }
  if ((freq >= 150000000) && (freq < 220000000)) {
    Even_Divisor = 4;
  }
}


void SendFrequency()
{
  EvenDivisor();
  si5351.set_freq_manual((freq - cwoffset) * SI5351_FREQ_MULT, Even_Divisor * freq * SI5351_FREQ_MULT, SI5351_CLK0);
  si5351.set_freq_manual((freq - cwoffset) * SI5351_FREQ_MULT, Even_Divisor * freq * SI5351_FREQ_MULT, SI5351_CLK2);
  si5351.set_phase(SI5351_CLK0, 0);
  si5351.set_phase(SI5351_CLK2, Even_Divisor);
 
if(Even_Divisor != oldEven_Divisor)
  {
    si5351.pll_reset(SI5351_PLLA);
    oldEven_Divisor = Even_Divisor;
  }
}
//void SendFrequency()
//{
//  si5351.set_freq((freq * 100ULL), SI5351_CLK0);
//}
