#include <stdlib.h>
#include <mega16.h>

#define SetBit(x,y) (x|=y)
#define ClrBit(x,y) (x&=~y)
#define TestBit(x,y) (x&y)

#define LCD_RST 0b00000001
#define LCD_E   0b00000010
#define LCD_RW  0b00000100
#define LCD_RS  0b00001000
#define LCD_CS2 0b00010000
#define LCD_CS1 0b00100000

#define LCD_DB PORTB
#define LCD_DBI PINB
#define LCD_IO DDRB
#define LCD_COM PORTC

#define Freq 8000000

#define cp "pF"
#define cn "nF"
#define cu "uF"

#define lp "pHn"
#define ln "nHn"
#define lu "uHn"
#define lm "mHn"

#define r "Om"
#define rk "kOm"
#define rm "MOm"
  
#include "delay.h"
#include "ks0108_1.h"

unsigned long Nx;

interrupt [TIM1_OVF] void timer1_overflow(void)
{
    char *s="Ok";
    TIMSK=0;
    PORTB=0;//b11111100;
    TCNT1=0x10000-(Freq/2048)/3200;
    TCCR1B=0;        
    textx=0;
    texty=2;
    puts(s,10,0xFF);
    itoa(Nx, s);
    textx=0;
    texty=4;
    puts(s,10,0);    
}

interrupt [EXT_INT0] void ext_int0_isr(void)
{
    char *s="Ok";
    //SetBit(PIND, 0b00000001);
    textx=0;
    texty=2;
    puts(s,10,0xFF);
//    PORTD=0b11111111;
//    TCCR1B=0b00000101;
//    TCNT1=0x10000-(Freq/2048)/3200; //*32;
//    TIMSK=0b00100100;
}

interrupt [TIM1_CAPT] void timer1_capt(void)
{
/*    char *ss="On";
    char *s="On";
*/    Nx++;                  /*
    clear();
    textx=0;
    texty=0;
    puts(ss,10,0);
    itoa(Nx, s);
    textx=0;
    texty=2;
    puts(s,10,0);*/ 
/*    clear();   
    itoa(num, s);   
    textx=5;
    texty=5;
    puts(s,10,0);*/ 
}

void main(void)
{
 char *s="On";

 DDRD=0x00;
 DDRC=0xFF;
 DDRB=0xFF;
 
 PORTD=0b11111110;

 SetBit(LCD_COM,LCD_RST);

 TCCR1A=0;
 TIFR=0;

 //TIMSK=0x20;
 TCCR1B=0b00000101;
 TIMSK=0b00100100;
 //SetBit(GICR, 0b10000000);
 GICR=0b01000000;
 MCUCR=0b00000010;

 init_lcd(); 

 clear();

 textx=0;
 texty=0;
 puts(s,10,0);

 #asm("sei");

 while(1);
}