/*  Filename     PKIT2.C
    Description  PKIT-2 Move light 127 step 8 output
    Hardware     PKIT-2 BOARD
    Compiler     CCS PCM C Complier V 3.173
    Engineer     Pojchara B.
    Company      Sila Research Co.,Ltd. */

#include <16f818.h>
#fuses intrc_io,nowdt,protect,nobrownout,put,nomclr,nolvp,nowrt
#use delay(clock=100000)
#define CLK PIN_A4
#define STR PIN_A2
#define DATA PIN_A3
#define SW1 PIN_A5
#define RUN_PROG PIN_A6

void out_hc595(byte ds1){
BYTE i,DIS[1];
    DIS[0] = ds1;
    output_low(CLK);
    output_low(STR);
    for(i=1;i<=8;++i) {
        if((*DIS&0x80)==0)
            output_low(DATA);
        else
            output_high(DATA);
        shift_left(DIS,1,0);
        output_high(CLK);
        output_low(CLK);
    }
    output_high(STR);
}
void flash(byte dat){
byte i;
    for(i=0;i<=2;i++){
        out_hc595(dat);
        delay_ms(8);
        out_hc595(0);
        delay_ms(8);
    }
}
void run (int addr_end){
byte i;
int address=0,buff=0;
long del;
    while(1){
        del = read_adc();
        del *= 2;
        out_hc595(read_eeprom(address));
        address++;
        if(address>=addr_end)address=0;
        while (del) del--;
        if(~input(RUN_PROG))break;
    }
}
int prog (){
int i,value_dip,address;
    for(address=0;address<=128;address++)
        write_eeprom(address,0x00);
    address = 0;
    flash(0xff);
    while(1){
        value_dip = ~(input_b());
        out_hc595(value_dip);
        if(~input(SW1)){
            write_eeprom(address,value_dip);
            if(value_dip==0) flash(0xff);
            else flash(value_dip);
            delay_ms(2);
            if(~input(SW1))delay_ms(3);
            address++;
            if(address>=0x7e){
                while(~input(RUN_PROG)){
                    out_hc595(0xff);
                    delay_ms(4);
                    out_hc595(0);
                    delay_ms(4);
                }
                write_eeprom(0x7f,0x7e);
                return(0x7e);
            }
        }else if(input(RUN_PROG)){
            write_eeprom(0x7f,address);
            return(address);
        }
    }
}
void main (){
int addr_end;
    port_b_pullups(TRUE);
    setup_port_a( ALL_ANALOG );
    setup_adc( ADC_CLOCK_INTERNAL );
    set_adc_channel( 1 );
    addr_end = read_eeprom(0x7f);
    delay_us(20);
    while (1){
        if(input(RUN_PROG))run(addr_end);
        else  addr_end = prog();
    }
}
