// Functions
//1. Initisalise Variables
//
// Parameter None
// Result None
//////////////////////////////////////////////////////////////////
void SonarInit()
{
int i;
pinMode(TP,OUTPUT);
pinMode(EP,INPUT);
digitalWrite(TP,LOW);
SonarActive = false;
PCMSK0 |= 0b1100; // enable PC interrupts on arduino pins 50,51
}
////////////////////////////////////////////////////////////////
/////
void sendPing()
{
SonarActive=true;
digitalWrite(TP, HIGH);
delayMicroseconds(10);
digitalWrite(TP,LOW);
PingS = micros();
SonarTimeOut = 500;
// Wemight get a false int here but check ib recieve time > minimum.
PCICR |= 1; // enable PCI0 pin group interrupt
}
////////////////////////////////////////////////////////////////
/// Pin-Change interrupt, for arduino pins 50..53, and 13..10
ISR(PCINT0_vect)
{
unsigned long t = micros();
int dt = t - PingS;
if (dt > 470)
{ //
// check which pin fell here, and note time
// dt is the microsecond to 4 microsecond resolution of the path there and back.
PCICR &= 0xfe; // disable PCI0 pin group interrupt
SonarActive = false;
UpdateAverage(dt);
}
else
{ // still waiting for leading edge
// showln ("here")
}
}
///
void ResetSonar()
{
SonarActive = false;
PCICR &= 0xfe; // disable PCI0 pin group interrupt
}
////////////////////////////////////////////////////////////
//2. Update Average array
//
// Parameter new time count
// Result None
void UpdateAverage (long Time)
{
Avg[2]=Avg[1];
Avg[1]=Time;
}
// faster to do this linear not loop
/////////////////////////////////////////////////////////////////
//3. Calculate running average
//
// Parameter None
// Result New averag
long CalculateAvg()
{
long total=0;
total = (Avg[1]+Avg[2])/2;
if (total <2830)
return total;
else
{ // max reliable count after range calcs are wrong..
return(2830);
}
}
////////////////////////////////////////////////////////////////
//4. Calculate Distance
//
// Parameter None
// Result Distance cm
float CalculateDistance()
{
float calcvalue;
long avgtime = CalculateAvg();
calcvalue = (avgtime /58.2);
calcvalue = calcvalue / 2.0 ;
// Distance_CM = ((Duration of high level)*(Sonic :340m/s))/2
showln(calcvalue);
return calcvalue;
}
This code uses a single pin interrupt its set for mega pins but with a little research you should be able to modify..