hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

3 LED control input Python script for Raspberry Pi GPIO

Wed May 21, 2014 2:42 pm

]Hi everyone, I posted a tutorial video with a Python script, using the GPIO pins of the Raspberry Pi and a breadboard, for controlling 3 LEDs with user input. The link of the video I shared is in : https://www.youtube.com/watch?v=T-47R88fgBo
Hope you like it, and feel free to share the code included here and in the video and please suggest any code modification ideas.

Thank you

Hernâni Arsénio


Code:

import os
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(7,GPIO.OUT)
GPIO.setup(11,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
#Setup variables for user input
led_choice = 0
count = 0

os.system('clear')

print "Which LED you want to blink?"
print "1: Red?"
print "2: Green?"
print "3: Yellow?"
print "4: All?"
led_choice = input("Make your choice: ")

if led_choice == 1:
os.system('clear')
print "You choose the red LED"
count = input("How many times you want it to blink?: ")
while count > 0:
GPIO.output(7,GPIO.HIGH)
time.sleep(1)
GPIO.output(7,GPIO.LOW)
time.sleep(1)
count = count - 1

if led_choice == 2:
os.system('clear')
print "You choose the green LED"
count = input("How many times you want it to blink?: ")
while count > 0:
GPIO.output(11,GPIO.HIGH)
time.sleep(1)
GPIO.output(11,GPIO.LOW)
time.sleep(1)
count = count - 1
if led_choice == 3:
os.system('clear')
print "You choose the yellow LED"
count = input("How many times you want it to blink?: ")
while count > 0:
GPIO.output(13,GPIO.HIGH)
time.sleep(1)
GPIO.output(13,GPIO.LOW)
time.sleep(1)
count = count - 1

if led_choice == 4:
os.system('clear')
print "You choose all LEDs"
count = input("How many times you want them to blink?: ")
while count > 0:
GPIO.output(7,GPIO.HIGH)
time.sleep(1)
GPIO.output(7,GPIO.LOW)

GPIO.output(11,GPIO.HIGH)
time.sleep(1)
GPIO.output(11,GPIO.LOW)

GPIO.output(13,GPIO.HIGH)
time.sleep(1)
GPIO.output(13,GPIO.LOW)

count = count - 1


GPIO.cleanup()

User avatar
MattHawkinsUK
Posts: 538
Joined: Tue Jan 10, 2012 8:48 pm
Location: UK
Contact: Website

Re: 3 LED control input Python script for Raspberry Pi GPIO

Wed May 21, 2014 7:34 pm

You need to wrap your code in

Code: Select all

[code]
[/code] tags so it keeps the indentation. Otherwise if people cut and paste it won't work as intended.
My Raspberry Pi blog and home of the BerryClip Add-on board : http://www.raspberrypi-spy.co.uk/
Follow me on Google+, Facebook, Pinterest and Twitter (@RPiSpy)

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Re: 3 LED control input Python script for Raspberry Pi GPIO

Wed May 21, 2014 7:50 pm

Here´s the code, thank you!

Code: Select all

import os
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(7,GPIO.OUT)
GPIO.setup(11,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
#Setup variables for user input
led_choice = 0
count = 0

os.system('clear')

print "Which LED you want to blink?"
print "1: Red?"
print "2: Green?"
print "3: Yellow?"
print "4: All?"
led_choice = input("Make your choice: ")

if led_choice == 1:
	os.system('clear')
	print "You choose the red LED"
	count = input("How many times you want it to blink?: ")
	while count > 0:
		GPIO.output(7,GPIO.HIGH)
		time.sleep(1)
		GPIO.output(7,GPIO.LOW)
		time.sleep(1)
		count = count - 1
		
if led_choice == 2:
	os.system('clear')
	print "You choose the green LED"
	count = input("How many times you want it to blink?: ")
	while count > 0:
		GPIO.output(11,GPIO.HIGH)
		time.sleep(1)
		GPIO.output(11,GPIO.LOW)
		time.sleep(1)
		count = count - 1
if led_choice == 3:
        os.system('clear')
        print "You choose the yellow LED"
        count = input("How many times you want it to blink?: ")
        while count > 0:
                GPIO.output(13,GPIO.HIGH)
                time.sleep(1)
                GPIO.output(13,GPIO.LOW)
                time.sleep(1)
                count = count - 1

if led_choice == 4:
	os.system('clear')
	print "You choose all LEDs"
	count = input("How many times you want them to blink?: ")
	while count > 0:
		GPIO.output(7,GPIO.HIGH)
		time.sleep(1)
		GPIO.output(7,GPIO.LOW)
		
                GPIO.output(11,GPIO.HIGH)
		time.sleep(1)
		GPIO.output(11,GPIO.LOW)
                
                GPIO.output(13,GPIO.HIGH)
                time.sleep(1)
                GPIO.output(13,GPIO.LOW)
               
                count = count - 1
                

GPIO.cleanup()

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Guess the magic number python script for controlling LEDs

Thu May 22, 2014 12:47 am

Hi everyone, i shared a new video in Youtube with the following Python program that is capable of guess a number between 0 and 999, and if your guess is higher than the defined "magic number" it will blink the Red LED five times, if your guess is lower than the "magic number" it will blink the green LED five times and if your guess the magic number defined as 321, all the 3 LEDs will blink five times.
All of this using the same wiring diagram of my last post:

The link to the video: https://www.youtube.com/watch?v=WQpjPH_n_Qs
And the code :

Code: Select all

import os
import math
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(7,GPIO.OUT)
GPIO.setup(11,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
#Setup variables for user input
number = 321
count = 5
os.system('clear')
print("Guess a magic number between 0 and 999")

# Prompt the user to guess the number
guess = input("Enter your guess: ")

if guess == number:
    print("Yes, the number is " + str(number))
    
    while count > 0:
    	GPIO.output(7,GPIO.HIGH)
	time.sleep(1)
	GPIO.output(7,GPIO.LOW)
		
        GPIO.output(11,GPIO.HIGH)
        time.sleep(1)
	GPIO.output(11,GPIO.LOW)
                
        GPIO.output(13,GPIO.HIGH)
        time.sleep(1)
        GPIO.output(13,GPIO.LOW)
               
        count = count - 1

elif guess > number:
 print("Your guess is too high")
 
 while count > 0:
  
   GPIO.output(7,GPIO.HIGH)
   time.sleep(1)
   GPIO.output(7,GPIO.LOW)
   time.sleep(1)
   count = count - 1

else:
 print("Your guess is too low")
 while count > 0:
   GPIO.output(11,GPIO.HIGH)
   time.sleep(1)
   GPIO.output(11,GPIO.LOW)
   time.sleep(1)
   count = count - 1         

GPIO.cleanup()

Please share and sugest any modifications to the code

Thank you all

Hernâni Arsénio

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Re: 3 LED control input Python script for Raspberry Pi GPIO

Sun May 25, 2014 6:44 pm

Updated wiring diagram here: https://drive.google.com/file/d/0ByFgW1 ... sp=sharing
Also updated in the videos
I guess i´ve done wrong placing the resistors, but now it looks fine and working.

Thank you

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Re: 3 LED control input Python script for Raspberry Pi GPIO

Sun May 25, 2014 9:33 pm

Hi everyone I made a bit of modification to the code of the program : 3 LED control input Python script for Raspberry Pi GPIO
Just made it with the purpose of now if we choose option 4 for all the 3 LEDs they will blink all at the same time instead of one after the other, blinking the number of times we choose. the code is now like this:

Code: Select all

import os
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(7,GPIO.OUT)
GPIO.setup(11,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
#Setup variables for user input
led_choice = 0
count = 0

os.system('clear')

print "Which LED you want to blink?"
print "1: Red?"
print "2: Green?"
print "3: Yellow?"
print "4: All?"
led_choice = input("Make your choice: ")

if led_choice == 1:
	os.system('clear')
	print "You choose the red LED"
	count = input("How many times you want it to blink?: ")
	while count > 0:
		GPIO.output(7,GPIO.HIGH)
		time.sleep(1)
		GPIO.output(7,GPIO.LOW)
		time.sleep(1)
		count = count - 1
		
if led_choice == 2:
	os.system('clear')
	print "You choose the green LED"
	count = input("How many times you want it to blink?: ")
	while count > 0:
		GPIO.output(11,GPIO.HIGH)
		time.sleep(1)
		GPIO.output(11,GPIO.LOW)
		time.sleep(1)
		count = count - 1
if led_choice == 3:
        os.system('clear')
        print "You choose the yellow LED"
        count = input("How many times you want it to blink?: ")
        while count > 0:
                GPIO.output(13,GPIO.HIGH)
                time.sleep(1)
                GPIO.output(13,GPIO.LOW)
                time.sleep(1)
                count = count - 1

if led_choice == 4:
	os.system('clear')
	print "You choose all LEDs"
	count = input("How many times you want them to blink?: ")
	while count > 0:
		GPIO.output(7,GPIO.HIGH)
		GPIO.output(11,GPIO.HIGH)
	        GPIO.output(13,GPIO.HIGH)
		time.sleep(1)
		GPIO.output(7,GPIO.LOW)
                GPIO.output(11,GPIO.LOW)
                GPIO.output(13,GPIO.LOW)
                time.sleep(1)
                count = count - 1
                

GPIO.cleanup()
Made also the same modification in the Guess the magic number python script for controlling LEDs with Raspberry Pi GPIO, with the same purpose. So the updated code is now like this:

Code: Select all

import os
import math
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(7,GPIO.OUT)
GPIO.setup(11,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
#Setup variables for user input
number = 321
count = 5
os.system('clear')
print("Guess a magic number between 0 and 999")

# Prompt the user to guess the number
guess = input("Enter your guess: ")

if guess == number:
    print("Yes, the number is " + str(number))
    
    while count > 0:
    	GPIO.output(7,GPIO.HIGH)
	GPIO.output(11,GPIO.HIGH)
	GPIO.output(13,GPIO.HIGH)
        time.sleep(1)
	GPIO.output(7 ,GPIO.LOW)
	GPIO.output(11,GPIO.LOW)
        GPIO.output(13,GPIO.LOW)
        time.sleep(1)
               
        count = count - 1

elif guess > number:
 print("Your guess is too high")
 
 while count > 0:
  
   GPIO.output(7,GPIO.HIGH)
   time.sleep(1)
   GPIO.output(7,GPIO.LOW)
   time.sleep(1)
   count = count - 1

else:
 print("Your guess is too low")
 while count > 0:
   GPIO.output(11,GPIO.HIGH)
   time.sleep(1)
   GPIO.output(11,GPIO.LOW)
   time.sleep(1)
   count = count - 1         

GPIO.cleanup()

The link to this updated scripts is now in the shared videos in this post or here for the 3 LED control input Python script for Raspberry Pi GPIO program : https://drive.google.com/file/d/0ByFgW1 ... sp=sharing and for the Guess the magic number python script for controlling LEDs with Raspberry Pi GPIO program here : https://drive.google.com/file/d/0ByFgW1 ... sp=sharing
Feel free to share comment, for any suggestion for modifications or new ideas.

Thank you

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Re: 3 LED control input Python script for Raspberry Pi GPIO

Tue Jun 03, 2014 1:40 am

Hello everyone, i´ve made a bit of change in the code so the program is now running with a bit of code modification to make it run more properly, only by changing the order of the variables, that make the guessed number if lower than 321 will blink the yellow LED and the green LED five times. And if the guess is higher than 321 it will blink the yellow LED and the red LED five times.
Please share and comment for new ideas. It is already updated in the video I shared: "Guess the magic number python script for controlling LEDs with Raspberry Pi GPIO" in https://www.youtube.com/watch?v=WQpjPH_n_Qs but the code is now like this:

Code: Select all

import os
import math
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(7,GPIO.OUT)
GPIO.setup(11,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
#Setup variables for user input
number = 321
count = 5
os.system('clear')
print("Guess a magic number between 0 and 999")

# Prompt the user to guess the number
guess = input("Enter your guess: ")

if guess == number:
    print("Yes, the number is " + str(number))
    
    while count > 0:
    	GPIO.output(7,GPIO.HIGH)
	GPIO.output(11,GPIO.HIGH)
	GPIO.output(13,GPIO.HIGH)
        time.sleep(1)
	GPIO.output(7 ,GPIO.LOW)
	GPIO.output(11,GPIO.LOW)
        GPIO.output(13,GPIO.LOW)
        time.sleep(1)
               
        count = count - 1

elif guess > number:
 print("Your guess is too high")
 
 while count > 0:
   GPIO.output(13,GPIO.HIGH)
   time.sleep(1)
   GPIO.output(13,GPIO.LOW)  
   GPIO.output(7,GPIO.HIGH)
   time.sleep(1)
   GPIO.output(7,GPIO.LOW)
   time.sleep(1)
   count = count - 1

else:
 print("Your guess is too low")
 while count > 0:
   GPIO.output(13,GPIO.HIGH)
   time.sleep(1)
   GPIO.output(13,GPIO.LOW)
   GPIO.output(11,GPIO.HIGH)
   time.sleep(1)
   GPIO.output(11,GPIO.LOW)
   time.sleep(1)
   count = count - 1         

GPIO.cleanup()


Or you can download the script from here: https://drive.google.com/file/d/0ByFgW1 ... sp=sharing
Thank you

User avatar
AndrewS
Posts: 3625
Joined: Sun Apr 22, 2012 4:50 pm
Location: Cambridge, UK
Contact: Website

Re: 3 LED control input Python script for Raspberry Pi GPIO

Tue Jul 08, 2014 10:56 pm

Rather than having the 'magic number' always be 321, you could make the game more 'fun' by doing

Code: Select all

import random
number = random.randint(0,999)
and then you could experiment with having the program continuing to loop (printing out "higher" or "lower") until the player guesses the correct answer (but perhaps you'd want to use a lower maximum than 999 ;) ).


As https://docs.python.org/2/library/functions.html#input explains, it's better to use raw_input than input. But as you want the value as an integer rather than a string, you'd do something like

Code: Select all

guess = int(raw_input("Enter your guess: "))

You seem to like flashing LEDs (who doesn't!), so rather than repeating the same chunks of code over and over again you could make them into a reusable function

Code: Select all

def flash_led(pin, count, interval=1):
    for i in range(count):
        GPIO.output(pin, GPIO.HIGH)
        time.sleep(interval)
        GPIO.output(pin, GPIO.LOW)
        time.sleep(interval)
and then you could do flash_led(7, 5) to make GPIO7 blink 5 times, or you could do flash_led(11, 12, 0.3) the make GPIO11 blink 12 times, but much faster.

And you could extend it to flash multiple LEDs at once

Code: Select all

def flash_leds(pin_list, count, interval=1):
    for i in range(count):
        for pin in pin_list:
            GPIO.output(pin, GPIO.HIGH)
        time.sleep(interval)
        for pin in pin_list:
            GPIO.output(pin, GPIO.LOW)
        time.sleep(interval)
calling it with e.g. flash_leds([11, 13, 7], 4) to make it flash all your LEDs 4 times 8-)

Have you had a read through of http://www.raspberrypi.org/documentatio ... /README.md yet?

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Re: 3 LED control input Python script for Raspberry Pi GPIO

Tue Jul 08, 2014 11:00 pm

Great tip, i´ll do that. Thanks.

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Re: 3 LED control input Python script for Raspberry Pi GPIO

Tue Jul 08, 2014 11:25 pm

By the way, is true that i like to make scripts using LEDs, for some reasons: first of all because of the scarcity of resources for more electronic components to make more complex programs, and last, but not the least, my wife works as educational psychologist in a school with children with problems such as autism, and she gave me the idea of making these scripts for interaction with LEDs for cognitive learning using computer programs for helping the students.
The Raspberry Pi is a UK made mini PC, developed in the Cambridge Labs (at least, I guess that is what I´ve read) with a lot of resources for making programs combining the GPIO / Python applied to the "Real World".

I´ll keep on experimenting new scripts, with LEDs or even more components in the future, but I have to say that it is fascinating what we can do with some skills on programming and electronics.

Minimalism turned into great things is the "flag" of the RPi.

Thanks for the suggestions AndrewS, i´ll keep on working.

Best regards

Hernâni Arsénio

User avatar
AndrewS
Posts: 3625
Joined: Sun Apr 22, 2012 4:50 pm
Location: Cambridge, UK
Contact: Website

Re: 3 LED control input Python script for Raspberry Pi GPIO

Wed Jul 09, 2014 12:01 am

At the recent CamJam one of the speakers described how one of the students in his after-school Raspberry Pi club made a simple game in Python using nothing more than a single LED.
When you start the game it flashes the LED a random number of times (with a 1-second pause between flashes), and asks you to type in the number of flashes you saw. If you get it right, it makes the flashes quicker, flashes a different number of times, and again asks you to type in the number of flashes you saw. And it keeps repeating (getting faster each time) until you get it wrong, when the game is over. Obviously the challenge is to get as many correct guesses as possible.
The speaker was saying how it shows that just with a bit of imagination, fun games are achievable even with very simple inputs and outputs :)

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Re: 3 LED control input Python script for Raspberry Pi GPIO

Wed Jul 09, 2014 12:07 am

"just with a bit of imagination, fun games are achievable even with very simple inputs and outputs"

That´s true, often the simplest solutions are the best in big problems... :)

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Re: 3 LED control input Python script for Raspberry Pi GPIO

Tue Jul 15, 2014 3:58 pm

I´ve written this script that is more like a test program to be followed closely by a tutor or a psychologist, but also to help learn sequential logic to children with problems like Asperger Syndrome, Autism, Down Syndrome, and other problems related to cognitive disorders.
It can be described as: "This script was written to make a user understand the meaning of sequential logic. The combination of different inputs gives a certain output. A constant output(RED LED) is given as the program starts, and by trying different inputs the user is asked to reach a different constant output(GREEN LED) by using the inputs learned."
Children with Asperger Syndrome have great difficulty to count, associate numbers to arithmetics and also counting the days of the week.
I´ve followed AndrewS advice and made some research and bought some push-down switches to make the inputs. and the code is like:

Code: Select all

#This script was written to make a user understand the meaning of sequential
#logic. The combination of different inputs gives a certain output.
#A constant output(RED LED) is given as the program starts, and by trying
#different inputs the user is asked to reach a different constant
#output(GREEN LED) by using the inputs learned.
import os
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD) #GPIO setup for Board Pin number
GPIO.setwarnings(False)
GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Circuit ON
GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Circuit OFF
GPIO.setup(11, GPIO.OUT) #GREEN LED
GPIO.setup(12, GPIO.OUT) #RED LED

while True:
 try:
  input_state = GPIO.input(7)        #Variables for push button ON
  input_state_reset = GPIO.input(13) #and push button Reset
  if input_state == False:
   print('Circuit ON')
   GPIO.output(11, GPIO.HIGH)
   GPIO.output(12, GPIO.LOW)
   time.sleep(0.2)  #deboucing
   os.system('clear') 
  elif input_state_reset == False:
   print('Reset')
   GPIO.output(11, GPIO.LOW)
   GPIO.output(12, GPIO.LOW)
   time.sleep(2)
   os.system('clear')
  if input_state == False and input_state_reset == False: #Boolean if statement for both inputs pressed at same time
   print('TEST COMPLETE')                                 
   GPIO.output(11, GPIO.HIGH)
   GPIO.output(12, GPIO.LOW)
   time.sleep(4)
  else:
   print('Circuit OFF')
   GPIO.output(11, GPIO.LOW)
   GPIO.output(12, GPIO.HIGH)
   time.sleep(0.2)
   os.system('clear')   
 except (RuntimeError, KeyboardInterrupt): #Stop program by pressing Ctrl+C
  GPIO.cleanup()                           #until it stops and lights out 
                                           #all LEDs. 
I´ve took a picture of the circuit, to give a general idea : https://drive.google.com/file/d/0ByFgW1 ... sp=sharing

Feel free to share the code, give sugestions, corrections and new ideas

Thank you

Hernâni Arsénio
Last edited by hernaniarsenio on Tue Jul 15, 2014 8:46 pm, edited 2 times in total.

User avatar
AndrewS
Posts: 3625
Joined: Sun Apr 22, 2012 4:50 pm
Location: Cambridge, UK
Contact: Website

Re: 3 LED control input Python script for Raspberry Pi GPIO

Tue Jul 15, 2014 4:52 pm

I haven't tested your code, but it looks fine. Guess a few comments sprinkled around wouldn't hurt ;-)

For more GPIO tutorials, see http://raspi.tv/rpi-gpio

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Re: 3 LED control input Python script for Raspberry Pi GPIO

Tue Jul 15, 2014 8:55 pm

I´m trying to make the program stop when the print('TEST COMPLETE') occurs as also as printing the time in seconds the test took to reach this state. The game/test (?) could also return the number of times the print('Circuit ON') and print('Reset') occurs.
That data could be analysed for statistics purposes to be used in studies of learning progress of the user that tries the the inputs until he reaches the (TEST COMPLETE) output.
When I test this program I have some trouble to syncronize the (TEST COMPLETE) output, I guess changing the time.sleep function would make it work better.
Please reply for sugestions or new ideas.

Thank you

Hernâni Arsénio

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Re: 3 LED control input Python script for Raspberry Pi GPIO

Sat Jul 19, 2014 10:41 pm

Hello everyone, I´ve been working in this script and managed to make the time.sleep function work better and figured out how to end the program by the time that both the inputs are pressed.
Still need ideas how to apply statistic data at the end of the program as also as the running time of the test/game (?).
The code is now:

Code: Select all

#This script was written to make a user understand the meaning of sequential
#logic. The combination of different inputs gives a certain output.
#A constant output(RED LED) is given as the program starts, and by trying
#different inputs the user is asked to reach a different constant
#output(GREEN LED) by using the inputs learned. 
import os
import sys
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD) #GPIO setup mode for board pin number
GPIO.setwarnings(False)
GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Circuit ON
GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Circuit OFF
GPIO.setup(11, GPIO.OUT) #GREEN LED
GPIO.setup(12, GPIO.OUT) #RED LED
while True:
 try:
  input_state = GPIO.input(7)
  input_state_reset = GPIO.input(13)
  if input_state == False:
    print('Circuit ON')
    GPIO.output(11, GPIO.HIGH)
    GPIO.output(12, GPIO.LOW)
    time.sleep(0.1)
    os.system('clear')  
  elif input_state_reset == False:
    print('Reset')
    GPIO.output(11, GPIO.LOW)
    GPIO.output(12, GPIO.LOW)
    time.sleep(2)
    os.system('clear')
  if input_state == False and input_state_reset == False:  #Boolean if statement for both inputs pressed
   print('TEST COMPLETE')                                  #which ends the program by lighting up the Green LED
   GPIO.output(11, GPIO.HIGH)                              #and the turning down the LEDs 
   GPIO.output(12, GPIO.LOW)
   time.sleep(3)
   os.system('clear')
   GPIO.cleanup()
   exit()
  else:
   print('Circuit OFF')
   GPIO.output(11, GPIO.LOW)
   GPIO.output(12, GPIO.HIGH) 
   time.sleep(0.05)
   os.system('clear')
 except (RuntimeError, KeyboardInterrupt): #By pressing Ctrl+C the user can end the program
  GPIO.cleanup()

Pictures that show both constant outputs
Circuit OFF: https://drive.google.com/file/d/0ByFgW1 ... sp=sharing
TEST COMPLETE: https://drive.google.com/file/d/0ByFgW1 ... sp=sharing
Feel free to share the code, and give sugestions, corrections and new ideas.

Thank you

Hernâni Arsénio

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Re: 3 LED control input Python script for Raspberry Pi GPIO

Sun Oct 19, 2014 9:25 pm

Hello everyone, I´ve managed to make something else in the latest code that I shared, and now the program is able to give the tester the overall time of the test and the number of tried inputs until the right combination of inputs is done and we reach the final constant output (GREEN LED).
I´ve shared a video on Youtube in this link: http://youtu.be/fMe1RoaDl4E showing a bit how it works, and it has on the video description the wiring diagram and python script links for download, and the used materials.

Code:

Code: Select all

#This script was written to make a user understand the meaning of sequential
#logic. The combination of different inputs gives a certain output.
#A constant output(RED LED) is given as the program starts, and by trying
#different inputs the user is asked to reach a different constant
#output(GREEN LED) by using the inputs learned. 
import os
import sys
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD) #GPIO setup mode for board pin number
GPIO.setwarnings(False)
GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Circuit ON
GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Circuit OFF
GPIO.setup(11, GPIO.OUT) #GREEN LED
GPIO.setup(12, GPIO.OUT) #RED LED
start_time = time.time()
count = 0
while True:
 try:
  input_state = GPIO.input(7)
  input_state_reset = GPIO.input(13)
  buttonState = GPIO.input(7)
  buttonState2 = GPIO.input(13)
  
  if (input_state == False) and (buttonState == False):
    print('Circuit ON')
    GPIO.output(11, GPIO.HIGH)
    GPIO.output(12, GPIO.LOW)
    count = count + 1
    time.sleep(0.1)
    os.system('clear')  
  elif (input_state_reset == False and  buttonState2 == False):
    print('Reset')
    GPIO.output(11, GPIO.LOW)
    GPIO.output(12, GPIO.LOW)
    count = count + 1
    time.sleep(2)
    os.system('clear')
  if input_state == False and input_state_reset == False:  #Boolean if statement for both inputs pressed
   print('TEST COMPLETE')                                  #which ends the program by lighting up the Green LED
   GPIO.output(11, GPIO.HIGH)                              #printing the overall time of the test/game and the number
                                                           #of input tries and the turning down the LEDs
   GPIO.output(12, GPIO.LOW)
   count = count + 1
   end_time = time.time()
   duration = end_time - start_time
   time.sleep(3)
   print "Time of test: " + str(duration) + " seconds"
   time.sleep(15)
   print("Number of tries: %s times" % count)
   time.sleep(10)
   os.system('clear')
   GPIO.cleanup()
   exit()
  else:
   print('Circuit OFF')
   GPIO.output(11, GPIO.LOW)
   GPIO.output(12, GPIO.HIGH) 
   time.sleep(0.05)
   os.system('clear')
 except (RuntimeError, KeyboardInterrupt): #By pressing Ctrl+C the user can end the program
  GPIO.cleanup()

Please feel free to share the code, and give new ideas and sugestions.

Thank you

Hernâni Arsénio

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Re: 3 LED control input Python script for Raspberry Pi GPIO

Tue Jan 06, 2015 5:31 am

Hello everyone, I´ve made this simple program in Python and the Raspberry Pi GPIO with the purpose of assembling a device that could help children with Autism more sequential systems such as in this case, the seasons of the year.
It ca be described like this: This script was written to make a user understand the meaning of sequential logic.
For understanding that different INPUTS gives a different OUTPUT when conbined to try to teach
the seasons of the year with three sequences of two INPUTS and a fourth of three INPUTS for making the user
find the "Hidden Season" that would be the SPRING. It starts with this order: SUMMER -> FALL -> WINTER -> SPRING.
The program starts with a constant RED LED on, everytime that one of the three INPUTS is pressed a season is reached
it constantly lights on the GREEN LED, tells the tester the time until that OUTPUT was reached and the number of tries until
it occured. And then the program restarts. Only if the three INPUTS are pressed, the "Hidden Season" is found, it lights on the
YELLOW LED and tells the tester the overall time of the test and the overall tries until the "Hidden Season" was found for data
collection of a tester.
I´ve also shared a video today in Youtube that shows a bit how it work an it includes the wiring diagram and the Python script to download,

The Python code is here:

Code: Select all

#This script was written to make a user understand the meaning of sequential logic.
#For understanding that different INPUTS gives a different OUTPUT when conbined to try to teach
#the seasons of the year with three sequences of two INPUTS and a fourth of three INPUTS for making the user
#find the "Hidden Season" that would be the SPRING. It starts with this order: SUMMER -> FALL -> WINTER -> SPRING.
#The program starts with a constant RED LED on, everytime that one of the three INPUTS is pressed a season is reached
#it constantly lights on the GREEN LED, tells the tester the time until that OUTPUT was reached and the number of tries until
#it occured. And then the program restarts. Only if the three INPUTS are pressed, the "Hidden Season" is found, it lights on the
#YELLOW LED and tells the tester the overall time of the test and the overall tries until the "Hidden Season" was found for data 
#collection of a tester. 
import os
import sys
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD) #GPIO setup mode for board pin number
GPIO.setwarnings(False)
GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP) #INPUTS
GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(11, GPIO.OUT) #GREEN LED
GPIO.setup(12, GPIO.OUT) #RED LED
GPIO.setup(18, GPIO.OUT) #YELLOW LED
start_time = time.time()
end_time = 0
unit_count = 0
count = 0
while True:
  
 try:
   input_state = GPIO.input(7)
   input_state2 = GPIO.input(15)
   input_state3 = GPIO.input(16)
  
   if (input_state == False) or (input_state2 == False ) or (input_state3 == False) :
    print 'Circuit ON'
    GPIO.output(11, GPIO.HIGH)
    GPIO.output(12, GPIO.LOW)
    GPIO.output(18, GPIO.LOW)
    unit_count = unit_count + 1
    time.sleep(0.1)
    os.system('clear') 
  
   if (input_state == False and input_state2 == False and input_state3 == False):
    print "SPRING:" +  " END OF TEST"
    GPIO.output(11, GPIO.LOW)
    GPIO.output(12, GPIO.LOW)
    GPIO.output(18, GPIO.HIGH)
    count = unit_count + count
    end_time = time.time() - start_time
    duration = end_time
    time.sleep(1)
    print "Overall time of test: " + str(duration) + " seconds"
    time.sleep(1)
    print("Number of tries: %s times" % count)
    time.sleep(8)
    os.system('clear')
    GPIO.cleanup()
    exit(0)   
   if (input_state == False and input_state2 == False): 
    print "SUMMER:" + " TEST 1 COMPLETE"                               
    GPIO.output(11, GPIO.HIGH)                             
    GPIO.output(12, GPIO.LOW)
    unit_count = unit_count + 1
    end_time = time.time()
    duration = end_time - start_time
    time.sleep(1)
    print "Time of test: " + str(duration) + " seconds"
    time.sleep(1)
    print("Number of tries: %s times" % unit_count)
    time.sleep(8)
    os.system('clear')
   if (input_state2 == False and input_state3 == False):
    print "FALL:"  " TEST 2 COMPLETE"                                 
    GPIO.output(11, GPIO.HIGH)                          
    GPIO.output(12, GPIO.LOW)
    unit_count = unit_count + 1
    end_time = time.time()
    duration = end_time - start_time
    time.sleep(1)
    print "Time of test: " + str(duration) + " seconds"
    time.sleep(1)
    print("Number of tries: %s times" % unit_count)
    time.sleep(8)
    os.system('clear')
   if (input_state == False and input_state3 == False):
    print  "WINTER:" +  " TEST 3 COMPLETE"  
    GPIO.output(11, GPIO.HIGH)                              
    GPIO.output(12, GPIO.LOW)
    unit_count = unit_count + 1
    end_time = time.time()
    duration = end_time - start_time
    time.sleep(1)
    print "Time of test: " + str(duration) + " seconds"
    time.sleep(1)
    print("Number of tries: %s times" % unit_count)
    time.sleep(8)
    os.system('clear')
   else:
    print "CIRCUIT OFF"
    GPIO.output(11, GPIO.LOW)
    GPIO.output(12, GPIO.HIGH)
    GPIO.output(18, GPIO.LOW)
    time.sleep(0.05)
    os.system('clear')
 except (RuntimeError, KeyboardInterrupt): #By pressing Ctrl+C the user can end the program
    GPIO.cleanup()

