1

I'm writing a python application which uses a PIR motion sensor to trigger the RPi camera (Rev. 1.3) and start a video. For this purpose I'm using the threading library, to achieve multithreading. At the moment I have 3 threads and one of them is used to trigger the camera. This is the code in the mentioned thread:

from test_cam import start_cam
while True:
    if state == 1:
        if (GPIO.input(23)==1 or GPIO.input(14)==1 or GPIO.input(15)==1)and triggered == False:
            update_triggered(True)
            start_cam()

The start_cam method is in another python file, which is imported at the beginning of the code above. The method is implemented as follows:

def start_cam():
    camera = picamera.PiCamera()
    camera.resolution = '720p'
    camera.framerate = 30

    start = dt.datetime.now()
    camera.start_recording('./' + start.strftime('%Y-%m-%d_%H-%M-%S') + '.h264')
    camera.wait_recording(20)
    camera.stop_recording()
    camera.close()

The issue with it, is that the video starts recording but a lot of frames are missing in between. The average video length is ca. 5 seconds, although it should be ca. 20 seconds.

My suspect is that the multhithreading is causing this problem, because of the CPU distribution between the threads. I tested the start_cam method in a non multithreading environment and it worked fine. There were no missing frames or skips in the recording.

Does anyone know how to fix or workaround this problem?

Many thanks in advance

2

The while True loop is a busy spin. It will use all the CPU time it can. I would add a time.delay(0.01) or time.delay(0.1) to that loop.

  • Where exactly would you add the delay? The while true loop is necessary because the thread should remain alive, until the program ends. If I don't add the loop, the thread will end. – primef Oct 8 '17 at 16:18
  • 1
    Anywhere in the loop. This is loop is now continuously running so many cycles after another that it's stressing your CPU. Just add a small delay at the the end or the beginning of the loop to take some stress away from the CPU. – 88weighed Oct 9 '17 at 15:39
  • It now works like a charm. The problem is solved and by adding a delay on my other threads too, I got an overall performance increase. Many thanks :) – primef Oct 9 '17 at 18:14

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.