Search code examples
pythondjangobackgroundraspberry-pi2gpio

Raspberry Pi and Django - Background check GPIO Button


I'm having troubles to get this thing work. Basically i have my raspberry, with apache and django running good, in my views i can turn on and off a led using gpiozero, i can do pretty much every output thing i want with gpio pins.

But there is this thing i can't do: How to get input from gpio pins?

I tried setting up Celery but there are 2 problems, i can't make it work how i want (after 3 days of tests looking 10 different guides, even official ones) and it doesn't do exactly what i want. Celery can do background process only when they are called in a django view.

What i want to do is having a background process that run 24/24 that watch pin input activity. Simple example: When the button connected on gpio 23 is pressed, change a value in a django model or turn on another gpio pin.

Someone with a hint? Thanks all!


Solution

  • I have worked with Django and Celery but not with the Raspberry Pi, so this might not be an ideal solution. Since you haven't provided your code I'll try to outline how you would go about creating this functionality.

    1. Set up your Django Application and Celery integration

    2. Create the Celery Task to modify your django model value when it's called

    3. Create a new script and import the celery task from your Django project

    4. Implement a function in your script that triggers the Celery Job

    5. Create a button object and add a call to your function to the on_pressed method (see below)

    6. Run your script

    Based on code from this article.

    from gpiozero import Button
    from signal import pause
    
    def trigger_celery_task():
        # Add the code to create a new task here
    
    button = Button(2)
    
    button.when_pressed = trigger_celery_task
    
    # Wait for events
    pause()