Sunday, January 11, 2015

Using the append method

The switch from pre-initializing a blank list to using the append method was much, much faster than I thought it would be. It only required one new function, which was the len() function. This just returns the length of a list. That's really all I have to say about this changes. Here's the code:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)

def LEDflash(channel):
    GPIO.output(LED[i], GPIO.HIGH)
    time.sleep(0.5)
    GPIO.output(LED[i], GPIO.LOW)

def pushed(channel):
    global busy, MaxLength
    if busy == False:
        busy = True
        for i in range(1,5):
            if channel == button[i]:
                pressed = i
                LEDflash(i)
        buttonpush.append(pressed)
        ShowData()
        if len(buttonpush) == MaxLength:
            print "MaxLength reached"
            ResetData()
        busy = False

def ResetData():
    global MaxLength, buttonpush
    buttonpush = []
    print "Data cleared"
    ShowData()

def ShowData():
    if Display == True:
        print buttonpush

# Game Constants
MaxLength = 5
Display = True

# Label buttons and pins
button = [4, 12, 16, 20, 21]
LED = [22, 5, 6, 13, 19]

# Set GPIO pins
for i in range (0,5):
    GPIO.setup(button[i], GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(LED[i], GPIO.OUT)

for i in range (1,5):
    GPIO.add_event_detect(button[i], GPIO.FALLING, callback=pushed, bouncetime=200)

# Initialize variables
busy = False
buttonpush = []
game = True

GPIO.output(LED[0], GPIO.HIGH)
while game == True:
    GPIO.wait_for_edge(button[0], GPIO.FALLING)
    if len(buttonpush) == 0:
        game = False
    else:
        ResetData()
GPIO.output(LED[0], GPIO.LOW)
GPIO.cleanup()
I need to think carefully about the actual game now. I tried to just wing it, and I don't really like how the code is turning out. It's a confused mess, which I suppose is exactly what one would expect to happen if the code writer was just winging it. I'm going to spend some time thinking of the right way to organize the code so that everything works the way I want it to.

No comments:

Post a Comment