// *** 8Mhz or 16Mhz version relies on speed selected in IDE ***
// Updated May 2022 D6=75:25 mixer, D7=50:50 mixer, (D6 AND D7)=60:40 mixer
// Updated Nov 2021 for new MK PCB, has throttle reverse on D2. Same sketch runs on a 2018 DIY-More with dipswitch.
// Please note this is dated Feb 2020 and has a small change over the previous version - pins D6 and D8 are swapped (75:25 mix and minute-minder button)
// This puts the two mixer options side by side which makes more sense and also permits the optional use of an 8-way Dipswitch instead of links on header pins.
//
// New in V2: AETR/TAER/ETAR channel maps with auto Spek 400uS, buzzer moved, expo, rates, ch7 speed, 1100-1900 range,  two S/C keying speeds,
// interrupt-driven ppm, dual (+/-) stick mapping, minute-minder, revised audio tones
// Please note that the calibration procedure is different to the previous version, see below.
//
// A simple seven channel PPM encoder. Six propo, one switched with servo-slow, single-channel escapement emulation mix, Vtail, Elevons, minute-minder etc
// Please do not use Arduino bootloader for programming, its startup delay messes things up and can strip servo gears with some modules (eg Corona)
// Connections:
// Pots are wired between ground and regulated 5v from Arduino. Wipers connected as follows:
// A0=aileron, A1=elevator, A2=rudder, A3=throttle, A4=aux1, A5=aux2,  A6=expo, A7=rates. Always use this wiring order regardless of PPM channel order.
// Ground A6 and A7 with links or Spektrum bind-plugs if rates & expo are not required. Dont leave them floating.
// If fewer analogue channels are used, tie unused ones to a used one, do not leave floating. Eg on a 4ch set, tie A4 to aileron wiper, A5 to elevator wiper
// Unwanted digital functions can be omitted except for button on D10 or D11 which is needed for calibrating the sticks. Omitting ch7 toggle (D12) means no range test.
// Note that the DIY More ProMini Strong has annotations for D0 and D1 reversed - the pins actually number 10234567.
// D0=PPM, D1=S/C escapement speed, D2=throttle reverse, D3=ch7 speed, D4&5=channel order, D6=75:25 mixer, D7=50:50 mixer, (D6 AND D7)=60:40 mixer
// D8=increment minute timer, D9=throttle lock, D10=sequential s/c, D11=compound s/c, D12=ch7 toggle switch, D13=buzzer NPN base, collector to battery pos,
// ... emmitter to buzzer+, buzzer- to neg (emitter follower). Parallel haptic with buzzer. Used for minute minder, inactivity timer & throttle-lock warning.
// Features:
// Calibration - center trims, hold either s/c button in, switch on, still holding button move all controls to extremes including auxilliary pots
// Center all controls including throttle and aux pots. Release button.  At this point the throttle-lock warning should chirp because the throttle is centred.
// Do not switch off during calibration, the calibration values cant be saved if the set has been switched off!
// Throttle response can optionally be made non-linear during calibration by 'centering' the throttle stick to say 2/3 rather than to neutral stick.
// Variable expo & rates on Futaba ch1, 2 & 4, ditto JR ch2, 3 & 4. Elevon mixer on Futaba ch1 & ch2, JR ch2 & 3, 75% aileron, 25% elevator or 50:50 for V-tails
// Mixer option can only be changed on power-up (avoids accidentally switching during flight).  Single-channel emulation mix, compound or sequential.
// Flick toggle 3x for range test.  Servo reversing by holding sticks over on power up (saved to eeprom). Servo-slow on channel 7 toggle.
// Auto and manual throttle-lock with warning.
// Follow the story on the single-channel forum http://mode-zero.uk/viewtopic.php?f=27&t=844
// Diagram and documentation on http://www.singlechannel.co.uk see Archive page
// If you use this software in whole or in part please acknowledge its source - Phil_G on most forums, philg@talk21.com  http://www.singlechannel.co.uk
// Special thanks to the late Dave Burton and Mike Kitchen for their improved expo maths, and Hasi for the interrupt-driven ppm.
// Thanks also to testers Ron, Shaun, Pat, Frank and Al

