Im working on a game for my RPi3 B running raspbian, whenever I run this py script from the command line it runs once and stops, I would like it to stay open and keep running as it waits for a knock sensor to be knocked.. I am new to python if that helps. When the script detects a knock sensor it sends a value (Strike 1) to my sqlite db. I then retrieve that data using php and ajax into my browser running from my local apache server. It all works if I run the py script first in idle as it stays open but not from the command line..

#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
import sqlite3

KnockPin = 12 

print ("Welcome to Bases Loaded")

def setstr():
    global strikes
    strikes = 0

def setup():
    GPIO.setup(KnockPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

def knock(ev=None):

    with sqlite3.connect('/var/www/html/basesLoaded.db') as conn:

        global strikes
        strikes += 1

        if strikes ==0:
        elif strikes == 1:

            conn.execute("UPDATE bl set STRIKE = 1 WHERE ID =1");

            print ("Strike 1 :", conn.total_changes);

        elif strikes == 2:

            conn.execute("UPDATE bl set STRIKE = 2 WHERE ID=1");

            print ("Strike 2 :", conn.total_changes);

        elif strikes == 3:
            conn.execute("UPDATE bl set STRIKE = 0 WHERE ID=1");
            print ("Strike 3 Your Out :", conn.total_changes);

def register_callbacks():
    GPIO.add_event_detect(KnockPin, GPIO.FALLING, callback=knock, bouncetime=2500) 

if __name__ == '__main__':

    except KeyboardInterrupt: 

1 Answer 1


This question if really off-topic as it is nothing specific to the Raspberry Pi.

Put a while forever loop after the call to register_callbacks. The loop needs to do nothing more than time.sleep(1). At the moment the program terminates after the register_callbacks call.

  • Thanks for the simple tip, now it works! I can launch the py file from my browser now using php!
    – Ryan D
    May 5, 2016 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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