Feel free to share the code, and give sugestions, corrections and new ideas.

Thank you

Hernâni Arsénio

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Re: 3 LED control input Python script for Raspberry Pi GPIO

Fri Mar 13, 2015 2:48 pm

Hello everyone, i would like to share with all the Raspberry Pi Community, and this forum my gladness of gathering the knowledge on Python language programming, in which it wouldn´t be possible to create a small project that is in the Future Ideas Worldwide Academic Competition as one of the 30 final competitors of the program, check it on: https://join.futureideas.org, that was made in partnership with my university here in Portugal as part of my Bachellor degree in Network and Telecommunications Systems of Escola Superior de Tecnologia do Instituto Politécnico de Setúbal in the Analogic Electronics project area, that required the use of a Arduino and the C/C++ language, but became more developed and refined applying it to the Raspberry Pi GPIO and Python language.

The idea description:

https://join.futureideas.org/temp/priva ... 1423039788

Sequential logic learning for children with Autism and Asperger Syndrome

T­his study was made as a project for the Analogic Electronics class of the Bachellor degree in Network and Telecommunications Systems of Escola Superior de Tecnologia do Instituto Politécnico de Setúbal, Portugal. It is focused in trying to understand if a group of children with Autism and Asperger Syndrome are able to understand sequential logic by trying different learned input combinations to reach a constant output different from the initial. The study is based in a electronic program made in C language, using a breadboard, push-down switches, a 2x16 LCD, light emission diodes (LEDs), a small speaker and a programmable device called Arduino.