#define full_n -400 // full negative deflection of sticks
#define full_p +400 // full positive deflection of sticks
#define ppmOutputPin 0  // set the PPM signal output pin,  D0 for DIYMore 328P boards
#define ppmwidth 300
#define onState 1  //set polarity of the pulses: 1 is positive, 0 is negative
#define num_channels 7  //set the number of PPM channels
#define PPM_FrLen 20000  //set the PPM frame length in microseconds (1ms = 1000us)
#define neutralPulse 1500
#define sc_speed  1  // *** remember DIYMore board has D0 and D1 reversed ***
#define thr_rev   2  // throttle reverse, use with care with electrics!
#define ch7speed  3  // slow or slower
#define ch_order1 4  // D4&D5 open = AETR, D4 linked = TAER127, D5 linked = TAER712 & 400uS, D4&D5 linked = ETAR
#define ch_order2 5  // D4&D5 open = AETR, D4 linked = TAER127, D5 linked = TAER712 & 400uS, D4&D5 linked = ETAR
#define mix_75    6  // mixer 75:25  \  both D6 & D7 for 60:40
#define mix_50    7  // mixer 50:50  /
#define min_tmr   8  // set/clear minute minder
#define sw_cut    9  // throttle-cut toggle
#define sw_seq   10  // pushbutton for s/c sequential
#define sw_btn   11  // pushbutton for s/c compound
#define sw_tog   12  // toggle channel 7
#define buzzer   13  // inactivity buzzer & haptic
#define INACTFRAMES 30000  // 10 minutes

int slow_val, raw, flips, ch, calibrated = 1, stickcalHi[] = {0, 0, 0, 0, 0, 0}, stickcalLo[] = {1023, 1023, 1023, 1023, 1023, 1023}, stickcalMid[] = {512, 512, 512, 512, 512, 512};
int a0_val, chtemp, mix_option = 0, contrl_pos[] = {1500, 1500, 1500, 1500, 1500, 1500, 1500, 8000}; // last is sync
int lastch7, cchannel7, slow, sweep, min_minder = 0, PPM_PulseLen = ppmwidth;  //set the pulse length
long int expo, rates, input, expoCalc1, expoCalc2, expoCalc3, mins;
byte reverse[] = {0, 0, 0, 0, 0, 0}, rangetest = 0, flip = 0, flipped = 0;
static int rotor28[] = { -36, -72, -108, -144, -180, -216, -252, -216, -180, -144, -108, -72, -36,  0,  36,  72, 108, 144, 180, 216, 252, 216, 180, 144, 108, 72, 36, 0};
static int rotor24[] = { -42, -84, -126, -168, -210, -252, -210, -168, -126,  -84,  -42,   0,  42, 84, 126, 168, 210, 252, 210, 168, 126,  84,  36,   0,   0,  0,  0, 0};
byte tlock = 1, rotorptr = 0, timer_flg = 0;
float scrudder = 0, scelev = 0;
unsigned int inact = 0, fiftyhz = 0, tmr_held = 0;
volatile int ppm[num_channels] = {1500, 1500, 1500, 1500, 1500, 1500, 1500}, sync, framecounter = 0;

#include <EEPROM.h>

