How I made a slot machine using the Raspberry Pi and Python.

Recently I made a slot machine with a Raspberry Pi, LEDs, a homemade coin slot and Python.

Part 1: The LEDs

Firstly I connected the LEDs to my Raspberry Pi. You’ll need 9 of them, 3 of each color.

IMG_1061.JPG

Here are which GPIO pins the LEDs are connected to:

R1 > 13
Y1 > 16
G1 > 26

R2 > 22
Y2 > 23
G2 > 27

R3 > 4
Y3 > 17
G3 > 24

Part 2: The Coin Slot

Then I made the coin slot – I used some lego technic to make a hole the size of a 2p coin and then put a copper strip on each side. I then attached ground to one strip and pin 18 to another, and coded it the same as I would a push button. Tin foil will also work.

Penny Slot wiring.png

EDIT: The black cables going from the LEDs to the ground strip in the diagram should be 470 ohm resistors, not cables.

Part 3: The code

import RPi.GPIO as GPIO
from time import sleep
from random import randint
import subprocess

R1,Y1,G1,R2,Y2,G2,R3,Y3,G3=13,16,26,22,23,27,4,17,24
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.setup((R1,Y1,G1,R2,Y2,G2,R3,Y3,G3),GPIO.OUT)

while True:
    inputValue = GPIO.input(18)
    if inputValue == False:
        print("Coin entered")
        for i in range(12):
            GPIO.output((R1,Y1,G1,R2,Y2,G2,R3,Y3,G3),GPIO.HIGH)
            sleep(0.05*i)
            GPIO.output((R1,Y1,G1,R2,Y2,G2,R3,Y3,G3),GPIO.LOW)
            sleep(0.05*i)
        a,b,c=randint(1,3),randint(1,3),randint(1,3)
        if a==1:
            GPIO.output(R1,GPIO.HIGH)
        elif a==2:
            GPIO.output(Y1,GPIO.HIGH)
        elif a==3:
            GPIO.output(G1,GPIO.HIGH)
        if b==1:
            GPIO.output(R2,GPIO.HIGH)
        elif b==2:
            GPIO.output(Y2,GPIO.HIGH)
        elif b==3:
            GPIO.output(G2,GPIO.HIGH)
        if c==1:
            GPIO.output(R3,GPIO.HIGH)
        elif c==2:
            GPIO.output(Y3,GPIO.HIGH)
        elif c==3:
            GPIO.output(G3,GPIO.HIGH)
        if a==b and b==c:
            print ("WINNER")
            #p=subprocess.Popen(["mpg123", 'Winner.mp3'])
        #else:
            #p=subprocess.Popen(["mpg123", 'Fail.mp3'])
    sleep(0.01)

As you can see, you can play sound effects is they win or lose on the lines p=subprocess.Popen(["mpg123", 'Winner.mp3']). However, you will need to have mpg123 installed by typing sudo apt-get install mpg123 into the terminal. Then you will have to download two sound effect audio files (one for winner, one for loser) and replace ‘Winner.mp3’ and ‘Loser.mp3’ with their locations. Also, remember to plug a speaker into the audio jack.

Part 4: Decorating

I placed everything inside a cardboard box and made holes for the LEDs to be visible. I also placed a plastic container underneath the coin slot to collect the coins. Lastly, I glued some pieces of paper to the box with instructions.

If you have any questions, feel free to ask in the comments!

Advertisements