Sir, this is the arduino code I'm using to transmit and receive the signal (from Mr. Kwong, only some lines changed). The code searches the highest voltage peak from the transmitted waves and was assumed to be the voltage of the sound wave that was reflected back from the obstacle. Is there any error in this code Sir?
/*
* A Sensitive DIY Ultrasonic Range Sensor
* http://www.kerrywong.com
*/
void stopTransducer()
{
cli();
TCCR1B = 0;
sei();
digitalWrite(9,LOW);
digitalWrite(10,LOW);
}
void startTransducer(float freq, float dutyCycle)
{
if (dutyCycle > 0.5) dutyCycle = 0.5;
else if (dutyCycle < 0) dutyCycle = 0;
cli();
TCCR1B = _BV(WGM13) | _BV(CS10) | _BV(ICNC1);
//f0 = fclk / (2 * N * Top)
long topv = (long) ((float) F_CPU /(freq * 2.0 * 1.0));
ICR1 = topv;
OCR1A = (int) ((float) topv * dutyCycle);
OCR1B = (int) ((float) topv * (1 - dutyCycle));
DDRB |= _BV(PORTB1) | _BV(PORTB2);
TCCR1A = _BV(COM1A1) | _BV(COM1B1);
sei();
}
void setup()
{
Serial.begin(9600);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
}
byte a = 0;
unsigned long t_start = 0;
unsigned long t_peak = 0;
unsigned long t = 0;
byte v_peak = 0;
const float SPEED_OF_SOUND_20C = 0.0003432; //per micro-second
float d = 0;
void loop()
{
startTransducer(40000.0, 0.5);
delayMicroseconds(300);
stopTransducer();
v_peak = 0;
t_start =micros();
t_peak = t_start;
delay(1);
for (int i = 0; i < 256; i++) {
a = analogRead(0);
t = micros();
if (a > v_peak) {
t_peak = t;
v_peak = a;
}
}
t = t_peak - t_start;
d = (float) t * SPEED_OF_SOUND_20C / 2.0;
Serial.println(d , 2);
}