Posts: 1
Joined: Fri Jul 13, 2018 6:19 pm

N.O button press to generate 4 random GPIO outputs

Fri Jul 13, 2018 6:41 pm

I am very much a beginner as in this is my first raspberry pi project. I’m in a time crunch and happen to have a raspberry pi laying around my office, as it may not be the best product for what is needed I was hoping I could reach out and have a member of this community help me (please please)
I have a Raspberry Pi 3 model B here and what I would like to have is: I would like to press a single N.O button and trigger a random closure of 1 of the GPIO outputs.... as in each time I momentarily press the button I get a momentary closure of one of 4 GPIOs randomly. If this is not possible with the Pi alone I have a 4 relay shield that could be used for this. (It could be better actually) I would love the support and an excited for this to spring board me into programming these things more.
Again thank you ahead of time for the help.

Posts: 3985
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: N.O button press to generate 4 random GPIO outputs

Sat Jul 14, 2018 9:36 am


Yes what you want to do should be possible.

put this together off the top of my head its untested so it may not work, but it should give you a starting point.

Code: Select all

import RPi.GPIO as GPIO
import random
GPIO.setup(6, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(19, GPIO.OUT)
GPIO.setup(26, GPIO.OUT)

GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)

matrix = [6, 13, 19, 26]
    print  " Start "
    while True:
        # waiting for button press
        while GPIO.input(23) == 1:
        print "Button is pressed."
        num = random.randint(1,4)
        pin = matrix [num]
        # waiting for button release
        while GPIO.input(23) == 0:
        print "Button is release."
except KeyboardInterrupt:
if it works, it should wait for the press of the button connected to gpio 23 and then select on of the 4 output gpio's ( 6,13,19,26 ) and switch it on while ever the button is pressed.
Remember we want information no help
The use of crystal balls & mind reading is not supported

Return to “Beginners”

Who is online

Users browsing this forum: No registered users and 26 guests