Sub-Topic
Neuroscience
Problem
Does children with Autism and Asperger Syndrome can learn different sequential logics using self-learned input combinations? Does children with different kinds of Austism (Kanner or Asperger) have the same difficulty in ending the test/game? Can this test/game make children with Autism get to a path of evolution and learning, and create a bigger list of interests and activities?
Research
Due to the low developments in the area of mental health, and specially in the area of Development and Behaviour problems such as Autism. It is urgent that we can reach something different in this area by trying to design a low-cost device that can be used for data collection of psychologists, teachers and parents of children with Autism. It is known that since 2009 that O Connor made the last research in this area by trying to teach sequential logic, but since then no one tried anything with such simple inputs and stimulous. The goal is to make a device that can be assembled with a low amount of resources that can teach children with autism counting, association and sequential systems, for example: days of the week, months and seasons of the year by applying in the device more inputs (switches), outputs (LEDs) and by editing a more complex code.
Solution
The solution to the mentioned problems passes fundamentally by trying to make a symbiose between Technology and Mental Health, by making a device that can be used for continuous tests in children that pass the game/test, and by gathering data for researchers to study the evolution of the game/test completion, once that the program is capable to print in a smal LCD the overall time of the test and the number of tries until the correct input is reached by the tested children.
Application
Description of the application: This script was written to make a user understand the meaning of sequential logic. The combination of different inputs gives a certain output. A constant output(RED LED) is given as the program starts, and by trying different inputs the user is asked to reach a different constant output(GREEN LED) by using the inputs learned. In a first approach to this test we can say that it has no time limit, and it can and should be followed closely by the parents, so the children can at least focus in the device inputs and outputs. It can be showed as task or game to be accomplished and explained to the parents, that the children must try to reach a contant green light instead of the red light (OUTPUTS) by using as many time the combinations of two buttons. For instance, it can be explained to children with Asperger Sydrome by the following method: "Let?s play a game, this game has two buttons, if you press them, different lights of different colors will be on or off. When the game starts, only the red light will be on and what I want you to do is that you try to make the green light be always on, and for that you must press the buttons"

