Good day
I am trying to sample distance using a sonar/ultrasonic sensor for altitude measurement. When the PWM is not active, the sensor gives accurate measurements in centimeters, however with the PWM active, the sensors outputs unrealistic measurements. I have seen other having issues with the arduino platform and have resolved this issue by decoupling the supply of the sensor with an electrolytic capacitor. However this does not resolve the issue and upon closer inspection, with the PWM active, the measured pulse/echo is wrong. Is this an issue with the sonar and PWM fighting over the raspi's timer?
Is there anyway to fix this?
I have been trying to debug this problem for 3 days now. I tried using the wiring-pi library and the pigpio library but both have the same problem.
This is an example code with the same issue:
int main(int argc, char** argv){
//Sonar Sensor Initialize LOW
gpioInitialise(); //Initialize Wiring Pi using broadcom pin numbering
gpioSetMode(27, PI_OUTPUT); //Set up gpio pins
gpioSetMode(25, PI_INPUT);
//Set-up PWM pins
gpioSetMode(24, PI_OUTPUT);
gpioSetMode(17, PI_OUTPUT);
gpioSetMode(22, PI_OUTPUT);
gpioSetMode(18, PI_OUTPUT);
gpioSetPWMfrequency(24,400);
gpioSetPWMfrequency(17,400);
gpioSetPWMfrequency(22,400);
gpioSetPWMfrequency(18,400);
gpioPWM(24,113); //1
gpioPWM(17,113); //2
gpioPWM(22,113); //3
gpioPWM(18,113); //4
delay(30);
while(1){ //While loop (pseudo pid control loop)
//-------Poll Sensor-------
//Start TRIG pulse HIGH
gpioWrite(27, 1);
delayMicroseconds(10);
gpioWrite(27, 0);
while(gpioRead(25) == 0){};
long timeInitial = micros(); //Get time since program started in microseconds
while(gpioRead(25) == 1){};
long timeEcho = micros() - timeInitial;
cout << "timeInitial = "<< (double)timeInitial << endl;
cout << "timeEcho = "<< (double)timeEcho << endl;
//Get distance in cm
float altitude = timeEcho / 58.2;
cout << "Altitude "<< altitude << endl;
//-------"Update PWM"-------
gpioPWM(24,155); //1
gpioPWM(17,155); //2
gpioPWM(22,155); //3
gpioPWM(18,155); //4
delay(50);
}
return 0;
}