int Pin = 6;             // IN-13 controlled by pin 6
int fadeValue = 0;

int MinPWM = 7;       //  Set the PWM values that advance the bargraph by 10mm increments.  This needs to be measured
int PWM_10mm = 15;    //  for each IN-13 tube
float FactorSeg1 = 0.1*(PWM_10mm - MinPWM);  //  Set the linear correction factor for each 10mm segment
int PWM_20mm = 24;
float FactorSeg2 = 0.1*(PWM_20mm - PWM_10mm);
int PWM_30mm = 39;
float FactorSeg3 = 0.1*(PWM_30mm - PWM_20mm);
int PWM_40mm = 56;
float FactorSeg4 = 0.1*(PWM_40mm - PWM_30mm);
int PWM_50mm = 78;
float FactorSeg5 = 0.1*(PWM_50mm - PWM_40mm);
int PWM_60mm = 103;
float FactorSeg6 = 0.1*(PWM_60mm - PWM_50mm);
int PWM_70mm = 135;
float FactorSeg7 = 0.1*(PWM_70mm - PWM_60mm);
int PWM_80mm = 169;
float FactorSeg8 = 0.1*(PWM_80mm - PWM_70mm);
int MaxPWM = 205;
float FactorSeg9 = 0.067*(MaxPWM - PWM_80mm);

int BargraphLength = 95;        //  Maximum length of the bargraph display
int Millimeters;                //  Current bargraph length at any moment

void setup() {
//---------------------------------------------- Set PWM frequency for D5 & D6 -------------------------------
//NOTE: Changing this timer 0 affects millis() and delay!
  TCCR0B = TCCR0B & B11111000 | B00000001;    // set timer 0 divisor to     1 for PWM frequency of 62500.00 Hz

  analogWrite(Pin, 0);   //  Start out by zeroing the bargraph
  delay(2000);
}

void loop() {
  {for (Millimeters = 0 ; Millimeters <= BargraphLength; Millimeters += 1) {  // Sweep up from the current position to max
    SendToIN13();
    delay(1000);
  }
   delay(64000);

   for (Millimeters = 95 ; Millimeters >= 0; Millimeters -= 1) {  //  Sweep down from max to min
   SendToIN13();
   delay(1000);
  }
   delay(64000);
  }
}

// This subroutine converts millimeters of bargraph into a corresponding PWM signal "fadeValue"
void SendToIN13()
{ if (Millimeters <= 10) fadeValue = MinPWM + Millimeters * FactorSeg1;
  else if (Millimeters <= 20) fadeValue = PWM_10mm + ((Millimeters - 10) * FactorSeg2);   
  else if (Millimeters <= 30) fadeValue = PWM_20mm + ((Millimeters - 20) * FactorSeg3);
  else if (Millimeters <= 40) fadeValue = PWM_30mm + ((Millimeters - 30) * FactorSeg4);  
  else if (Millimeters <= 50) fadeValue = PWM_40mm + ((Millimeters - 40) * FactorSeg5);  
  else if (Millimeters <= 60) fadeValue = PWM_50mm + ((Millimeters - 50) * FactorSeg6);  
  else if (Millimeters <= 70) fadeValue = PWM_60mm + ((Millimeters - 60) * FactorSeg7);
  else if (Millimeters <= 80) fadeValue = PWM_70mm + ((Millimeters - 70) * FactorSeg8);   
  else                        fadeValue = PWM_80mm + ((Millimeters - 80) * FactorSeg9); 
  analogWrite(Pin, fadeValue);
}