C/C++ code:

Code: Select all

//This script was written to make a user understand the meaning of sequential
//logic. The combination of different inputs gives a certain output.
//A constant output(RED LED) is given as the program starts, and by trying
//different inputs the user is asked to reach a different constant
//output(GREEN LED) by using the inputs learned. 

#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73
#define NOTE_DS2 78
#define NOTE_E2  82
#define NOTE_F2  87
#define NOTE_FS2 93
#define NOTE_G2  98
#define NOTE_GS2 104
#define NOTE_A2  110
#define NOTE_AS2 117
#define NOTE_B2  123
#define NOTE_C3  131
#define NOTE_CS3 139
#define NOTE_D3  147
#define NOTE_DS3 156
#define NOTE_E3  165
#define NOTE_F3  175
#define NOTE_FS3 185
#define NOTE_G3  196
#define NOTE_GS3 208
#define NOTE_A3  220
#define NOTE_AS3 233
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_CS5 554
#define NOTE_D5  587
#define NOTE_DS5 622
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_FS5 740
#define NOTE_G5  784
#define NOTE_GS5 831
#define NOTE_A5  880
#define NOTE_AS5 932
#define NOTE_B5  988
#define NOTE_C6  1047
#define NOTE_CS6 1109
#define NOTE_D6  1175
#define NOTE_DS6 1245
#define NOTE_E6  1319
#define NOTE_F6  1397
#define NOTE_FS6 1480
#define NOTE_G6  1568
#define NOTE_GS6 1661
#define NOTE_A6  1760
#define NOTE_AS6 1865
#define NOTE_B6  1976
#define NOTE_C7  2093
#define NOTE_CS7 2217
#define NOTE_D7  2349
#define NOTE_DS7 2489
#define NOTE_E7  2637
#define NOTE_F7  2794
#define NOTE_FS7 2960
#define NOTE_G7  3136
#define NOTE_GS7 3322
#define NOTE_A7  3520
#define NOTE_AS7 3729
#define NOTE_B7  3951
#define NOTE_C8  4186
#define NOTE_CS8 4435
#define NOTE_D8  4699
#define NOTE_DS8 4978
#include <LiquidCrystal.h>
const int buttonPin = 13;  //Defining variable names for each input and output   
const int buttonPin2 = 9; 
const int redLed = 6;
const int greenLed = 10;
int buttonState = 0;      //Defining logic state of each input
int buttonState2 = 0;
int count = 0;            //Defining number of pressed inputs
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int melody[] = {
  NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3, NOTE_B3, NOTE_C4};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = 
{
  4, 8, 8, 4,4,4,3,4 };