void setup()  {
  pinMode(ppmOutputPin, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(mix_50, INPUT_PULLUP);
  pinMode(mix_75, INPUT_PULLUP);
  pinMode(sw_cut, INPUT_PULLUP);
  pinMode(sw_seq, INPUT_PULLUP);
  pinMode(sw_btn, INPUT_PULLUP);
  pinMode(sw_tog, INPUT_PULLUP);
  pinMode(ch_order1, INPUT_PULLUP);
  pinMode(ch_order2, INPUT_PULLUP);
  pinMode(ch7speed, INPUT_PULLUP);
  pinMode(sc_speed, INPUT_PULLUP);
  pinMode(min_tmr, INPUT_PULLUP);
  pinMode(thr_rev, INPUT_PULLUP);

  for (ch = 0; ch < 3; ++ch) {
    digitalWrite(buzzer, HIGH);
    delay(30);
    digitalWrite(buzzer, LOW);
    delay(30);
  }

  while (digitalRead(sw_btn) == 0 || digitalRead(sw_seq) == 0) {  // calibrate sticks
    calibrated = 0;
    for (int stick = 0; stick < 6; ++stick) {
      raw = analogRead(stick);
      if (raw > stickcalHi[stick]) stickcalHi[stick] = raw;
      if (raw < stickcalLo[stick]) stickcalLo[stick] = raw;
      stickcalMid[stick] = raw;  // save neutral sticks as button is released
    }
  }  // calibrate button released

  if (calibrated == 0) {
    for (ch = 0; ch < 6; ch++) {
      EEPROMWriteInt(ch * 6,     stickcalLo[ch]);   // eeprom locations  0,  6, 12, 18, 24, 30  (decimal)
      EEPROMWriteInt(ch * 6 + 2, stickcalMid[ch]);  // eeprom locations  2,  8, 14, 20, 26, 32  (decimal)
      EEPROMWriteInt(ch * 6 + 4, stickcalHi[ch]);   // eeprom locations  4, 10, 16, 22, 28, 34  (decimal)
    }
    calibrated = 1;
  }

  for (ch = 0; ch < 6; ch++) {
    stickcalLo[ch]  = EEPROMReadInt(ch * 6);        // eeprom locations  0,  6, 12, 18, 24, 30  (decimal)
    stickcalMid[ch] = EEPROMReadInt(ch * 6 + 2);    // eeprom locations  2,  8, 14, 20, 26, 32  (decimal)
    stickcalHi[ch]  = EEPROMReadInt(ch * 6 + 4);    // eeprom locations  4, 10, 16, 22, 28, 34  (decimal)
    reverse[ch] = EEPROM.read(ch + 36) & 1;         // eeprom locations 36, 37, 38, 39, 40, 41  (decimal)
  }

  slow = digitalRead(sw_tog) == 0 ? full_p : full_n; // initial channel 7 value

  if (digitalRead(mix_50) == 0) mix_option = 5050;
  if (digitalRead(mix_75) == 0) mix_option = 7525;
  if (digitalRead(mix_75) == 0 && digitalRead(mix_50) == 0) mix_option = 6040;

  if (digitalRead(ch_order1) == 1 && digitalRead(ch_order2) == 0) PPM_PulseLen = 400; else PPM_PulseLen = 300; //set Spekky pulse length TAER7A1A2

  // check for reversing, stick over on power-up, throttle rev on D2
  for (ch = 0; ch < 3; ch++) {
    contrl_pos[ch] = map(analogRead(ch), stickcalLo[ch], stickcalHi[ch], full_n, full_p);
    if (contrl_pos[ch] > full_p - 50 || contrl_pos[ch] < full_n + 50) {
      reverse[ch] ^= B00000001;
      EEPROM.write(36 + ch, reverse[ch]);
    }
  }
  reverse[3] = 1 - digitalRead(thr_rev);          // throttle reverse on D2
  reverse[4] = 0; reverse[5] = 0;                 // no aux reverse

  digitalWrite(ppmOutputPin, !onState);  // set the PPM signal pin to the default state (off)
  cli();
  TCCR1A = 0; // set entire TCCR1 register to 0
  TCCR1B = 0;
  OCR1A = 100;  // compare match register, change this
  TCCR1B |= (1 << WGM12);  // turn on CTC mode
  TCCR1B |= (1 << CS11);  // 8 prescaler: 0,5 microseconds at 16mhz
  TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
  sei();
}

void loop() {

  // read sticks
  for (ch = 0; ch < 6; ch++) {
    raw = analogRead(ch);
    if (raw > stickcalMid[ch]) contrl_pos[ch] = map (raw, stickcalMid[ch], stickcalHi[ch], 0, full_p);
    else contrl_pos[ch] = map (raw, stickcalLo[ch], stickcalMid[ch], full_n, 0);
  }

  // Optionally, and only if you fully understand the array allocations, you can set any unused analogues here instead of
  // paralleling unused analogue inputs.  Either method prevents floating inputs 'wandering' or following an adjacent pin.
  // Physical wiring is: A0=aileron stick pot, A1=elevator, A2=rudder, A3=throttle, A4=aux1, A5=aux2, and
  // A0 is your 'primary steering' control - on a rudder/elevator/throttle set, the rudder servo is plugged into the aileron channel. SOP.
  // Array numbering is: contrl_pos[0]=aileron stick pot, contrl_pos[1]=elevator, contrl_pos[2]=rudder, contrl_pos[3]=throttle,
  // contrl_pos[4]=aux1, contrl_pos[5]=aux2.
  // So for example on a 3ch set, zero the rudder, aux1 & aux2 elements (contrl_pos[0] is primary steering) like this:

  // contrl_pos[2]=0; contrl_pos[4]=0; contrl_pos[5]=0; // example for a 3ch rudder-elevator-throttle set
  // contrl_pos[4]=0; contrl_pos[5]=0; // example for a 4ch aileron-elevator-rudder-throttle set


  // single-channel emulation
  scrudder = 0;

  // compound button
  if (rotorptr == 0 && digitalRead(sw_btn) == 0) ++rotorptr; // if esc is at rest and we press the button, start the rotation
  if (rotorptr != 0) {
    scelev = 0;

    if (digitalRead(sc_speed) == 0) {
      scrudder = rotor24[rotorptr];
      if (digitalRead(sw_btn) == 0 && (rotorptr == 5 || rotorptr == 17)) --rotorptr; // do pawl stops @ 90 and 270 degrees
      if (digitalRead(sw_btn) == 0 && rotorptr == 22) {
        --rotorptr;  // do pawl stops @ 355 degrees kue
        scelev = 250;
      }
      ++rotorptr; if (rotorptr == 24) rotorptr = 0;
    }
    else {
      scrudder = rotor28[rotorptr];
      if (digitalRead(sw_btn) == 0 && (rotorptr == 6 || rotorptr == 20)) --rotorptr; // do pawl stops @ 90 and 270 degrees
      if (digitalRead(sw_btn) == 0 && rotorptr == 26) {
        --rotorptr;  // do pawl stops @ 355 degrees kue
        scelev = 250;
      }
      ++rotorptr; if (rotorptr == 28) rotorptr = 0;
    }
  }

  // sequential button
  if (digitalRead(sw_seq) == 1) flipped = 0;
  else {
    if (flipped == 0) {
      flip ^= 1;
      flipped = 1;
    }
    scrudder = flip == 0 ? -250 : 250;
  }

  contrl_pos[0] = contrl_pos[0] + scrudder;
  contrl_pos[1] = contrl_pos[1] + scelev;

  // throttle cut/hold-off
  if (digitalRead(sw_cut) == 0) tlock = 1;
  if (digitalRead(sw_cut) == 1 && contrl_pos[3] < (full_n + 60)) tlock = 0;
  if (contrl_pos[3] > (full_n + 60) && tlock) {
    if (bitRead(fiftyhz, 0) && bitRead(fiftyhz, 5) && bitRead(fiftyhz, 3)) digitalWrite(buzzer, HIGH); else digitalWrite(buzzer, LOW);
  }
  if (tlock) contrl_pos[3] = full_n;

  // do slow flap/retract channel. digitalRead(ch7speed) * 5 + 5 gives 5 or 10uS increments per frame, so at 50fps, 800uS takes 3.2 sscs or 1.6 secs
  slow_val = digitalRead(ch7speed) * 15 + 5;  // 5uS or 20uS increments per frame, so at 50fps, 800uS takes 3.2 secs or 0.8 secs
  if (digitalRead(sw_tog) == 0) {
    cchannel7 = full_p;
    if (slow < full_p) slow += slow_val;
  }
  if (digitalRead(sw_tog) == 1) {
    cchannel7 = full_n;
    if (slow > full_n) slow -= slow_val;
  }
  contrl_pos[6] = slow;
  a0_val = contrl_pos[0];

  /*Rates and Expo.   With thanks to Mike Kitchen and Prof Dave Burton RIP = Phil
     We apply expo first and then the rates
     Original Expo Formula by Prof Dave Burton and coded by Mike Kitchen
     The expo calculation is not "true" exponential but a cubic polynominal approximating an exponential function
     The basic form of the expo equation is: output = ((1 - expo) * input) + (expo * input^3)
     The formula can be re-written as: output = input - (expo * input) + (expo * input^3)
     where  -1 <= output  =< 1, 0 <= expo =< 1 and -1<= input =< 1.
     But we need -500 <= output =< 500, 0 <= expo =< 100 and -500 <= input =< 500 (ie the input and output in the range +/-500 and expo in the range 0-100)
     If we re-arrange for input and output +/-500 and expo 0 to 100 then we get the following formula
     output = input - (expo * input /100) + (expo * input * input * input)/25,000,000
     Expo is set by the expo pot in the range 0-1023. Map this to 0% to 100%.

     The rates formula is output = input * pot value / 1023   (hence need inverting to match Phil_G rates+
     where input and output are in the range +/-500 and pot value in the range 0-1023

  */

  expo = (long) map(analogRead(A6), 0, 1023, 0, 100); //read the expo pot and map into the range 0 to 100
  rates = (long) 1023 - analogRead(A7); //read the rates pot and leave in the range 0 - 1023
  if (rates < 100) rates = 100;
  for (ch = 0; ch < 3; ch++) { // for aileron, elevator and rudder
    input = (long int) contrl_pos[ch];
    expoCalc1 = input * expo / 100; //Do the first element of the calculation
    expoCalc2 = (input * input * input) / 100L; //Do the second element of the calculation in two stages to ensure it doesn't overflow "long" variable ie divide by 100 and then a further 250,000
    expoCalc2 = expoCalc2 * expo / 158000L;  // 250000L for +-500.  Ths value is adjusted for +-400.
    expoCalc3 = input - expoCalc1 + expoCalc2;  //Sum the three terms of the expo calc
    contrl_pos[ch] = (int) (expoCalc3 * rates / 1023); // the rates calculation
  }

  /*End of new expo and rates */

  // do timed stuff
  if (cchannel7 != lastch7) {
    ++flips;
    framecounter = 0;
  }
  if (framecounter < 15 && flips > 5) {
    rangetest ^= 1; // this flags the 3 flicks 'active'
    framecounter = 15;
  }
  if (framecounter > 14) flips = 0;
  lastch7 = cchannel7;

  // if rangetest selected, waggle rudder (ch1) whilst holding throttle low
  if (rangetest == 1) {
    tlock = 1; // apply throttle lock
    if (framecounter == 50) {
      framecounter = 0;
      flip ^= 1;
    }
    contrl_pos[0] = flip == 0 ? -250 : 250;
    if (a0_val < -150 || a0_val > 150) rangetest = 0;
    if (digitalRead(sw_tog) == 0) contrl_pos[6] = full_n; else contrl_pos[6] = full_p;
  }

  // format the frame
  for (ch = 0; ch < 7; ch++) {
    contrl_pos[ch] += neutralPulse;
    contrl_pos[ch] = constrain(contrl_pos[ch], 900, 2100);
    if (reverse[ch] == 1) contrl_pos[ch] = 3000 - contrl_pos[ch];
  }

  // check if mixer switched in
  if (mix_option == 5050) {
    contrl_pos[0] /= 2;
    contrl_pos[1] /= 2;
    chtemp = contrl_pos[1];
    contrl_pos[1] = contrl_pos[0] + 1500 - contrl_pos[1];
    contrl_pos[0] += chtemp;
  }

  if (mix_option == 7525) {
    contrl_pos[0] *= 3;
    contrl_pos[0] /= 4;
    contrl_pos[1] /= 4;
    chtemp = contrl_pos[1];
    contrl_pos[1] = contrl_pos[0] + 750 - contrl_pos[1];
    contrl_pos[0] += chtemp;
  }
  if (mix_option == 6040) {
    contrl_pos[0] *= 6;
    contrl_pos[0] /= 10;
    contrl_pos[1] *= 4;
    contrl_pos[1] /= 10;
    chtemp = contrl_pos[1];
    contrl_pos[1] = contrl_pos[0] + 1200 - contrl_pos[1];
    contrl_pos[0] += chtemp;
  }

  // this puts the servo positions in Futaba or Spektrum/JR channel order as required
  if (digitalRead(ch_order1) == 1 && digitalRead(ch_order2) == 1) { // AETRA1A27
    chtemp = contrl_pos[3];
    contrl_pos[3] = contrl_pos[2];
    contrl_pos[2] = chtemp;
  }
  if (digitalRead(ch_order1) == 1 && digitalRead(ch_order2) == 0) { // TAER7A1A2
    chtemp = contrl_pos[3];  // save throttle
    contrl_pos[3] = contrl_pos[2];
    contrl_pos[2] = contrl_pos[1];
    contrl_pos[1] = contrl_pos[0];
    contrl_pos[0] = chtemp;
    chtemp = contrl_pos[4]; // save aux1
    contrl_pos[4] = contrl_pos[6]; contrl_pos[6] = contrl_pos[5]; contrl_pos[5] = chtemp;
  }
  if (digitalRead(ch_order1) == 0 && digitalRead(ch_order2) == 1) { // TAERA1A27 as per old encoder
    chtemp = contrl_pos[3];  // save throttle
    contrl_pos[3] = contrl_pos[2];
    contrl_pos[2] = contrl_pos[1];
    contrl_pos[1] = contrl_pos[0];
    contrl_pos[0] = chtemp;
  }
  if (digitalRead(ch_order1) == 0 && digitalRead(ch_order2) == 0) { // ETARA1A27
    chtemp = contrl_pos[0];  // save aileron
    contrl_pos[0] = contrl_pos[1];
    contrl_pos[1] = contrl_pos[3];
    contrl_pos[3] = contrl_pos[2];
    contrl_pos[2] = chtemp;
  }

  cli();
  for (ch = 0; ch < num_channels; ch++) ppm[ch] = contrl_pos[ch];
  sei();

  while (sync == 0);  sync = 0; // wait for sync so 20ms per loop() iteration

  // hold button to set minute-minder
  if (digitalRead(min_tmr) == 0) { // minute minder button pressed
    if (++min_minder == 30) {
      timer_flg = 1;
      digitalWrite(buzzer, HIGH);
      delay(30);
      digitalWrite(buzzer, LOW);
      min_minder = 0;
      mins += 3000; // 3000 frames per minute
    }
  }
  else min_minder = 0;

  // countdown minute-minder
  if (digitalRead(min_tmr) == 1 && timer_flg == 1) {
    if (mins > 0) --mins;
    if (mins == 0) {
      //if (bitRead(fiftyhz, 3) == 1 && bitRead(fiftyhz, 5) == 1 && bitRead(fiftyhz, 7) == 1) digitalWrite(buzzer, HIGH); else digitalWrite(buzzer, LOW);
      if (bitRead(fiftyhz, 0) == 1 && bitRead(fiftyhz, 6) == 1 && bitRead(fiftyhz, 7) == 1 && bitRead(fiftyhz, 8) == 1) digitalWrite(buzzer, HIGH);
      else digitalWrite(buzzer, LOW);
    }
  }

  // quick dab of the button clears minute-minder
  if (digitalRead(min_tmr) == 0 && timer_flg == 1 && mins == 0 && min_minder < 30) {
    timer_flg = 0; // minute minder button pressed to cancel alarm
    digitalWrite(buzzer, LOW);
  }

  if (inact < INACTFRAMES && timer_flg == 0 && tlock == 0) digitalWrite(buzzer, LOW);

  // inactivity timer. 10 mins is approx 30000 frames.
  if (a0_val < -100 || a0_val > 100) inact = 0;
  if (digitalRead(sw_btn) == 0 || digitalRead(sw_seq) == 0) inact = 0;
  if (++inact > INACTFRAMES) {
    if (bitRead(fiftyhz, 2) == 1 && bitRead(fiftyhz, 5) == 1) digitalWrite(buzzer, HIGH); else digitalWrite(buzzer, LOW);
  }
  if (bitRead(fiftyhz, 0) == 0) digitalWrite(buzzer, LOW);
}

// This function will write a 2 byte integer to the eeprom at the specified address and address + 1
void EEPROMWriteInt(int p_address, int p_value)
{
  byte lowByte = p_value % 256;
  byte highByte = p_value / 256;
  EEPROM.write(p_address, lowByte);
  EEPROM.write(p_address + 1, highByte);
}

//This function will read a 2 byte integer from the eeprom at the specified address and address + 1
unsigned int EEPROMReadInt(int p_address)
{
  byte lowByte = EEPROM.read(p_address);
  byte highByte = EEPROM.read(p_address + 1);
  return lowByte + highByte * 256;
}

#if (F_CPU == 16000000)  // 16Mhz
ISR(TIMER1_COMPA_vect) { // Hasi method ppm
  static boolean state = true;
  TCNT1 = 0;
  if (state) { //start pulse
    digitalWrite(ppmOutputPin, onState);
    OCR1A = PPM_PulseLen * 2;
    state = false;
  }
  else { //end pulse and calculate when to start the next pulse
    static byte cur_chan_numb;
    static unsigned int calc_rest;
    digitalWrite(ppmOutputPin, !onState);
    state = true;
    if (cur_chan_numb >= num_channels) {
      cur_chan_numb = 0;
      calc_rest = calc_rest + PPM_PulseLen;//
      OCR1A = (PPM_FrLen - calc_rest) * 2;
      calc_rest = 0;
      sync = 1;
      ++framecounter;
      ++fiftyhz;
    }
    else { // aend next channel
      OCR1A = (ppm[cur_chan_numb] - PPM_PulseLen) * 2;
      calc_rest = calc_rest + ppm[cur_chan_numb];
      cur_chan_numb++;
    }
  }

#else // 8Mhz
ISR(TIMER1_COMPA_vect) { // Hasi method ppm
  static boolean state = true;
  TCNT1 = 0;
  if (state) { //start pulse
    digitalWrite(ppmOutputPin, onState);
    OCR1A = PPM_PulseLen;
    state = false;
  }
  else { //end pulse and calculate when to start the next pulse
    static byte cur_chan_numb;
    static unsigned int calc_rest;
    digitalWrite(ppmOutputPin, !onState);
    state = true;
    if (cur_chan_numb >= num_channels) {
      cur_chan_numb = 0;
      calc_rest = calc_rest + PPM_PulseLen;//
      OCR1A = (PPM_FrLen - calc_rest);
      calc_rest = 0;
      sync = 1;
      ++framecounter;
      ++fiftyhz;
    }
    else { // aend next channel
      OCR1A = (ppm[cur_chan_numb] - PPM_PulseLen);
      calc_rest = calc_rest + ppm[cur_chan_numb];
      cur_chan_numb++;
    }
  }
#endif // 8Mhz
}

// If you use this software in whole or in part please acknowledge its source - Phil_G on most forums, philg@talk21.com  http://www.singlechannel.co.uk
