calculate the current phase of the moon

Опубликовано 07 Фев 2015
Автор:

byte getPhase(int Y, int M, int D) {  // calculate the current phase of the moon
  double AG, IP;                      // based on the current date
  byte phase;                         // algorithm adapted from Stephen R. Schmitt's
                                      // Lunar Phase Computation program, originally
  long YY, MM, K1, K2, K3, JD;        // written in the Zeno programming language
                                      // http://home.att.net/~srschmitt/lunarphasecalc.html
  // calculate julian date
  YY = Y - floor((12 - M) / 10);
  MM = M + 9;
  if(MM >= 12)
    MM = MM - 12;

  K1 = floor(365.25 * (YY + 4712));
  K2 = floor(30.6 * MM + 0.5);
  K3 = floor(floor((YY / 100) + 49) * 0.75) - 38;

  JD = K1 + K2 + D + 59;
  if(JD > 2299160)
    JD = JD -K3;

  IP = normalize((JD - 2451550.1) / 29.530588853);
  AG = IP*29.53;

  if(AG < 1.20369)
    phase = B00000000;
  else if(AG < 3.61108)
    phase = B00000001;
  else if(AG < 6.01846)
    phase = B00000011;
  else if(AG < 8.42595)
    phase = B00000111;
  else if(AG < 10.83323)
    phase = B00001111;
  else if(AG < 13.24062)
    phase = B00011111;
  else if(AG < 15.64800)
    phase = B00111111;
  else if(AG < 18.05539)
    phase = B00111110;
  else if(AG < 20.46277)
    phase = B00111100;
  else if(AG < 22.87016)
    phase = B00111000;
  else if(AG < 25.27754)
    phase = B00110000;
  else if(AG < 27.68493)
    phase = B00100000;
  else
    phase = 0;

  return phase;
}

double normalize(double v) {           // normalize moon calculation between 0-1
    v = v - floor(v);
    if (v < 0)
        v = v + 1;
    return v;
}

byte decToBcd(byte val) {            // Convert normal decimal numbers to binary coded decimal
  return ((val / 10 * 16) + (val % 10));
}

byte bcdToDec(byte val) {            // Convert binary coded decimal to normal decimal numbers
  return ((val / 16 * 10) + (val % 16));
}