// initialize the library with the numbers of the interface pins


void setup() 
{ 
  
 //configure pin2 as an input and enable the internal pull-up resistor
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
  pinMode(redLed, OUTPUT); //RED LED
  pinMode(greenLed, OUTPUT); // GREEN LED 
  lcd.begin(16, 2); //set up the LCD's number of columns and rows
  lcd.print("START TEST!");
  delay(2000);
  lcd.clear();  
}

void loop() {
buttonState = digitalRead(buttonPin);
buttonState2 = digitalRead(buttonPin2);
 
  {
  //read the pushbutton value into a variable
  
  int sensorVal = digitalRead(buttonPin);
  int sensorVal2 = digitalRead(buttonPin2);
  //print out the value of the pushbutton
  
 
  if (sensorVal == HIGH && sensorVal2 == HIGH) {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    lcd.setCursor(0, 0);
    lcd.print("CIRCUIT OFF");
    delay(500);
    lcd.clear();
 } 
  if (sensorVal == LOW && sensorVal2 == LOW){
    digitalWrite(redLed, LOW);                 
    digitalWrite(greenLed, HIGH); 
    delay(2000); 
    for (int thisNote = 0; thisNote < 7; thisNote++) {

     int noteDuration = 1000/noteDurations[thisNote]; //Melody for alerting the tester that the game or test is complete
     tone(7, melody[thisNote],noteDuration);
     int pauseBetweenNotes = noteDuration * 1.30;
     delay(pauseBetweenNotes);
     noTone(7);
     } 
    lcd.setCursor(0, 0);
    lcd.print("TEST COMPLETE"); //Moment when both inputs are pressed and the test is finished
    delay(5000);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Time of test:"); 
    lcd.setCursor(0, 1);
    lcd.print(millis()/1000);
    lcd.print(" seconds");
    delay(15000);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Number of tries:");
    lcd.setCursor(0, 1);
    lcd.print(count++); 
    lcd.print(" times");
    exit(0);
 } 
 if ((sensorVal == LOW && sensorVal2 == HIGH) && (buttonState == LOW && buttonState2 == HIGH)) //Declaration of if fuction using two AND statements
 {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    lcd.setCursor(0, 0);
    lcd.print("CIRCUIT ON");
    count++;
    delay(500);
    lcd.clear();
 } 
 if ((sensorVal == HIGH && sensorVal2 == LOW) && (buttonState == HIGH && buttonState2 == LOW)) //Declaration of if fuction using two AND statements
 {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, LOW);
   
    delay(500);
    lcd.setCursor(0, 0);
    count++;
    lcd.print("RESET");
    delay(500);
    lcd.clear();
 }
 
  }
}
  





