I tried again the answer of DinoT_Intel and still giving me 0. Maybe is the sensor the problem. Maybe the ultrasonic sensor of seeedstudio doesn't work with that code, i don 't know.
My 4 pin sensor is a HC-SR04 and this is the code that i use is this. I don't remember where I get it but it works.
*********************************
#include <TimerOne.h>
#define speakerPin 9
#define trigPin 3
#define echoPin2 2
unsigned long SEC=1000; //1sec = 10^6microsecond
long pstart=0;
long pstop=0;
boolean got=false;
int freq=500; //in Hz (1/sec)
int tt=SEC/freq/2;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT_FAST);
pinMode(echoPin2, INPUT_FAST);
Timer1.initialize(SEC);
//you need at least 15us + ping time. it didnt work below 1000us for me for below code
}
void pingUltra()
{
fastDigitalWrite(trigPin, LOW);
delayMicroseconds(2);
fastDigitalWrite(trigPin, HIGH);
delayMicroseconds(10);
fastDigitalWrite(trigPin, LOW);// NOT checking for LOW. it seemed to hang here if i used it.
pstart=micros();
while(digitalRead(echoPin2)==HIGH ){}
pstop=micros();
}
double media(int x)
{
double med=0;
for(int i=0; i<x;i++)
{
pingUltra();
med+=((pstop-pstart)/57)+4;
}
return med/x;
}
void loop()
{
double dist=media(10);
if(dist!=0)
{
Serial.print("CM: ");
Serial.println(dist);
for(int i=0;i<10;i++)
{
analogWrite(speakerPin,200);
delayMicroseconds(tt);
analogWrite(speakerPin,0);
delayMicroseconds(tt);
}
analogWrite(speakerPin,00);
}
delay(1000);
}
**********************************