 
 /***************************
 Used for sonar - HC-SR04
 Pekka Ritamaki 
 26.3.2016 
 module: WIFI  
 file: ultra4.c 
 Trig PIN RC.0 output 
 Echo PIN RC.1 input 
 *********************** 
 Files HC-SR.c  main module 
  DS1820.c   lämpötilamittaus DS1820 anturit  0,1 ja 2 
  Ultra4.c  ultraäänietäisyysmittaus HC-SR4:lla 
  WIFI.c    wifimoduli ESP8266 moduulilla ESP202 
  Käyttöjännite 5V 50-100mA  3.3V LD33 jänniteregulaattorilla  
  
 ***************************************************** 
   Used sonar - HC-SR04  
   time 8MHz/4 =2MHz 
   2MHz /8 = 0.25MHZ =250KHz 
 
*/ 
 

//#use fast_io(c) 


// Defining the pins
 int8 timer_end ; 
 int8 count; 
  
#define trig PIN_C0     //  Output pin 
#define echo PIN_C1     // input pin 

#BYTE T1OSC =0x10 
#BIT  T1OSCEN =T1OSC.3 
#BIT  T1ON = T1OSC.0 

// interrupt  for non trigger case  2us * 256 *250 =128ms 
// valvo,että tulee trigger,muuten timer_end =1
#int_TIMER0 
void isr( void) { 
if (count ++ > 25) 
timer_end=1;  
restart_wdt(); 
} 

 // ulstrasonic function 
 
void ultra( void )
{
int32 distance, time;          // Defining variables

 
setup_ccp1 ( CCP_OFF);         //PWM1 off 
setup_ccp2 ( CCP_OFF);         // PWM2 off 
 
setup_adc_ports( ADC_OFF );      // ADC off 
 
T1ON=1;                           // timer1 on 
 setup_comparator(NC_NC_NC_NC); // Comparators off 

 
timer_end=0; 
count=0; 
  
                                      
output_high(trig);                       // ping the sonar
delay_us(20);                            // sending 20us pulse
output_low(trig);                        // pulse off 
 
 enable_interrupts(GLOBAL);  
 
while(!input(ECHO) && !timer_end)       // wait for high state of echo pin or interrupt on 
{}

set_timer1(0);                           // setting timer zero

while(input(ECHO)&& !timer_end)          // Wait for high state of echo pin
{}

time=get_timer1();                       // Getting the time
disable_interrupts(GLOBAL);  
//printf("\r time =%ld", time); 
//distance=time*0.028 + 1.093 ;          // Calculating the distance inch
// distance=(time* 58L)/100 + 27.7L ;             // Calculating the distance mm   
 distance=(time* 15.58L)/100 + 27.7L ;             // Calculating the distance mm        
  if(time <13000)                          
   sprintf(str1,"D%04Lumm", distance); //  displaying distance 
   else 
     sprintf(str1,"D0000mm" ); 
 

 
} 
