vanlooverenkoen
vanlooverenkoen

Reputation: 2301

2 Python scripts use the same GPIO pin RPI

Is it possible to write 2 scripts

1 For setting a GPIO pin

and 1 for reading out what the status of the gpio pin is.

I now have written these two scripts in python. but when I launch them both only 1 will work

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18,GPIO.IN)
print GPIO.input(18)

The other one listens to a button and if the button is pressed the pin 18 is set to high, if he is pressed again the pin is set to low

#!/usr/bin/python
import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BCM)
pushbutton = 2
relay = 18

GPIO.setup(pushbutton, GPIO.IN)
GPIO.setup(relay, GPIO.OUT)

def main():
    ingedrukt = GPIO.input(pushbutton)
    try:
        while (True):
            if(ingedrukt == False):
                if(GPIO.input(pushbutton) == False):
                    sleep(0.5)
                    if(GPIO.input(pushbutton) ==False):
                        GPIO.output(relay, GPIO.HIGH)
                        ingedrukt = True
                        print "Pushed"
            else:
                if(GPIO.input(pushbutton) == True):
                    GPIO.output(relay, GPIO.LOW)
                    ingedrukt = False
                    print "Not pushed"
    except KeyboardInterrupt:
        print "Quit"
        GPIO.cleanup()
main()

Is this possible anyway if so, what am I doing wrong?

Upvotes: 1

Views: 3142

Answers (3)

SpaceCase
SpaceCase

Reputation: 148

You don't need to set the relay as a GPIO input to read the state. All you need is the print GPIO.input(18) command. So your first script should read:

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
print GPIO.input(18)

I would add the line

GPIO.setwarnings(False)

Upvotes: 2

Cantfindname
Cantfindname

Reputation: 2138

What do you mean only one works? Maybe this helps?

It is possible that you have more than one script/circuit on the GPIO of your Raspberry Pi. As a result of this, if RPi.GPIO detects that a pin has been configured to something other than the default (input), you get a warning when you try to configure a script. To disable these warnings: GPIO.setwarnings(False)

from: http://sourceforge.net/p/raspberry-gpio-python/wiki/BasicUsage/

Upvotes: 0

Owen Hempel
Owen Hempel

Reputation: 434

You're trying to concurrently run two scripts? Why not have the print statement in your listening script? Also, your printing status of the pin script needs a while loop

Upvotes: 0

Related Questions