Python code:

Code: Select all

#This script was written to make a user understand the meaning of sequential
#logic. The combination of different inputs gives a certain output.
#A constant output(RED LED) is given as the program starts, and by trying
#different inputs the user is asked to reach a different constant
#output(GREEN LED) by using the inputs learned. 
import os
import sys
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD) #GPIO setup mode for board pin number
GPIO.setwarnings(False)
GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Circuit ON
GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Circuit OFF
GPIO.setup(11, GPIO.OUT) #GREEN LED
GPIO.setup(12, GPIO.OUT) #RED LED
start_time = time.time()
count = 0
while True:
 try:
  input_state = GPIO.input(7)
  input_state_reset = GPIO.input(13)
  buttonState = GPIO.input(7)
  buttonState2 = GPIO.input(13)
  
  if (input_state == False) and (buttonState == False):
    print('Circuit ON')
    GPIO.output(11, GPIO.HIGH)
    GPIO.output(12, GPIO.LOW)
    count = count + 1
    time.sleep(0.1)
    os.system('clear')  
  elif (input_state_reset == False and  buttonState2 == False):
    print('Reset')
    GPIO.output(11, GPIO.LOW)
    GPIO.output(12, GPIO.LOW)
    count = count + 1
    time.sleep(2)
    os.system('clear')
  if input_state == False and input_state_reset == False:  #Boolean if statement for both inputs pressed
   print('TEST COMPLETE')                                  #which ends the program by lighting up the Green LED
   GPIO.output(11, GPIO.HIGH)                              #printing the overall time of the test/game and the number
                                                           #of input tries and the turning down the LEDs
   GPIO.output(12, GPIO.LOW)
   count = count + 1
   end_time = time.time()
   duration = end_time - start_time
   time.sleep(3)
   print "Time of test: " + str(duration) + " seconds"
   time.sleep(15)
   print("Number of tries: %s times" % count)
   time.sleep(10)
   os.system('clear')
   GPIO.cleanup()
   exit()
  else:
   print('Circuit OFF')
   GPIO.output(11, GPIO.LOW)
   GPIO.output(12, GPIO.HIGH) 
   time.sleep(0.05)
   os.system('clear')
 except (RuntimeError, KeyboardInterrupt): #By pressing Ctrl+C the user can end the program
  GPIO.cleanup()
Seasons of the year learning (Python):

Code: Select all

#This script was written to make a user understand the meaning of sequential logic.
#For understanding that different INPUTS gives a different OUTPUT when conbined to try to teach
#the seasons of the year with three sequences of two INPUTS and a fourth of three INPUTS for making the user
#find the "Hidden Season" that would be the SPRING. It starts with this order: SUMMER -> FALL -> WINTER -> SPRING.
#The program starts with a constant RED LED on, everytime that one of the three INPUTS is pressed a season is reached
#it constantly lights on the GREEN LED, tells the tester the time until that OUTPUT was reached and the number of tries until
#it occured. And then the program restarts. Only if the three INPUTS are pressed, the "Hidden Season" is found, it lights on the
#YELLOW LED and tells the tester the overall time of the test and the overall tries until the "Hidden Season" was found for data 
#collection of a tester. 
import os
import sys
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD) #GPIO setup mode for board pin number
GPIO.setwarnings(False)
GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP) #INPUTS
GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(11, GPIO.OUT) #GREEN LED
GPIO.setup(12, GPIO.OUT) #RED LED
GPIO.setup(18, GPIO.OUT) #YELLOW LED
start_time = time.time()
end_time = 0
unit_count = 0
count = 0
while True:
  
 try:
   input_state = GPIO.input(7)
   input_state2 = GPIO.input(15)
   input_state3 = GPIO.input(16)
  
   if (input_state == False) or (input_state2 == False ) or (input_state3 == False) :
    print 'Circuit ON'
    GPIO.output(11, GPIO.HIGH)
    GPIO.output(12, GPIO.LOW)
    GPIO.output(18, GPIO.LOW)
    unit_count = unit_count + 1
    time.sleep(0.1)
    os.system('clear') 
  
   if (input_state == False and input_state2 == False and input_state3 == False):
    print "SPRING:" +  " END OF TEST"
    GPIO.output(11, GPIO.LOW)
    GPIO.output(12, GPIO.LOW)
    GPIO.output(18, GPIO.HIGH)
    count = unit_count + count
    end_time = time.time() - start_time
    duration = end_time
    time.sleep(1)
    print "Overall time of test: " + str(duration) + " seconds"
    time.sleep(1)
    print("Number of tries: %s times" % count)
    time.sleep(8)
    os.system('clear')
    GPIO.cleanup()
    exit(0)   
   if (input_state == False and input_state2 == False): 
    print "SUMMER:" + " TEST 1 COMPLETE"                               
    GPIO.output(11, GPIO.HIGH)                             
    GPIO.output(12, GPIO.LOW)
    unit_count = unit_count + 1
    end_time = time.time()
    duration = end_time - start_time
    time.sleep(1)
    print "Time of test: " + str(duration) + " seconds"
    time.sleep(1)
    print("Number of tries: %s times" % unit_count)
    time.sleep(8)
    os.system('clear')
   if (input_state2 == False and input_state3 == False):
    print "FALL:"  " TEST 2 COMPLETE"                                 
    GPIO.output(11, GPIO.HIGH)                          
    GPIO.output(12, GPIO.LOW)
    unit_count = unit_count + 1
    end_time = time.time()
    duration = end_time - start_time
    time.sleep(1)
    print "Time of test: " + str(duration) + " seconds"
    time.sleep(1)
    print("Number of tries: %s times" % unit_count)
    time.sleep(8)
    os.system('clear')
   if (input_state == False and input_state3 == False):
    print  "WINTER:" +  " TEST 3 COMPLETE"  
    GPIO.output(11, GPIO.HIGH)                              
    GPIO.output(12, GPIO.LOW)
    unit_count = unit_count + 1
    end_time = time.time()
    duration = end_time - start_time
    time.sleep(1)
    print "Time of test: " + str(duration) + " seconds"
    time.sleep(1)
    print("Number of tries: %s times" % unit_count)
    time.sleep(8)
    os.system('clear')
   else:
    print "CIRCUIT OFF"
    GPIO.output(11, GPIO.LOW)
    GPIO.output(12, GPIO.HIGH)
    GPIO.output(18, GPIO.LOW)
    time.sleep(0.05)
    os.system('clear')
 except (RuntimeError, KeyboardInterrupt): #By pressing Ctrl+C the user can end the program
    GPIO.cleanup()
