4

I am using wiringPi Library and using this library to read data from GPIO Pins attached to a PIR Sensor.

I am using a while loop which reads input data. If there is a motion it will print motion.

while(1)
{
    while(digitalRead(1)==0)
          check=false;
    if(check==false)
    {
         cout<<"Motion Detected"<<endl;
         check=true;
    }
}

The above code uses processor 100%.

What to do in this case? How can I reduce my processor usage.?

Ghanima
  • 15,958
  • 17
  • 65
  • 125
Veer
  • 149
  • 2
  • 6

2 Answers2

7

I think your problem is that when motion is detected the loop runs at full speed. I would suggest one of the following sollutions:

  1. Use a blocking read from the GPIO pin. That way your program will hang untill there is new data ready, i.e. if the GPIO pin has changed state.

  2. When using polling you should make your program sleep at least once with run of the loop, as suggested by Gerben in the comments.

For 2 structure your code a bit differently. Change the while to an if and frame the whole thing in a while loop instead, like so:

#import <time.h>

while( 1 ) {
    if( digitalRead(1) == 0 ) {
        cout << "Motion detected." << endl;
    }
    usleep(50000);
}

That way the sleep routine will release the CPU for 50ms with each run of the loop.

Kenneth
  • 721
  • 1
  • 4
  • 11
0

I believe you are looking for the nanosleep() solution:

usleep() has been removed since POSIX-2008 and recommends to use nanosleep() instead.

electron1979
  • 121
  • 11