shramik wrote: ↑
Sat Dec 09, 2017 4:26 am
sir, now the script goes into a infinite loop and uses entire CPU usage and hangs the system. is there any other code to find the distance using ultrasonic sensor.
I did try to warn you of problems with your approach, including this one.
As elParaguayo suggested gpiozero might help but the quick and dirty fix would be to add a timeout to your while loops.
Without writing the code for you, this is one way do it:
Code: Select all
store time and start sending ultrasound
wait for echo to be detected or for maximum time to be exceeded
stop sending ultrasound
calculate distance (half the elapsed time multiplied by some constant)
I'd also put this into a seperate thread started during your class' init method with a property that returns the most recent measurement.
As I mentioned above, your original code would never have given the correct distance. It's measuring the length of the pulse rather than the time taken for the echo to arrive. Your first while loop is uneccessary, you only need to store the start time once when you start sending ultrasound.
To reduce CPU load, use a callback function rather than a while loop to detect the incoming echo. See the documentation for your chosen gpio library for how to do this.(Hint: you'll need to use instance variables to store the start time, end time, and distance)
The reason you're seeing an infinite loop is that that is what you've written. Your calling function has a "while True" loop which will never exit and which calls your sense method 5 times a second. This is componded by your sense method having two tight loops that may never exit.
You're using a very short pulse length: 0.00001 seconds. It's entirely possible given that linux is a multi-tasking system and that it takes time to execute any line of code that the entire pulse could be received and the gpio state be back to 0 before you even enter the first while loop. That same loop will never exit if the gpio never goes high (i.e. no echo is received).