I'm working on a project which will use a PIR motion sensor to take a photo of the room, also triggered by the PIR sensor. I'm using the PIR sensor for something else at the same time, so I'd rather make further use of the sensor, rather than use something like motionEye.

I'm new to Linux, but not to Python. At the moment, my code is:

import RPi.GPIO as GPIO
import time
import webbrowser as web
from subprocess import call

GPIO.setup(11, GPIO.IN)

#Open local web page in default browser

while True:
    i = GPIO.input(11)    #Read output from PIR sensor
    if i==0:
        call(['usr/bin/vcgencmd', 'display_power', '0']) #Turn monitor off
    elif i==1:
        id = str(time.time())
        filename = "/home/pi/camera/"+id"".jpg"
        call(['usr/bin/vcgencmd', 'display_power', '0']) #Turn monitor on
        call(['usr/bin/raspistill', '-o', filename])     #Take a photo

Is there a better way to implement it so that the filenames don't duplicate?

  • if the code is working to your liking, why change it?
    – jsotola
    Aug 13 '18 at 3:03
  • Agreed. What does "better way" mean to you? I sometimes just increment an index, and save it in a file each time so that if I start the script again it keeps track, but I'd say that might be a worse way, though the problem with system time is that it might be (will be) wrong each time you power up your Pi.
    – uhoh
    Aug 13 '18 at 5:24

Creating a name based on the current time is a common solution to this problem. As long as you know that you will not create two files within the same second, this is fine.

Depending on your needs, you can format the time in different ways. If you only care about a unique name, using the time in seconds is fine. Sometimes it is desirable to have that time human readable, as year/month/day hour/minute/second.

  • Possibly add a test to make sure time has been NTP synchronized first. Or append an additional short random number or its hash to lower probability of a time overwrite until NTP.
    – uhoh
    Aug 13 '18 at 5:26

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.