//***************************************************************************
//******
//****** Digital ignition for 2 stroke engines. SPORTDEVICES 11/6/2003
//******
//****** NOTE: use compiler: PCW v2.619
//******
//****** Digital parts: PIC16F84a, XTAL 4MHz
//****** Complete schematic: www.sportdevices.com/ignition/ignition.htm
//****** To ask any question: jandani@sportdevices.com
//******
//******
//****************************************************************************

//#include <16F873.H>
//#use delay(clock=3686400)
//#use rs232 (baud=9600,xmit=PIN_C6,rcv=PIN_C7)

#include <16F84a.H>
#fuses XT,NOWDT
#use fast_io(a)
#use delay(clock=4000000)

#define pulse 500 //spark time, microseconds

int const ignition[64]=
{22,23,25,27,29,31,33,35,37,39,41,44,46,49,51,54,56,59,62,65,68,70,73,77,80,83,86,89,
93,96,100,103,106,108,110,112,115,117,119,122,124,127,129,131,134,136,139,141,144,146,
149,151,154,157,159,162,165,167,170,173,175,178,181,184};

//Note: Delay are calculated in multiples of 4 microseconds
//first value is for 15121 RPM (TMR0 count=31) and last value is for 4987 RPM (TMR0 count=94)


#define pickup PIN_A0  //pin 17
#define thyristor  PIN_A1  //pin 18
#byte TMR0=0x01
#byte PORTA=0x05
#byte PORTB=0x06
#byte INTCON=0x0b
#byte OPTION_REG=0x81

int tmr0h;

#int_global
void int_tmr0()
{
  tmr0h++;
  bit_clear(INTCON,2);
}

void main(){
int perl,perh,retardo;

   INTCON=0xa0; //T0IE=1
   OPTION_REG=0x06;  //PULLUP on, prescalar=128   2^(1+6)=8
   set_tris_a(0x01);
   set_tris_b(0x00);

   while (true)
   {
      while (input(pickup));
      while (!input(pickup));
      perl=TMR0; perh=tmr0h;
      TMR0=0; tmr0h=0;

      if ((!perh)&&(perl>30)&&(perl<95))
      {
        perl=perl-31;
        retardo=ignition[perl];
 
        retardo=retardo-8; //delay adjust (substract 8*4=32 us)
        //do delay
        #asm
 bucle: nop
        decfsz &retardo,f
        goto bucle
        #endasm

        output_high(thyristor);
        delay_us(pulse);
        output_low(thyristor);
      }
      else
      if ((perh)||(perl>94))
      {
        //do delay
        #asm
        bcf    03,0
        rlf    perl,F
        rlf    perh,F
        incf    perl,F
        incf    perh,F
loop2:  nop
        decfsz perl,f
        goto loop2
        decfsz perh,f
        goto loop2
        #endasm

        output_high(thyristor);
        delay_us(pulse);
        output_low(thyristor);
       }
   }
}

 


