Reputation: 503
I am having problems in this C/C++ program I wrote for the Raspberry Pi in Raspbian. Here is the link to download the cpp file UltraSonicTest.cpp:
#include <wiringPi.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int trigger = 4; //GPIO pin 23
int echo = 5; //GPIO pin 24
double readValue();
void continuousRead();
int main(){
printf("Raspberry Pi Sonar Test\n");
if (wiringPiSetup() == -1)
return 1;
printf("WiringPi Setup Successful\n");
pinMode(trigger, OUTPUT);
pinMode(echo, INPUT);
digitalWrite(trigger, 0); //GPIO pin 23 in the off position
for (int i=0; i<10; i++){
printf("Calling ContinuousRead\n");
continuousRead();
}
return 0;
}
double readValue(){
printf("Entering ReadValue...");
double start=0, end=0, elapsed=0, distance=0;
struct timespec gettime_now;
// Send 10us pulse to trigger
digitalWrite(trigger, 1);
delayMicroseconds(0.00001);
digitalWrite(trigger, 0);
clock_gettime(CLOCK_REALTIME, &gettime_now);
start = gettime_now.tv_nsec;
while (digitalRead(echo)==0){
clock_gettime(CLOCK_REALTIME, &gettime_now);
start = gettime_now.tv_nsec;
}
while (digitalRead(echo)==1){
clock_gettime(CLOCK_REALTIME, &gettime_now);
end = gettime_now.tv_nsec;
}
elapsed = (end-start);
//printf("Start: %lf\n", start);
//printf("Stop: %lf\n", end);
//printf("Time in milliseconds: %lf\n", elapsed/1000000);
//printf("Elapsed: %lf seconds\n", elapsed = elapsed/1000000000);
elapsed = elapsed/1000000000;
//printf("%lf seconds * 34029 cm = %lf cm/s\n", elapsed, distance = elapsed*34029);
distance = elapsed*34029;
//printf("Distance = %lf cm\n",distance = distance/2);
distance = distance/2;
//printf("%lf cm = %lf inches\n",distance, distance/2.54);
printf("Leaving ReadValue\n");
return distance;
}
void continuousRead(){
printf("..Starting ContinuousRead..");
delay(1000);
printf("Calling ReadValue\n");
double distance= readValue();
printf("Distance: %lf cm \n", distance);
}
I have the function call being called multiple times in a for loop, but the call only goes through 1-3 times.
sudo ./a.out
Raspberry Pi Sonar Test
WiringPi Setup Successful
Calling ContinuousRead
..Starting ContinuousRead..Calling ReadValue
Entering ReadValue...Leaving ReadValue
Distance: 2.194802 cm
Calling ContinuousRead
..Starting ContinuousRead..Calling ReadValue
Any idea what I'm doing wrong?
Upvotes: 1
Views: 589
Reputation: 503
From the comment from nonsensickle!
delayMicroseconds(0.00001);
seems to have slowed down performance and and other side effects.
changed to delay(1);
now the speed is acceptable. and it goes through the whole loop now.
Upvotes: 2