Declaration of the application of the game/test in two children with Autism (Kanner)
https://join.futureideas.org/apps/IMT/U ... 1423039788

Sorry for being in Portuguese, but it basically says that i´ve applied a test about sequential logic learning in two children with Autism here in Portugal with the kind help of APPDA (Associação Portuguesa para as Pertubações de Desnvolvimento e Autismo) a portuguese association that helps children and parents of children with Autism.

Thank you Raspberry Pi Community and wish me luck.

Hernâni Arsénio

big_riq
Posts: 19
Joined: Sat Mar 28, 2015 3:17 am

Re: 3 LED control input Python script for Raspberry Pi GPIO

Sat Mar 28, 2015 3:42 am

i use the original coding. and made specific modifications. what im having a problem with is getting it to loop and stopping the program on command. i have a different model pi so i changed the gpio outputs etc, also made it generate a random number between 1 and 100.

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Re: 3 LED control input Python script for Raspberry Pi GPIO

Sat Mar 28, 2015 9:43 am

Thank you for your reply big_riq. Please try to press CTRL+C several times to end the loop. It worked fine for me in Raspberry Pi Model B.

Best regards

Hernâni Arsénio

big_riq
Posts: 19
Joined: Sat Mar 28, 2015 3:17 am

Re: 3 LED control input Python script for Raspberry Pi GPIO

Sat Apr 11, 2015 2:33 am

i was trying to do was.. since i changed the code to import a random number, if the person guesses wrong i want it t o promt to them if its too high or low, ask them to guess again, and all within running the program once. for the reason that if its a random number that number will change every time i run the program again.

thanks in advance

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Re: 3 LED control input Python script for Raspberry Pi GPIO

Thu Sep 24, 2015 5:50 pm

Hello everyone, I´ve been working around with the Sequential logic game/test in Raspberry Pi GPIO Python program, and made some modifications to the code, so it could add some new features to the game/test, such as the input of a name and age of the tested subject, and in the end of the program ir could display a table where all the data is shown to the tester.

Python code:

Code: Select all

#This script was written to make a user understand the meaning of sequential
#logic. The combination of different inputs gives a certain output.
#A constant output(RED LED) is given as the program starts, and by trying
#different inputs the user is asked to reach a different constant
#output(GREEN LED) by using the inputs learned. 
import os
import sys
import RPi.GPIO as GPIO
import time
import texttable as tt
GPIO.setmode(GPIO.BOARD) #GPIO setup mode for board pin number
GPIO.setwarnings(False)
GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Circuit ON
GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Circuit OFF
GPIO.setup(11, GPIO.OUT) #GREEN LED
GPIO.setup(12, GPIO.OUT) #RED LED
count = 0
name = 0
age = 0
name = raw_input("Enter name: ")
age = raw_input("Enter age: ")
os.system('clear')
start_time = time.time()
while True:
 try:
  input_state = GPIO.input(7)
  input_state_reset = GPIO.input(13)
  buttonState = GPIO.input(7)
  buttonState2 = GPIO.input(13)
  
  if (input_state == False) and (buttonState == False):
    print('Circuit ON')
    GPIO.output(11, GPIO.HIGH)
    GPIO.output(12, GPIO.LOW)
    count = count + 1
    time.sleep(0.1)
    os.system('clear')  
  elif (input_state_reset == False and  buttonState2 == False):
    print('Reset')
    GPIO.output(11, GPIO.LOW)
    GPIO.output(12, GPIO.LOW)
    count = count + 1
    time.sleep(2)
    os.system('clear')
  if input_state == False and input_state_reset == False:  #Boolean if statement for both inputs pressed
   print('TEST COMPLETE')                                  #which ends the program by lighting up the Green LED
   GPIO.output(11, GPIO.HIGH)                              #printing the overall time of the test/game and the number
                                                           #of input tries and the turning down the LEDs
   GPIO.output(12, GPIO.LOW)
   count = count + 1
   end_time = time.time()
   duration = end_time - start_time
   time.sleep(3)
   
   tab = tt.Texttable()

   x = [[]] # The empty row will have the header

   for i in range(1,2):
    x.append([name + " " + age + " yrs", count , duration]) 
    tab.add_rows(x)
    tab.set_cols_align(['r','r','r'])
    tab.header(['Name and age', 'Number of tries', 'Time of test (sec)'])
    print tab.draw()
    time.sleep(15)
    os.system('clear')
    GPIO.cleanup()
    exit()
  else:
   print('Circuit OFF')
   GPIO.output(11, GPIO.LOW)
   GPIO.output(12, GPIO.HIGH) 
   time.sleep(0.05)
   os.system('clear')
 except (RuntimeError, KeyboardInterrupt): #By pressing Ctrl+C the user can end the program
  GPIO.cleanup()

It couldn´t be possible to do make it the texttable module installed in the Raspberry Pi, so thanks to Gerome Fournier for the excellent work in this module.

I´ve also shared a video on YouTube here: https://youtu.be/mmoZPNysIrc , explaining how the second version of the Sequential logic game/test works.

Thank you all.

P.S: About the Worlwide Academic Competition, the project itself was one of the 10 finalists of the Future of Health Theme, so thank you so much for the help, support, and ideas to all the Raspberry Pi Community.

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Re: 3 LED control input Python script for Raspberry Pi GPIO

Sat Sep 26, 2015 11:38 am

Hello everyone, I´ve managed to make some more modifications in the Python code of Sequential logic game/test in Raspberry Pi GPIO Python, so it now can ask the tester for the date input aswell, and also the program is now capable to save in a external text (.txt), the results and details of each test that is made everytime we run the program on a table, for database and analisys purpose. The text file can be saved on a USB drive to be openned on a computer, for example.


