0

I've written a python script (shown below) which starts and stops another separate python script (datalogger) once a button is pressed. The datalogger script records logic levels (0 or 1) and stores them in a CSV. The recorded data should read 0 1 0 1 0 1 and so on.. However when I run the datalogger code by pressing the button the logic levels are recorded incorrectly i.e. 1 1 1 0 1 0 1 1 1. This is because the button script as it is currently written is continuously 'looking' for a button press which is interrupting the datalogger script.

Therefore does anyone know how I can alter this script to make it wait for a button press and then proceed to either start or stop the datalogger script? Basically I don't want the button script to be doing anything until a button is pressed so it doesn't interrupt the datalogger. Thanks.

import RPi.GPIO as GPIO
import time
import subprocess, os
import signal

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO_switch = 24 # select pin to connect button
GPIO.setup(GPIO_switch, GPIO.IN, pull_up_down=GPIO.PUD_UP)

try:

    run = 0
    while True:
        if GPIO.input(GPIO_switch)==0 and run == 0:
            rpistr = "python3 /home/pi/Documents/DataloggerV2.py"
            p=subprocess.Popen(rpistr, shell=True, preexec_fn=os.setsid)
            run=1
            while GPIO.input(GPIO_switch)==0:
                time.sleep(0.01)
        if GPIO.input(GPIO_switch)==0 and run == 1:
            run = 0
            os.killpg(p.pid, signal.SIGTERM)
            while GPIO.input(GPIO_switch)==0:
                time.sleep(0.01)


except KeyboardInterrupt:

    GPIO.cleanup()
  • Isn't this essentially the same question as you asked before? raspberrypi.stackexchange.com/questions/91152/… – Dirk Nov 26 '18 at 14:20
  • No I was asking if anyone knew why my data was getting altered in that question. I've now realised what was causing it and am asking if anyone knows a solution (by making the script wait for a button press). – user93154 Nov 26 '18 at 14:22
  • 2
    I'm not a python user, but what you want to use here are event driven callbacks -- functions you register with a library to be called when a specific event happens (you can implement that at a lower level by polling file descriptors, but I doubt you will need to do that in this case). If you are not committed to programming it yourself, you might want to look into an existing tool such as pigpiod: abyz.me.uk/rpi/pigpio/pigpiod.html We have a tag here for questions about it, if you decide to go that route instead: raspberrypi.stackexchange.com/questions/tagged/pigpio – goldilocks Nov 26 '18 at 14:52

Your Answer

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