Accessing multiple GPIO's from multiple Docker Containers

Question:

I am running into an issue with Docker Containers and RPI4 GPIO. Everything works great if the containers are run by themselves. Ex. Container 1 runs and provides output and then I stop it, then I am able to start Container 2 it provides output and then I stop it.

My overall goal for this project is to allow 2 Docker Containers to communicate with separate GPIO pins simultaneously. Container 1 is linked to GPIO Pin 23 and Container 2 is linked to GPIO Pin 17, other than this these programs are the exact same and just being triggered with an interrupt(main reasoning for this testing)

If anyone has any suggestions please let me know, I will go ahead and attach the code below.

Container 1:

import RPi.GPIO as GPIO
import time

M_PIN = 23
GPIO.setmode(GPIO.BCM)
GPIO.setup(M_PIN, GPIO.IN)
GPIO.setwarnings(False)
def my_callback(M_PIN):
    if GPIO.input(M_PIN) == GPIO.HIGH:
        print("PIN HIGH")
    elif GPIO.input(M_PIN) == GPIO.LOW:
        print("PIN LOW")

GPIO.add_event_detect(M_PIN, GPIO.BOTH, callback = my_callback, bouncetime=50)

Container 2:

import RPi.GPIO as GPIO
import time

M_PIN = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(M_PIN, GPIO.IN)
GPIO.setwarnings(False)
def my_callback(M_PIN):
    if GPIO.input(M_PIN) == GPIO.HIGH:
        print("PIN HIGH")
    elif GPIO.input(M_PIN) == GPIO.LOW:
        print("PIN LOW")

GPIO.add_event_detect(M_PIN, GPIO.BOTH, callback = my_callback, bouncetime=50)

Here is my docker-compose.yml:

version: '3'
services:
  container1:
    image: cont2
    privileged: true
  container2:
    image: cont1
    privileged: true

I have the environment setup exactly how I’d imagine it should be setup. I just need these interrupts in both containers to have the ability of being triggered whenever they are supposed to, whether it is at the same time or one 30 seconds after the other.

Asked By: dougy

||

Answers:

I ended up figuring it out.

By adding a loop at the bottom:

while(True):
    time.sleep(1)

I cannot believe I forgot to add this.

It ended up fixing the error displayed above. I originally tried other ways but they did not work but a while loop did.

Final:

import RPi.GPIO as GPIO
import time

M_PIN = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(M_PIN, GPIO.IN)
GPIO.setwarnings(False)
def my_callback(M_PIN):
    if GPIO.input(M_PIN) == GPIO.HIGH:
        print("PIN HIGH")
    elif GPIO.input(M_PIN) == GPIO.LOW:
        print("PIN LOW")

GPIO.add_event_detect(M_PIN, GPIO.BOTH, callback = my_callback, bouncetime=50)
while(True):
    time.sleep(1)
Answered By: dougy