
#include <pic.h>
#include <math.h>
#include "delay.h"

unsigned char tmrofc=0;	//TMR0 overflow counter

int getDigit();
void Display();
int DWOP(int);
int DWP(int);

int DWOP(int n){//DEC PNT ENA
switch(n){
	case 0:
		return 0xC0;
	case 1:
		return 0xF9;
	case 2:
		return 0xA4;
	case 3:
		return 0xB0;
	case 4:
		return 0x99;
	case 5:
		return 0x92;
	case 6:
		return 0x82;
	case 7:
		return 0xF8;
	case 8:
		return 0x80;
	case 9:
		return 0x90;
	default:
		return 0xBF;
}
}

int DWP(int n){//DEC PNT DIS
switch(n){
	case 0:
		return 0x40;
	case 1:
		return 0x79;
	case 2:
		return 0x24;
	case 3:
		return 0x30;
	case 4:
		return 0x19;
	case 5:
		return 0x12;
	case 6:
		return 0x02;
	case 7:
		return 0x78;
	case 8:
		return 0x00;
	case 9:
		return 0x10;
	default:
		return 0x3F;
}
}

void Display(d0,d1){
	unsigned int t=0;
	while(t<50){
		RA0=1;
		RA1=0;
		DWP(d0);
		DelayMs(15);
		DWOP(d1);
		RA0=0;
		RA1=1;
		DelayMs(15);
		t++;
	}
}

void interrupt ISR(){
	if(T0IF==1){
		tmrofc++;
	}
	if(INTF==1){
		float s=0;//distance in m
		float ticks=0;
		float time=0;
		unsigned char d0=0;
		unsigned char d1=0;
		ticks=(float)((tmrofc*256)+TMR0);
		time=ticks*1.6;
		s=time*0.00346;
		d0=(int)s%10;
		d1=(int)(s*10)%10;
		Display(d0,d1);
		
	}
}

void main()
{
   //Init
   TRISA=0X10;	//RA0-7Segment1,RA1-7Segment2,RA3-Trig,RA4/INT-Echo
   TRISB=0X00;	//PORTB as output of a-g,DP
   PORTA=0X00;
   PORTB=0X00;
   OPTION_REG=0X00;	//PS=1:2 to TMR0
   INTCON=0XB0;	//RB4 and TMR0 interrupt enable   
   
   
   
   while(1){
   	TMR0=0X00;	//Clear timer
   	RA3=1;		//Trigger now
   	DelayUs(10);	//Trigger Delay
   	RA3=0;		//Trigger off
   	DelayMs(500);
   }
}