Updated code:

Code: Select all

#This script was written to make a user understand the meaning of sequential
#logic. The combination of different inputs gives a certain output.
#A constant output(RED LED) is given as the program starts, and by trying
#different inputs the user is asked to reach a different constant
#output(GREEN LED) by using the inputs learned. 
import os
import sys
import RPi.GPIO as GPIO
import time
import texttable as tt
GPIO.setmode(GPIO.BOARD) #GPIO setup mode for board pin number
GPIO.setwarnings(False)
GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Circuit ON
GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Circuit OFF
GPIO.setup(11, GPIO.OUT) #GREEN LED
GPIO.setup(12, GPIO.OUT) #RED LED
count = 0
name = 0
age = 0
date = 0
date = raw_input("Enter date: ")
name = raw_input("Enter name: ")
age = raw_input("Enter age: ")
os.system('clear')
start_time = time.time()
while True:
 try:
  input_state = GPIO.input(7)
  input_state_reset = GPIO.input(13)
  buttonState = GPIO.input(7)
  buttonState2 = GPIO.input(13)
  
  if (input_state == False) and (buttonState == False):
    print('Circuit ON')
    GPIO.output(11, GPIO.HIGH)
    GPIO.output(12, GPIO.LOW)
    count = count + 1
    time.sleep(0.1)
    os.system('clear')  
  elif (input_state_reset == False and  buttonState2 == False):
    print('Reset')
    GPIO.output(11, GPIO.LOW)
    GPIO.output(12, GPIO.LOW)
    count = count + 1
    time.sleep(0.1)
    os.system('clear')
  if input_state == False and input_state_reset == False:  #Boolean if statement for both inputs pressed
   print('TEST COMPLETE')                                  #which ends the program by lighting up the Green LED
   GPIO.output(11, GPIO.HIGH)                              #printing the overall time of the test/game and the number
                                                           #of input tries and the turning down the LEDs
   GPIO.output(12, GPIO.LOW)
   count = count + 1
   end_time = time.time()
   duration = end_time - start_time
   time.sleep(3)
   
   tab = tt.Texttable()

   x = [[]] # The empty row will have the header

   for i in range(1,2):
    x.append([name + " " + age + " yrs", count , duration]) 
    tab.add_rows(x)
    tab.set_cols_align(['r','r','r'])
    tab.header(['Name and age', 'Number of tries', 'Time of test (sec)'])
    print date
    print tab.draw()
    time.sleep(15)
    file = open("newfile.txt", "a")

    file.write(date + " \n"  + tab.draw() + "\n")
    file.close()
    os.system('clear')
    GPIO.cleanup()
    exit()
  else:
   print('Circuit OFF')
   GPIO.output(11, GPIO.LOW)
   GPIO.output(12, GPIO.HIGH) 
   time.sleep(0.1)
   os.system('clear')
 except (RuntimeError, KeyboardInterrupt): #By pressing Ctrl+C the user can end the program
  GPIO.cleanup()
Text file (.txt) example:

Code: Select all

September 26, 2015 
+--------------+-----------------+--------------------+
| Name and age | Number of tries | Time of test (sec) |
+==============+=================+====================+
|   John 5 yrs |               6 |              5.192 |
+--------------+-----------------+--------------------+
September 26, 2015 
+--------------+-----------------+--------------------+
| Name and age | Number of tries | Time of test (sec) |
+==============+=================+====================+
|   Mark 9 yrs |               5 |              4.178 |
+--------------+-----------------+--------------------+
September 26, 2015 
+--------------+-----------------+--------------------+
| Name and age | Number of tries | Time of test (sec) |
+==============+=================+====================+
|   Eric 4 yrs |               6 |              6.523 |
+--------------+-----------------+--------------------+
September 26, 2015 
+--------------+-----------------+--------------------+
| Name and age | Number of tries | Time of test (sec) |
+==============+=================+====================+
|  Arthur 9 yrs |               6 |              5.533 |
+--------------+-----------------+--------------------+
Feel free to share the code, and give ideas, corrections and sugestions

Thank you

Hernâni Arsénio

hernaniarsenio
Posts: 31
Joined: Wed May 21, 2014 2:31 pm
Location: Setúbal, Portugal

Re: 3 LED control input Python script for Raspberry Pi GPIO

Mon Mar 21, 2016 3:30 am

Hello everyone, I´ve made some changes in the code so now the tester doesn´t need to insert the date of the tes everytime the code is executed.
I´ve shared a video today where you can find more information: https://youtu.be/9uAaiNsFeKc

Code in Python:

Code: Select all

#This script was written to make a user understand the meaning of sequential
#logic. The combination of different inputs gives a certain output.
#A constant output(RED LED) is given as the program starts, and by trying
#different inputs the user is asked to reach a different constant
#output(GREEN LED) by using the inputs learned. 
import os
import sys
import RPi.GPIO as GPIO
import time
import texttable as tt
GPIO.setmode(GPIO.BOARD) #GPIO setup mode for board pin number
GPIO.setwarnings(False)
GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Circuit ON
GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Circuit OFF
GPIO.setup(11, GPIO.OUT) #GREEN LED
GPIO.setup(12, GPIO.OUT) #RED LED
count = 0
name = 0
age = 0
name = raw_input("Enter name: ")
age = raw_input("Enter age: ")
os.system('clear')
start_time = time.time()
while True:
 try:
  input_state = GPIO.input(7)
  input_state_reset = GPIO.input(13)
  buttonState = GPIO.input(7)
  buttonState2 = GPIO.input(13)
  
  if (input_state == False) and (buttonState == False):
    print('Circuit ON')
    GPIO.output(11, GPIO.HIGH)
    GPIO.output(12, GPIO.LOW)
    count = count + 1
    time.sleep(0.1)
    os.system('clear')  
  elif (input_state_reset == False and  buttonState2 == False):
    print('Reset')
    GPIO.output(11, GPIO.LOW)
    GPIO.output(12, GPIO.LOW)
    count = count + 1
    time.sleep(0.1)
    os.system('clear')
  if input_state == False and input_state_reset == False:  #Boolean if statement for both inputs pressed
   print('TEST COMPLETE')                                  #which ends the program by lighting up the Green LED
   GPIO.output(11, GPIO.HIGH)                              #printing the overall time of the test/game and the number
                                                           #of input tries and the turning down the LEDs
   GPIO.output(12, GPIO.LOW)
   count = count + 1
   end_time = time.time()
   duration = end_time - start_time
   time.sleep(3)
   
   tab = tt.Texttable()

   x = [[]] # The empty row will have the header

   for i in range(1,2):
    x.append([name + " " + age + " yrs", count , duration]) 
    tab.add_rows(x)
    tab.set_cols_align(['r','r','r'])
    tab.header(['Name and age', 'Number of tries', 'Time of test (sec)'])
    print "Date: " + (time.strftime("%d/%m/%Y"))
    print tab.draw()
    time.sleep(15)
    file = open("newfile.txt", "a")

    file.write("Date: " + (time.strftime("%d/%m/%Y")) + " \n"  + tab.draw() + "\n")
    file.close()
    os.system('clear')
    GPIO.cleanup()
    exit()
  else:
   print('Circuit OFF')
   GPIO.output(11, GPIO.LOW)
   GPIO.output(12, GPIO.HIGH) 
   time.sleep(0.1)
   os.system('clear')
 except (RuntimeError, KeyboardInterrupt): #By pressing Ctrl+C the user can end the program
  GPIO.cleanup()

Please feel free to share the code, give new ideas, sugestions and corrections

Thank you!

Hernâni Arsénio

Return to “Python”