0

I am running two python scripts from two different terminals like so:

python3 one.py and python3 two.py

one.py

Waits for an input on GPIO 27, and then starts counting in seconds how long the program has been running.

import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)
GPIO.setup(27, GPIO.IN)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)

timer_a = time.time()
counter = 0
timer = 0

while True:
    if GPIO.input(27) == 0:
       counter = 1
       while counter == 1:
           if time.time() - timer_a > 1:
               timer+=1
               print("Time Elapsed (s): ", timer)
               timer_a = time.time()
               sleep(0.5)
GPIO.cleanup()

two.py

Waits for an input on GPIO 17, and increments a counter.

import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)
GPIO.setup(27, GPIO.IN)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)

timer_a = time.time()
counter1 = 0

while True:
    if GPIO.input(17) == 0:
        counter1 += 1
        print("Count: ", counter1)
        sleep(0.5)

GPIO.cleanup()

Procedure to replicate issue on my machine:

  1. Start both programs from terminal.
  2. Provide an input to GPIO 17 in one.py script.
  3. Timer starts.
  4. CPU usage: 30%
  5. Provide multiple inputs (one per second) to GPIO 27.
  6. Counter increments.
  7. CPU usage: 5%
  8. Stop providing inputs to GPIO 27.
  9. CPU usage: 30%

Wrongly, I was expecting the CPU usage to increase and not decrease when I am also providing an input to the second script.

When the if-statement in two.py evaluates to True the CPU usage is reduced by 25%. - Why?

  • Both loops are busy spins in that they execute as many times as possible. Busy spins are bad practice. Perhaps add a time.sleep(0.01) as the first or last statement in each while loop so they don't execute more than 100 times a second. – joan Jul 25 '18 at 9:59
3

The CPU usage is reduced when the if-statement is true in two.py because the sleep(0.5) is inside the if block. The sleep avoids the intensive while loop.

Move the sleep outside the if statement to make it consistent.

while True:
    if GPIO.input(17) == 0:
        counter1 += 1
        print("Count: ", counter1)
    sleep(0.5)
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.