Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #95411 > unrolled thread

RPI.GPIO Help

Started byJohn McKenzie <davros@bellaliant.net>
First post2015-08-16 19:40 +0000
Last post2015-09-14 05:53 -0700
Articles 20 on this page of 27 — 7 participants

Back to article view | Back to comp.lang.python


Contents

  RPI.GPIO Help John McKenzie <davros@bellaliant.net> - 2015-08-16 19:40 +0000
    Re: RPI.GPIO Help MRAB <python@mrabarnett.plus.com> - 2015-08-16 21:15 +0100
      Re: RPI.GPIO Help John McKenzie <davros@bellaliant.net> - 2015-08-20 15:12 +0000
        Re: RPI.GPIO Help MRAB <python@mrabarnett.plus.com> - 2015-08-20 16:45 +0100
          Re: RPI.GPIO Help alister <alister.nospam.ware@ntlworld.com> - 2015-08-20 15:54 +0000
        Re: RPI.GPIO Help Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2015-08-20 21:27 -0400
          Re: RPI.GPIO Help John McKenzie <davros@bellaliant.net> - 2015-08-28 17:40 +0000
            Re: RPI.GPIO Help hakugin.gin@gmail.com - 2015-08-28 13:56 -0700
            Re: RPI.GPIO Help Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2015-08-29 14:21 -0400
    Re: RPI.GPIO Help John McKenzie <davros@bellaliant.net> - 2015-08-31 17:41 +0000
      Re: RPI.GPIO Help hakugin.gin@gmail.com - 2015-08-31 11:25 -0700
      Re: RPI.GPIO Help MRAB <python@mrabarnett.plus.com> - 2015-08-31 19:34 +0100
      Re: RPI.GPIO Help Johannes Bauer <dfnsonfsduifb@gmx.de> - 2015-09-01 10:58 +0200
    Re: RPI.GPIO Help Tim Daneliuk <tundra@bogus-city.tundraware.com> - 2015-08-31 14:07 -0500
      Re: RPI.GPIO Help Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2015-09-01 02:08 -0400
    Re: RPI.GPIO Help John McKenzie <davros@bellaliant.net> - 2015-09-02 18:50 +0000
    Re: RPI.GPIO Help John McKenzie <davros@bellaliant.net> - 2015-09-09 19:03 +0000
      Re: RPI.GPIO Help MRAB <python@mrabarnett.plus.com> - 2015-09-09 20:29 +0100
    Re: RPI.GPIO Help John McKenzie <davros@bellaliant.net> - 2015-09-10 15:56 +0000
      Re: RPI.GPIO Help John McKenzie <davros@bellaliant.net> - 2015-09-11 18:24 +0000
        Re: RPI.GPIO Help MRAB <python@mrabarnett.plus.com> - 2015-09-11 19:49 +0100
        Re: RPI.GPIO Help hakugin.gin@gmail.com - 2015-09-11 12:00 -0700
        Re: RPI.GPIO Help hakugin.gin@gmail.com - 2015-09-11 12:24 -0700
        Re: RPI.GPIO Help Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2015-09-11 21:10 -0400
    Re: RPI.GPIO Help John McKenzie <davros@bellaliant.net> - 2015-09-13 06:08 +0000
      Re: RPI.GPIO Help Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2015-09-13 12:24 -0400
      Re: RPI.GPIO Help hakugin.gin@gmail.com - 2015-09-14 05:53 -0700

Page 1 of 2  [1] 2  Next page →


#95411 — RPI.GPIO Help

FromJohn McKenzie <davros@bellaliant.net>
Date2015-08-16 19:40 +0000
SubjectRPI.GPIO Help
Message-ID<lG5Ax.73238$E26.47630@fx20.iad>
 Hello, all. I am hoping some people here are familiar with the RPi.GPIO 
python module for the Raspberry Pi.

 Very new to Python and electronics. Not to computing in general though. 
I posted for help about accepting key presses and then discovered that 
wiring up buttons directly to the Pi was 1/50th as difficult as I thought 
it would be so I am going a different route than keyboard emulation and 
needing GUI toolkits, etc.

 However, I am getting error messages with RPi.GPIO.

 I have three buttons, Red, Yellow and Blue in colour, attached to the 
Pi. The eventual goal is to have pressing one button result in changing 
the colour of an LED lightstrip to that colour and the Pi record how long 
the strip spent as each colour.

 For development purposes I have the controls near me and my desktop 
computer, and the Pi networked to this computer. For now I have each 
button press result in a print statement. When I get this working I will 
replace the print statements with the code to change colours on the LED 
strip using the Blinkstick module.

 This is the basic test code.


import atexit
import time
from blinkstick import blinkstick
import RPi.GPIO as GPIO  

led = blinkstick.find_first()
colour = 0
timered = 0
timeyellow = 0
timeblue = 0
timestamp = time.strftime("%H:%M:%S")


GPIO.setmode(GPIO.BCM)
GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)  
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 




def red_button(channel):
    colour = 1
    print "Red Button Pressed"
    while colour == 1:
        timered += 1

def yellow_button(channel):
    colour = 2
    print "Yellow Button Pressed"
    while colour == 2:
        timeyellow += 1

def blue_button(channel):
    colour = 3
    print "Blue Button Pressed"
    while colour == 3:
        timeblue += 1

while True:
    GPIO.add_event_detect(22, GPIO.RISING, callback=red_button, 
bouncetime=200)
    GPIO.add_event_detect(23, GPIO.RISING, callback=yellow_button, 
bouncetime=200)
    GPIO.add_event_detect(24, GPIO.RISING, callback=blue_button, 
bouncetime=200)


def exit_handler():
    print '\033[0;41;37mRed Team:\033[0m ', timered
    print '\033[0;43;30mYellow Time:\033[0m ', timeyellow
    print '\033[0;44;37mBlue Time:\033[0m ', timeblue
    flog = open('flag1log.text', 'a')
    flog.write(timestamp + '\n' + 'Red Team: ' + str(timered) + '\n' + 
'Yellow Team: ' + str(timeyellow) + '\n' + 'Blue Team: ' + str(timeblue) 
+ '\n')
    flog.close()
atexit.register(exit_handler)
GPIO.cleanup()



 This results in the error message "RuntimeError: Conflicting edge 
detection already enabled for this GPIO channel".  Running GPIO.cleanup() 
in the interpreter results in a message stating the GPIO pins are not 
assigned and there is nothing to cleanup.
 
  Removing line 40, the while True: line, removes the error, but the 
program does not sit and wait waiting for a button press, it just runs 
and ends a second later.
  
   There are other things this script will need, but this is the core 
function  that I need to get working -pressing a button does what I want 
and the script keeps running so I can press another button if I want. If 
are familiar with the RPi.GPIO or see a more general Python mistake that 
could be affecting everything know I would appreciate your help. Thanks.
   

[toc] | [next] | [standalone]


#95415

FromMRAB <python@mrabarnett.plus.com>
Date2015-08-16 21:15 +0100
Message-ID<mailman.45.1439756138.4764.python-list@python.org>
In reply to#95411
On 2015-08-16 20:40, John McKenzie wrote:
>
>   Hello, all. I am hoping some people here are familiar with the RPi.GPIO
> python module for the Raspberry Pi.
>
>   Very new to Python and electronics. Not to computing in general though.
> I posted for help about accepting key presses and then discovered that
> wiring up buttons directly to the Pi was 1/50th as difficult as I thought
> it would be so I am going a different route than keyboard emulation and
> needing GUI toolkits, etc.
>
>   However, I am getting error messages with RPi.GPIO.
>
>   I have three buttons, Red, Yellow and Blue in colour, attached to the
> Pi. The eventual goal is to have pressing one button result in changing
> the colour of an LED lightstrip to that colour and the Pi record how long
> the strip spent as each colour.
>
>   For development purposes I have the controls near me and my desktop
> computer, and the Pi networked to this computer. For now I have each
> button press result in a print statement. When I get this working I will
> replace the print statements with the code to change colours on the LED
> strip using the Blinkstick module.
>
>   This is the basic test code.
>
>
> import atexit
> import time
> from blinkstick import blinkstick
> import RPi.GPIO as GPIO
>
> led = blinkstick.find_first()
> colour = 0
> timered = 0
> timeyellow = 0
> timeblue = 0
> timestamp = time.strftime("%H:%M:%S")
>
>
> GPIO.setmode(GPIO.BCM)
> GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
> GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
> GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
>
>
>
>
> def red_button(channel):
>      colour = 1
>      print "Red Button Pressed"
>      while colour == 1:
>          timered += 1
>
> def yellow_button(channel):
>      colour = 2
>      print "Yellow Button Pressed"
>      while colour == 2:
>          timeyellow += 1
>
> def blue_button(channel):
>      colour = 3
>      print "Blue Button Pressed"
>      while colour == 3:
>          timeblue += 1
>
> while True:
>      GPIO.add_event_detect(22, GPIO.RISING, callback=red_button,
> bouncetime=200)
>      GPIO.add_event_detect(23, GPIO.RISING, callback=yellow_button,
> bouncetime=200)
>      GPIO.add_event_detect(24, GPIO.RISING, callback=blue_button,
> bouncetime=200)
>
>
> def exit_handler():
>      print '\033[0;41;37mRed Team:\033[0m ', timered
>      print '\033[0;43;30mYellow Time:\033[0m ', timeyellow
>      print '\033[0;44;37mBlue Time:\033[0m ', timeblue
>      flog = open('flag1log.text', 'a')
>      flog.write(timestamp + '\n' + 'Red Team: ' + str(timered) + '\n' +
> 'Yellow Team: ' + str(timeyellow) + '\n' + 'Blue Team: ' + str(timeblue)
> + '\n')
>      flog.close()
> atexit.register(exit_handler)
> GPIO.cleanup()
>
>
>
>   This results in the error message "RuntimeError: Conflicting edge
> detection already enabled for this GPIO channel".  Running GPIO.cleanup()
> in the interpreter results in a message stating the GPIO pins are not
> assigned and there is nothing to cleanup.
>
>    Removing line 40, the while True: line, removes the error, but the
> program does not sit and wait waiting for a button press, it just runs
> and ends a second later.
>
>     There are other things this script will need, but this is the core
> function  that I need to get working -pressing a button does what I want
> and the script keeps running so I can press another button if I want. If
> are familiar with the RPi.GPIO or see a more general Python mistake that
> could be affecting everything know I would appreciate your help. Thanks.
>
I'm looking at this:

     http://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/

As far as I can tell, the 'add_event_detect' method adds a callback.

However, you have it in a loop, so you're trying to add more than one
callback (actually, the same one more than once!), which it doesn't
like.

You should add the callbacks only once and then have some kind of sleep
or do-nothing loop, perhaps waiting for the signal to quit (I don't
have a Raspberry Pi, so I don't know what the usual practice is).

[toc] | [prev] | [next] | [standalone]


#95508

FromJohn McKenzie <davros@bellaliant.net>
Date2015-08-20 15:12 +0000
Message-ID<F7mBx.11314$Md3.3869@fx01.iad>
In reply to#95415
 Thanks for the reply. Also, thanks to Laura who replied via email.

 Tried a bunch of things based off these comments and I always ended up 
with one of two situations, the channel conflict error, or an instant run 
and quit issue. This new version of the code runs but is unresponsive. I 
removed loops then put in a short sleep loop. while True:
    time.sleep(0.1) It could be my hardware is done up wrong, but it 
looks OK. Perhaps it is always sleeping.

 Anyone at all know about GPIO and the Pi under the Python library 
RPi.GPIO please feel free to advise as to what the problem is most likely 
to be.


import atexit
import time
from blinkstick import blinkstick
import RPi.GPIO as GPIO  

led = blinkstick.find_first()
colour = 0
timered = 0
timeyellow = 0
timeblue = 0
timestamp = time.strftime("%H:%M:%S")



GPIO.setmode(GPIO.BCM)
GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)  
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 



def red_button(channel):
    colour = 1
    while colour == 1:
        print "Red Button pressed"
        timered += 1


def yellow_button(channel):
    colour = 2
    while colour == 2:
        print "Yellow Button pressed"
        timeyellow += 1


def blue_button(channel):
    colour = 3
    while colour == 3:
        print "Blue Button pressed"
        timeblue += 1

GPIO.add_event_detect(23, GPIO.RISING, callback=yellow_button, 
bouncetime=200)
GPIO.add_event_detect(22, GPIO.RISING, callback=red_button, 
bouncetime=200)
GPIO.add_event_detect(24, GPIO.RISING, callback=blue_button, 
bouncetime=200)

while True:
    time.sleep(0.1)

def exit_handler():
    print '\033[0;41;37mRed Team:\033[0m ', timered
    print '\033[0;103;30mYellow Team:\033[0m ', timeyellow
    print '\033[0;44;37mBlue Team:\033[0m ', timeblue
    flog = open('flag1log.text', 'a')
    flog.write(timestamp + '\n' + 'Red Team: ' + str(timered) + '\n' + 
'Yellow Team: ' + str(timeyellow) + '\n' + 'Blue Team: ' + str(timeblue) 
+ '\n')
    flog.close()
atexit.register(exit_handler)
GPIO.cleanup()



 Thanks.

[toc] | [prev] | [next] | [standalone]


#95509

FromMRAB <python@mrabarnett.plus.com>
Date2015-08-20 16:45 +0100
Message-ID<mailman.24.1440085563.28100.python-list@python.org>
In reply to#95508
On 2015-08-20 16:12, John McKenzie wrote:
>
>   Thanks for the reply. Also, thanks to Laura who replied via email.
>
>   Tried a bunch of things based off these comments and I always ended up
> with one of two situations, the channel conflict error, or an instant run
> and quit issue. This new version of the code runs but is unresponsive. I
> removed loops then put in a short sleep loop. while True:
>      time.sleep(0.1) It could be my hardware is done up wrong, but it
> looks OK. Perhaps it is always sleeping.
>
>   Anyone at all know about GPIO and the Pi under the Python library
> RPi.GPIO please feel free to advise as to what the problem is most likely
> to be.
>
>
> import atexit
> import time
> from blinkstick import blinkstick
> import RPi.GPIO as GPIO
>
> led = blinkstick.find_first()
> colour = 0
> timered = 0
> timeyellow = 0
> timeblue = 0
> timestamp = time.strftime("%H:%M:%S")
>
>
>
> GPIO.setmode(GPIO.BCM)
> GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
> GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
> GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
>
>
>
> def red_button(channel):
>      colour = 1
>      while colour == 1:
>          print "Red Button pressed"
>          timered += 1
>
>
> def yellow_button(channel):
>      colour = 2
>      while colour == 2:
>          print "Yellow Button pressed"
>          timeyellow += 1
>
>
> def blue_button(channel):
>      colour = 3
>      while colour == 3:
>          print "Blue Button pressed"
>          timeblue += 1
>
> GPIO.add_event_detect(23, GPIO.RISING, callback=yellow_button,
> bouncetime=200)
> GPIO.add_event_detect(22, GPIO.RISING, callback=red_button,
> bouncetime=200)
> GPIO.add_event_detect(24, GPIO.RISING, callback=blue_button,
> bouncetime=200)
>
> while True:
>      time.sleep(0.1)
>
> def exit_handler():
>      print '\033[0;41;37mRed Team:\033[0m ', timered
>      print '\033[0;103;30mYellow Team:\033[0m ', timeyellow
>      print '\033[0;44;37mBlue Team:\033[0m ', timeblue
>      flog = open('flag1log.text', 'a')
>      flog.write(timestamp + '\n' + 'Red Team: ' + str(timered) + '\n' +
> 'Yellow Team: ' + str(timeyellow) + '\n' + 'Blue Team: ' + str(timeblue)
> + '\n')
>      flog.close()
> atexit.register(exit_handler)
> GPIO.cleanup()
>
>
The function 'red_button' will be called when a rising edge is detected.

In that function, you're assigning to 'colour' but not changing it in
the loop, so it's basically just a busy loop. However, you're trying to
change 'timered', which is a global variable, but you're not declaring
it as global, so that will raise UnboundLocalError.

Similar remarks apply to the other two callbacks.

I think you'd be better off detecting both the rising and falling
edges, with a callback for each, recording when each edge occurred
(duration of press = time of falling edge - time of rising edge).

[toc] | [prev] | [next] | [standalone]


#95510

Fromalister <alister.nospam.ware@ntlworld.com>
Date2015-08-20 15:54 +0000
Message-ID<mr4t7d$8oo$1@speranza.aioe.org>
In reply to#95509
On Thu, 20 Aug 2015 16:45:53 +0100, MRAB wrote:

> On 2015-08-20 16:12, John McKenzie wrote:
>>
>>   Thanks for the reply. Also, thanks to Laura who replied via email.
>>
>>   Tried a bunch of things based off these comments and I always ended
>>   up
>> with one of two situations, the channel conflict error, or an instant
>> run and quit issue. This new version of the code runs but is
>> unresponsive. I removed loops then put in a short sleep loop. while
>> True:
>>      time.sleep(0.1) It could be my hardware is done up wrong, but it
>> looks OK. Perhaps it is always sleeping.
>>
>>   Anyone at all know about GPIO and the Pi under the Python library
>> RPi.GPIO please feel free to advise as to what the problem is most
>> likely to be.
>>
>>
>> import atexit import time from blinkstick import blinkstick import
>> RPi.GPIO as GPIO
>>
>> led = blinkstick.find_first()
>> colour = 0 timered = 0 timeyellow = 0 timeblue = 0 timestamp =
>> time.strftime("%H:%M:%S")
>>
>>
>>
>> GPIO.setmode(GPIO.BCM)
>> GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
>> GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
>> GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
>>
>>
>>
>> def red_button(channel):
>>      colour = 1 while colour == 1:
>>          print "Red Button pressed" timered += 1
>>
>>
>> def yellow_button(channel):
>>      colour = 2 while colour == 2:
>>          print "Yellow Button pressed"
>>          timeyellow += 1
>>
>>
>> def blue_button(channel):
>>      colour = 3 while colour == 3:
>>          print "Blue Button pressed" timeblue += 1
>>
>> GPIO.add_event_detect(23, GPIO.RISING, callback=yellow_button,
>> bouncetime=200)
>> GPIO.add_event_detect(22, GPIO.RISING, callback=red_button,
>> bouncetime=200)
>> GPIO.add_event_detect(24, GPIO.RISING, callback=blue_button,
>> bouncetime=200)
>>
>> while True:
>>      time.sleep(0.1)
>>
>> def exit_handler():
>>      print '\033[0;41;37mRed Team:\033[0m ', timered print
>>      '\033[0;103;30mYellow Team:\033[0m ', timeyellow print
>>      '\033[0;44;37mBlue Team:\033[0m ', timeblue flog =
>>      open('flag1log.text', 'a')
>>      flog.write(timestamp + '\n' + 'Red Team: ' + str(timered) + '\n' +
>> 'Yellow Team: ' + str(timeyellow) + '\n' + 'Blue Team: ' +
>> str(timeblue) + '\n')
>>      flog.close()
>> atexit.register(exit_handler)
>> GPIO.cleanup()
>>
>>
> The function 'red_button' will be called when a rising edge is detected.
> 
> In that function, you're assigning to 'colour' but not changing it in
> the loop, so it's basically just a busy loop. However, you're trying to
> change 'timered', which is a global variable, but you're not declaring
> it as global, so that will raise UnboundLocalError.
> 
> Similar remarks apply to the other two callbacks.
> 
> I think you'd be better off detecting both the rising and falling edges,
> with a callback for each, recording when each edge occurred (duration of
> press = time of falling edge - time of rising edge).

you may also find it more useful to post this to Comp.sys.raspberry_pi
the python skills may not be quite as in depth as here but they will know 
more about the raspberry hardware



-- 
The easiest way to get the root password is to become system admin.
	-- Unknown source

[toc] | [prev] | [next] | [standalone]


#95514

FromDennis Lee Bieber <wlfraed@ix.netcom.com>
Date2015-08-20 21:27 -0400
Message-ID<mailman.0.1440120462.13558.python-list@python.org>
In reply to#95508
On Thu, 20 Aug 2015 15:12:37 GMT, John McKenzie <davros@bellaliant.net>
declaimed the following:

>
> Thanks for the reply. Also, thanks to Laura who replied via email.
>
> Tried a bunch of things based off these comments and I always ended up 
>with one of two situations, the channel conflict error, or an instant run 
>and quit issue. This new version of the code runs but is unresponsive. I 
>removed loops then put in a short sleep loop. while True:
>    time.sleep(0.1) It could be my hardware is done up wrong, but it 
>looks OK. Perhaps it is always sleeping.
>
> Anyone at all know about GPIO and the Pi under the Python library 
>RPi.GPIO please feel free to advise as to what the problem is most likely 
>to be.

	Just curious, but have you considered asking in the news group
comp.sys.raspberry-pi? Granted, most of them seem to argue more about
getting the OS to behave than in programming...

>
>led = blinkstick.find_first()

	I don't see you doing anything with the LED...

>colour = 0
>timered = 0
>timeyellow = 0
>timeblue = 0
>timestamp = time.strftime("%H:%M:%S")
>
>
>
>GPIO.setmode(GPIO.BCM)
>GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
>GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)  
>GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 
>
>
>
>def red_button(channel):

	What is "channel"? Does it map to the ID of the pin that triggered? If
it does, you could get rid of the three callback functions and just use on
callback with a set of IF statements testing "channel" to determine the
button.

>    colour = 1
>    while colour == 1:
>        print "Red Button pressed"
>        timered += 1

	timered is not declared "global", so will be considered local to the
function... And since it isn't initialized, should be raising an error.

	You initialize "colour" to 1, and then loop until "colour" is NOT 1 --
but there is nothing inside the loop that changes the value of colour, so
the loop will never exit, which means the callback never exits, which means
the GPIO process will never regain control to test for other button
presses.
	

>
>while True:
>    time.sleep(0.1)
>
	You start an infinite loop, nothing below this point will be executed
meaning...

>def exit_handler():

	The exit handler will not be defined...

>    print '\033[0;41;37mRed Team:\033[0m ', timered
>    print '\033[0;103;30mYellow Team:\033[0m ', timeyellow
>    print '\033[0;44;37mBlue Team:\033[0m ', timeblue
>    flog = open('flag1log.text', 'a')
>    flog.write(timestamp + '\n' + 'Red Team: ' + str(timered) + '\n' + 
>'Yellow Team: ' + str(timeyellow) + '\n' + 'Blue Team: ' + str(timeblue) 
>+ '\n')

	Ugh... Please read up on Python string interpolation (or format method,
depending on Python version)

	I don't have an R-Pi, nor your colorful LED, so this is just
pseudo-code...

-=-=-=-=-=-=-

import atexit
import time
import blinkstick as bs
import RPi.GPIO as GPIO


class Button(object):
    modeSet = False
    
    def __init__(self, buttonPin, LED, colorCode):
        self.totalTime = 0
        self.downTime = 0
        self.LED = LED
        if colorCode.lower() in "rgb":
            self.colorCode = colorCode
        else:
            self.colorCode = None

        if not Button.modeSet:  #classwide (shared) value
            GPIO.setmode(GPIO.BCN)  #so only performed once
            Button.modeSet = True

        GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.add_event_detect(buttonPin, GPIO.RISING,
                              callback=self.buttonDown,
                              bouncetime=200)
        GPIO.add_event_detect(buttonPin, GPIO.FALLING, #guessing
                              callback=self.buttonUp,
                              bouncetime=200)

    def buttonDown(self, buttonPin):   #this design doesn't use the pin
        self.downTime = time.time()     #record when button pressed
        if self.colorCode:              #if a valid RGB assigned
            (r, g, b) = LED.get_color() #modify LED color
            if self.colorCode == "r":
                LED.set_color(red=0xFF, green=g, blue=b)
            elif self.colorCode == "g":
                LED.set_color(red=r, green=0xFF, blue=b)
            elif self.colorCode == "b":
                LED.set_color(red=r, green=g, blue=0xFF)

    def buttonUp(self, buttonPin):
        self.totalTime += (time.time() - self.downTimp) #increment total
time
        self.downTime = 0   #just paranoia
        if self.colorCode:  #if valid RGB, turn the element off
            if self.colorCode == "r":
                LED.set_color(red=0x00, green=g, blue=b)
            elif self.colorCode == "g":
                LED.set_color(red=r, green=0x00, blue=b)
            elif self.colorCode == "b":
                LED.set_color(red=r, green=g, blue=0x00)

def exit_handler():
    #   I don't have a reference to terminal escape codes, so
    #   I'm going to skip that part
    print "Red Team  :\t%s" % redButton.totalTime
    print "Green Team:\t%s" % greenButton.totalTime
    print "Blue Team :\t%s" % blueButton.totalTime
    flog = open("flag1.log", "a")
    flog.write("%s\n" % time.strftime("%H:%M:%S"))
    flog.write("Red Team  :\t%s\n" % redButton.totalTime)
    flog.write("Green Team:\t%s\n" % greenButton.totalTime)
    flog.write("Blue Team :\t%s\n\n" % blueButton.totalTime)
    flog.close()

    GPIO.cleanup()



if __name__ == "__main__":
    LED = bs.blinkstick().find_first()   #get LED object

    redButton = Button(22, LED, "r")    #create button objects
    greenButton = Button(23, LED, "g")
    blueButton = Button(24, LED, "b")

    atexit.register(exit_handler)       #register exit handler
    
    while True:
        time.sleep(0)   #loop forever

-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
    wlfraed@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

[toc] | [prev] | [next] | [standalone]


#95741

FromJohn McKenzie <davros@bellaliant.net>
Date2015-08-28 17:40 +0000
Message-ID<c21Ex.10369$wH.5878@fx10.iad>
In reply to#95514
 Thanks for the replies, everyone.

 Two of you suggested I ask in comp.sys.raspberry-pi. We leave in a world 
where people cannot tell you the difference between the world wide web 
and the Internet and tech support for my ISP once told me in response to 
mentioning that thei news server was not functioning properly that I 
should "try turning on cookies" and further suggested I speak to the 
"owner of usenet" for help. Because of this new world it never occured to 
me that a new newsgroup would have been created in the last five years. I 
expected to be laughed at if I asked about Raspberry Pi having a presence 
on usenet. So thank you both for suggesting it. I will absolutely move my 
question there then come back here for more straight forward pure Python 
stuff.


Dennis replied in detail and asked a question of me.

>	I don't see you doing anything with the LED...

 As I mentioned in my original post I intend to turn LED lights a 
different colour but for developmented purposes I anm replace the code 
for that with a print statement. LED variable was leftover from the 
original script and I forgot to delete that line when sharing the 
development version.

>What is "channel"?

 Channel is something that is in every GPIO library example, and I pretty 
sure it is literal, not a placeholder. If I replace it with channel 
numbers it gives more errors. Channel is in place in working script 
examples you can download.


>	timered is not declared "global", so will be considered local 
to><> the

 Rereading global variables info. Never understood why all variables 
aren't always global at all times in any language. Why would you not want 
the variable accessible whenever you wanted it? Maybe it is related to 
performance or something. Anyway, will look at the scopes of variables 
again and look at the code again.


>	You initialize "colour" to 1, and then loop until "colour" is NOT 
1 --

 I thought the existance of the other callbacks would be able to interupt 
it. Thanks for another point for me to look into and learn about.


>	You start an infinite loop, nothing below this point will be 
executed

 The start of the infinite sleep loop is nessecary to have the script go 
reiterate instead of run once in under a second and stop. Not saying this 
has to be the way to do it, just explaining why I did it. What I used was 
the example used in dozens and dozens of answers given online to solve 
that same problem when using RPI.GPIO.


>	The exit handler will not be defined...
>	Ugh... Please read up on Python string interpolation (or format 
method,
>depending on Python version)

 Not sure what you are saying about that part of the code because it is 
the one part of the code that works perfectly. I copied from a generic 
example to start with and added my own text and ANSI codes and in every 
test it does what it is supposed exactly as it is supposed to.


 In addition to wanting to say thanks for your comments, I would like to 
say thanks for your example pseudo-code. I appreciate it and will, like 
you warned, keep in mind you do not have a Pi.


 Thanks everyone who replied to my questions for that matter.

 Now that I finnally have some time to work on this weekend I will take 
all your comments in and look at the code suggestions provided. Thank you.

[toc] | [prev] | [next] | [standalone]


#95747

Fromhakugin.gin@gmail.com
Date2015-08-28 13:56 -0700
Message-ID<0d033e9c-3bfa-4abb-9d29-01ef67b44d5c@googlegroups.com>
In reply to#95741
On Friday, August 28, 2015 at 1:40:41 PM UTC-4, John McKenzie wrote:
> Thanks for the replies, everyone.
> 
>  Two of you suggested I ask in comp.sys.raspberry-pi. We leave in a world 
> where people cannot tell you the difference between the world wide web 
> and the Internet and tech support for my ISP once told me in response to 
> mentioning that thei news server was not functioning properly that I 
> should "try turning on cookies" and further suggested I speak to the 
> "owner of usenet" for help. Because of this new world it never occured to 
> me that a new newsgroup would have been created in the last five years. I 
> expected to be laughed at if I asked about Raspberry Pi having a presence 
> on usenet. So thank you both for suggesting it. I will absolutely move my 
> question there then come back here for more straight forward pure Python 
> stuff.
> 
> 
> Dennis replied in detail and asked a question of me.
> 
> >	I don't see you doing anything with the LED...
> 
>  As I mentioned in my original post I intend to turn LED lights a 
> different colour but for developmented purposes I anm replace the code 
> for that with a print statement. LED variable was leftover from the 
> original script and I forgot to delete that line when sharing the 
> development version.
> 
> >What is "channel"?
> 
>  Channel is something that is in every GPIO library example, and I pretty 
> sure it is literal, not a placeholder. If I replace it with channel 
> numbers it gives more errors. Channel is in place in working script 
> examples you can download.
> 
> 
> >	timered is not declared "global", so will be considered local 
> to><> the
> 
>  Rereading global variables info. Never understood why all variables 
> aren't always global at all times in any language. Why would you not want 
> the variable accessible whenever you wanted it? Maybe it is related to 
> performance or something. Anyway, will look at the scopes of variables 
> again and look at the code again.
> 
> 
> >	You initialize "colour" to 1, and then loop until "colour" is NOT 
> 1 --
> 
>  I thought the existance of the other callbacks would be able to interupt 
> it. Thanks for another point for me to look into and learn about.
> 
> 
> >	You start an infinite loop, nothing below this point will be 
> executed
> 
>  The start of the infinite sleep loop is nessecary to have the script go 
> reiterate instead of run once in under a second and stop. Not saying this 
> has to be the way to do it, just explaining why I did it. What I used was 
> the example used in dozens and dozens of answers given online to solve 
> that same problem when using RPI.GPIO.
> 
> 
> >	The exit handler will not be defined...
> >	Ugh... Please read up on Python string interpolation (or format 
> method,
> >depending on Python version)
> 
>  Not sure what you are saying about that part of the code because it is 
> the one part of the code that works perfectly. I copied from a generic 
> example to start with and added my own text and ANSI codes and in every 
> test it does what it is supposed exactly as it is supposed to.
> 
> 
>  In addition to wanting to say thanks for your comments, I would like to 
> say thanks for your example pseudo-code. I appreciate it and will, like 
> you warned, keep in mind you do not have a Pi.
> 
> 
>  Thanks everyone who replied to my questions for that matter.
> 
>  Now that I finnally have some time to work on this weekend I will take 
> all your comments in and look at the code suggestions provided. Thank you.

This issue is not directly related to the PI itself, it is from not having much experience with Python. While I do not have my RPI handy to test with give the following a try...

import atexit 
import time 
from blinkstick import blinkstick 
import RPi.GPIO as GPIO   

led = blinkstick.find_first() 
colour = 0
time_red = 0
time_yellow = 0
time_blue = 0
timestamp = time.strftime("%H:%M:%S")


GPIO.setmode(GPIO.BCM)
GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)


def red_button(channel):
    colour = 1
    print "Red Button Pressed"

def yellow_button(channel):
    colour = 2
    print "Yellow Button Pressed"

def blue_button(channel):
    colour = 3
    print "Blue Button Pressed"

while True:
    GPIO.add_event_detect(22, GPIO.RISING, callback=red_button, bouncetime=200)
    GPIO.add_event_detect(23, GPIO.RISING, callback=yellow_button, bouncetime=200)
    GPIO.add_event_detect(24, GPIO.RISING, callback=blue_button, bouncetime=200)
    if colour == 1:
        time_red += 1
    elif colour == 2:
        time_yellow += 1
    elif colour == 3:
        time_blue += 1


def exit_handler():
    print '\033[0;41;37mRed Team:\033[0m ', time_red
    print '\033[0;43;30mYellow Time:\033[0m ', time_yellow
    print '\033[0;44;37mBlue Time:\033[0m ', time_blue
    flog = open('flag1log.text', 'a')
    flog.write(timestamp + '\n' + 'Red Team: ' + str(time_red) + '\n' + 'Yellow Team: ' + str(time_yellow) + '\n' + 'Blue Team: ' + str(time_blue) + '\n')
    flog.close()
atexit.register(exit_handler)
GPIO.cleanup()


I largely left your code intact. First I changed the name of your variables to make them easier to read, obviously this can be changed back. Second, I moved your "timer code" from the functions and into the while loop. I admit, this could cause your "timer" variables to get fairly large, pretty quickly.

I strongly recommend looking up how to create a stop watch script and have each button start a timer when pressed, making sure to total your results for each colour when the next button is pressed. I apologize that I do not have the time to provide example code.

[toc] | [prev] | [next] | [standalone]


#95757

FromDennis Lee Bieber <wlfraed@ix.netcom.com>
Date2015-08-29 14:21 -0400
Message-ID<mailman.127.1440872531.11709.python-list@python.org>
In reply to#95741
On Fri, 28 Aug 2015 17:40:24 GMT, John McKenzie <davros@bellaliant.net>
declaimed the following:


>>What is "channel"?
>
> Channel is something that is in every GPIO library example, and I pretty 
>sure it is literal, not a placeholder. If I replace it with channel 
>numbers it gives more errors. Channel is in place in working script 
>examples you can download.
>
	I suspect it is likely the pin-# that was attached when setting up the
callback linkage. The purpose being to allow one callback to be used for
multiple connections.

>
>>	timered is not declared "global", so will be considered local 
>to><> the
>
> Rereading global variables info. Never understood why all variables 
>aren't always global at all times in any language. Why would you not want 
>the variable accessible whenever you wanted it? Maybe it is related to 
>performance or something. Anyway, will look at the scopes of variables 
>again and look at the code again.
>

	The only language the really had everything global was Kemeny&Kurtz
BASIC -- from 1968.

	Even FORTRAN (1958 or so) did not have globals. Every subprogram (the
meta term encompassing subroutines and functions -- though in Python they
are all functions) had its local name space, arguments passed in... And --
possibly "common blocks" (which were declared memory addresses with
variables mapped onto them -- and those variables did not have to match
between subprograms

subroutine A
integer I
integer j
common /aBlock/ i, j

...

subroutine B
complex c
common /aBlock/ c
...


	"aBlock" is a memory region. In "A", that memory region is defined as a
pair of (32-bit) integers. In "B", that same memory region is now being
looked at as a single complex number... And the bit-pattern of i and j are
being interpreted as the floating point real and imaginary parts.

	There are software engineering concepts of "coupling" and "cohesion".
In short, you want to minimize the coupling between parts of the program
(between functions) by limiting shared data to passed in arguments, and
passed out return values. By doing this, you can take that function -- with
no code changes -- and plug it into another program and just use it.
Cohesion tends to mean what is in the function is well linked to performing
just the needs of that function -- it isn't spread all over the place.
https://en.wikipedia.org/wiki/Coupling_%28computer_programming%29

>
>>	You initialize "colour" to 1, and then loop until "colour" is NOT 
>1 --
>
> I thought the existance of the other callbacks would be able to interupt 
>it. Thanks for another point for me to look into and learn about.
>
	Callbacks are not interrupts (and even if they were interrupts, they'd
be at the same level -- and interrupts at the same level do not interrupt
each other).

	Behind the scenes, the GPIO library probably created a task that just
loops checking the registered I/O pins for state changes. When it sees a
state change, it calls the callback function linked to it -- and waits for
the callback to return to it so it can continue with its check loop.
>
>>	You start an infinite loop, nothing below this point will be 
>executed
>
> The start of the infinite sleep loop is nessecary to have the script go 
>reiterate instead of run once in under a second and stop. Not saying this 
>has to be the way to do it, just explaining why I did it. What I used was 
>the example used in dozens and dozens of answers given online to solve 
>that same problem when using RPI.GPIO.
>
	The infinite loop is needed, yes... But it needs to be performed after
you've defined all the callbacks (and the exit handler IS a type of
callback -- it gets called when an exit condition is activated).

	Program layout should be something like

import whatever

def all_functions():

register_callback(...)

main_loop	#in a gui framework, this may something like
framework.mainloop()

clean_up


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
    wlfraed@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

[toc] | [prev] | [next] | [standalone]


#95792

FromJohn McKenzie <davros@bellaliant.net>
Date2015-08-31 17:41 +0000
Message-ID<yl0Fx.3282$Ot4.1918@fx05.iad>
In reply to#95411
 Dennis, Hakugin, I tried your scripts and had to alter a typo here or 
there, but once the basic errors disappeared I had the same error 
message. "Conflicting edge detection already enabled for this GPIO 
channel".

 As much as I despise web based bulletin board systems I registered on 
the Raspberry Pi website to ask for help as well.

 Appreciate the effort you both put in those scripts. Will keep working 
with them and the general points you made.

 Still checking here and am discussing all this in the Raspberry pi 
newsgroup. Thanks to the several people who mentioned it.

 Again, still listening here if anyone has any more to add.

[toc] | [prev] | [next] | [standalone]


#95795

Fromhakugin.gin@gmail.com
Date2015-08-31 11:25 -0700
Message-ID<4d2a9d2c-7bc3-4d18-a612-d15f0027fe05@googlegroups.com>
In reply to#95792
On Monday, August 31, 2015 at 1:42:16 PM UTC-4, John McKenzie wrote:
> Dennis, Hakugin, I tried your scripts and had to alter a typo here or 
> there, but once the basic errors disappeared I had the same error 
> message. "Conflicting edge detection already enabled for this GPIO 
> channel".
> 
>  As much as I despise web based bulletin board systems I registered on 
> the Raspberry Pi website to ask for help as well.
> 
>  Appreciate the effort you both put in those scripts. Will keep working 
> with them and the general points you made.
> 
>  Still checking here and am discussing all this in the Raspberry pi 
> newsgroup. Thanks to the several people who mentioned it.
> 
>  Again, still listening here if anyone has any more to add.

I apologize, I did make a mistake with the example I provided and I just realized it. Change the code block:

while True: 
    GPIO.add_event_detect(22, GPIO.RISING, callback=red_button, bouncetime=200) 
    GPIO.add_event_detect(23, GPIO.RISING, callback=yellow_button, bouncetime=200) 
    GPIO.add_event_detect(24, GPIO.RISING, callback=blue_button, bouncetime=200) 
    if colour == 1: 
        time_red += 1 
    elif colour == 2: 
        time_yellow += 1 
    elif colour == 3: 
        time_blue += 1 

to:

GPIO.add_event_detect(22, GPIO.RISING, callback=red_button, bouncetime=200) 
GPIO.add_event_detect(23, GPIO.RISING, callback=yellow_button, bouncetime=200) 
GPIO.add_event_detect(24, GPIO.RISING, callback=blue_button, bouncetime=200)

while True: 
    if colour == 1: 
        time_red += 1 
    elif colour == 2: 
        time_yellow += 1 
    elif colour == 3: 
        time_blue += 1


You are getting the error because the script is attempting to perform a "add_event_detect" on the same pins each time the "while" loop iterates. By moving it above the loop the error should stop occuring.

[toc] | [prev] | [next] | [standalone]


#95796

FromMRAB <python@mrabarnett.plus.com>
Date2015-08-31 19:34 +0100
Message-ID<mailman.18.1441046250.23514.python-list@python.org>
In reply to#95792
On 2015-08-31 18:41, John McKenzie wrote:
>
>   Dennis, Hakugin, I tried your scripts and had to alter a typo here or
> there, but once the basic errors disappeared I had the same error
> message. "Conflicting edge detection already enabled for this GPIO
> channel".
>
Are you still calling GPIO.add_event_detect in a while loop?

>   As much as I despise web based bulletin board systems I registered on
> the Raspberry Pi website to ask for help as well.
>
>   Appreciate the effort you both put in those scripts. Will keep working
> with them and the general points you made.
>
>   Still checking here and am discussing all this in the Raspberry pi
> newsgroup. Thanks to the several people who mentioned it.
>
>   Again, still listening here if anyone has any more to add.
>

[toc] | [prev] | [next] | [standalone]


#95825

FromJohannes Bauer <dfnsonfsduifb@gmx.de>
Date2015-09-01 10:58 +0200
Message-ID<ms3pc0$95u$1@news.albasani.net>
In reply to#95792
On 31.08.2015 19:41, John McKenzie wrote:

>  Still checking here and am discussing all this in the Raspberry pi 
> newsgroup. Thanks to the several people who mentioned it.
> 
>  Again, still listening here if anyone has any more to add.

I've had the problem to use interrupt-driven GPIOs on the Pi about two
years back. Here's how I solved it:

http://pastebin.com/gdJaJByU

To explain the message you're getting: If you want to handle GPIOs in
the most resource-efficient way, you use interrupt-driven handling.
Interrupts for GPIOs can be configured to be off, level-triggered or
edge-triggered. For edge-triggering I'm also pretty sure that the type
of edge (rising, falling, both) can be specified.

IIRC (and I might not, been quite some time), these interrupts are
bundled together in GPIO ports ("channels"). All GPIOs in one channel
need to have the same configuration. You cannot have conflicing
configuration between two pins which belong to the same GPIO (and
apparently, your framework is trying to do it).

The code I posted does it all by hand (and it's not really hard, as you
can see). I used input and output functionality and do the interrupt
configuration myself (this works through the /proc filesystem on the Pi).

Hope this helps,
Cheers,
Johannes

-- 
>> Wo hattest Du das Beben nochmal GENAU vorhergesagt?
> Zumindest nicht öffentlich!
Ah, der neueste und bis heute genialste Streich unsere großen
Kosmologen: Die Geheim-Vorhersage.
 - Karl Kaos über Rüdiger Thomas in dsa <hidbv3$om2$1@speranza.aioe.org>

[toc] | [prev] | [next] | [standalone]


#95797

FromTim Daneliuk <tundra@bogus-city.tundraware.com>
Date2015-08-31 14:07 -0500
Message-ID<e9lebc-nmi2.ln1@oceanview.tundraware.com>
In reply to#95411
On 08/16/2015 02:40 PM, John McKenzie wrote:
> 
>  Hello, all. I am hoping some people here are familiar with the RPi.GPIO 
> python module for the Raspberry Pi.


I am not familiar with the module, but I am quite familiar with dealing
with hardware interfacing, mostly in assembler.

One thing you need to ensure is that either the module or your
code implents software debounce.  When a button is pressed or switched moved,
there is mechanical bounce for a some period of time immediately thereafter.
In the time right after the switch/button is pressed, the mechanical closure
"bounces" between "on" and "off" for a little while, until it settles down
to the position you've selected.

The idea is to use the initial change of state to initiate the button handling logic but
wait until the switch/button settles down to it's final (and therefore, reliable) state. 

One algorithm to do this is to wait a fixed amount of time after the initial event - say,
100ms - before reading the switch.  The other way to do is to read the button/switch state
ever few milliseconds and only accept the input if it has not changed in, say,
5 measurements.

HTH,

[toc] | [prev] | [next] | [standalone]


#95819

FromDennis Lee Bieber <wlfraed@ix.netcom.com>
Date2015-09-01 02:08 -0400
Message-ID<mailman.36.1441087727.23514.python-list@python.org>
In reply to#95797
On Mon, 31 Aug 2015 14:07:58 -0500, Tim Daneliuk
<tundra@bogus-city.tundraware.com> declaimed the following:

>On 08/16/2015 02:40 PM, John McKenzie wrote:
>> 
>>  Hello, all. I am hoping some people here are familiar with the RPi.GPIO 
>> python module for the Raspberry Pi.
>
>
>I am not familiar with the module, but I am quite familiar with dealing
>with hardware interfacing, mostly in assembler.
>
>One thing you need to ensure is that either the module or your
>code implents software debounce.  When a button is pressed or switched moved,
>there is mechanical bounce for a some period of time immediately thereafter.
>In the time right after the switch/button is pressed, the mechanical closure
>"bounces" between "on" and "off" for a little while, until it settles down
>to the position you've selected.
>
	Since the OP's intent seems to be for accumulative time for each
button, debounce likely isn't needed. If it were triggering some
significant action (issuing a serial-numbered ticket, say), debounce would
be needed... 
-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
    wlfraed@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

[toc] | [prev] | [next] | [standalone]


#95888

FromJohn McKenzie <davros@bellaliant.net>
Date2015-09-02 18:50 +0000
Message-ID<0yHFx.3758$_H1.2845@fx23.iad>
In reply to#95411
 Hakugin: Thanks for the correction. Someone elsewhere showed me example 
code that was very close to yours, with that being the main difference. 
His gave an error message that red_button was undefined so I moved the 
code block below the callbacks. After that it ran without producing 
errors but it was unresponsive. Will try your updated version tomorrow 
and will keep fiddling with his.

 Thank you all for warning me about debouncing. The RPi.GPIO library has 
built in debouncing. You can even adjust the timing of it.

 Turns out I got one thing right. Someone who knows better than I 
explained that GPIO.Cleanup() does go at the bottom and outside the def 
exit_handler() code block like I had it originally.

 Johannes: Thanks for sharing that. I will take a look at it when I have 
more time. Must head to the hospital for my treatment in a few minutes.

>Are you still calling GPIO.add_event_detect in a while loop?

 MRAB, apparently yes. Hakugin noticed and update his example code.

[toc] | [prev] | [next] | [standalone]


#96208

FromJohn McKenzie <davros@bellaliant.net>
Date2015-09-09 19:03 +0000
Message-ID<In%Hx.2854$6l6.96@fx08.iad>
In reply to#95411
 Hello.

 As per the suggestion of two of you I went to the Raspberry Pi 
newsgroup. Dennis is also there and has been posting in response to my 
problems. Between there and the Raspberry Foundation website I discovered 
that my wiring did not match my code and changed all PUD_DOWN to PUD_UP 
and all GPIO.RISING to GPIO.FALLING because I was wired to the ground pin.

 Someone suggested code very close to what hakugin suggested.

 Right now I have response buttons that work, but the colour of the LED 
strip is not correct. It adds colours instead of changing to a new one. I 
hit red, it pulses red, I hit blue, it pulses red and blue, making purple.

 It appears now my problem is more about Python usage than anything else, 
so I am asking for help here as well as having already asked elsewhere.

 Tried using a go to black command (led.set_color(name="black")) and a 
turn off command (led.turn_off()) before the pulse command to reset the 
colour and these did not work. To see what would happen I removed the 
"while colour == 1:" (or == 2: or ==3:) line and it acted as expected. 
The LED pulsed once. However, it would pulse the correct colour, it would 
not add colours together.

 So the while loop seems to be the cause of my problem, but it is needed 
to keep the pulse repeating as far I can know. Maybe Python has another 
way to repeat the function.

 Here is the code I was working from:

import atexit 
import time 
from blinkstick import blinkstick 
import RPi.GPIO as GPIO   

led = blinkstick.find_first() 
colour = 0
time_red = 0
time_yellow = 0
time_blue = 0
timestamp = time.strftime("%H:%M:%S")

GPIO.setmode(GPIO.BCM)
GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)


def red_button(channel):
    led.set_color(name="black")
    colour = 1
    while colour == 1:
        led.pulse(red=255, green=0, blue=0, repeats=1, duration=3000, 
steps=50)

def yellow_button(channel):
    led.set_color(name="black")
    colour = 2
    while colour == 2:
        led.pulse(red=255, green=255, blue=0, repeats=1, duration=3000, 
steps=50)

def blue_button(channel):
    led.set_color(name="black")
    colour = 3
    while colour == 3:
        led.pulse(red=0, green=0, blue=255, repeats=1, duration=2000, 
steps=50)
    

GPIO.add_event_detect(22, GPIO.FALLING, callback=red_button, 
bouncetime=200)
GPIO.add_event_detect(23, GPIO.FALLING, callback=yellow_button, 
bouncetime=200)
GPIO.add_event_detect(24, GPIO.FALLING, callback=blue_button, 
bouncetime=200)


while True:
    if colour == 1:
        time_red += 1
    elif colour == 2:
        time_yellow += 1
    elif colour == 3:
        time_blue += 1
    time.sleep(0.1)


def exit_handler():
    print "\033[0;41;37mRed Team:\033[0m ", time_red
    print "\033[0;43;30mYellow Time:\033[0m ", time_yellow
    print "\033[0;44;37mBlue Time:\033[0m ", time_blue
    flog = open("flag1.log", "a")
    flog.write(timestamp + "\n" + "Red Team: " + str(time_red) + "\n" + 
"Yellow Team: " + str(time_yellow) + "\n" + "Blue Team: " + str
(time_blue) + "\n")
    flog.close()
    GPIO.cleanup()
atexit.register(exit_handler)


 Any advice about the while loop for the colour pulsing is appreciated.

[toc] | [prev] | [next] | [standalone]


#96216

FromMRAB <python@mrabarnett.plus.com>
Date2015-09-09 20:29 +0100
Message-ID<mailman.290.1441826971.8327.python-list@python.org>
In reply to#96208
On 2015-09-09 20:03, John McKenzie wrote:
>
>   Hello.
>
>   As per the suggestion of two of you I went to the Raspberry Pi
> newsgroup. Dennis is also there and has been posting in response to my
> problems. Between there and the Raspberry Foundation website I discovered
> that my wiring did not match my code and changed all PUD_DOWN to PUD_UP
> and all GPIO.RISING to GPIO.FALLING because I was wired to the ground pin.
>
>   Someone suggested code very close to what hakugin suggested.
>
>   Right now I have response buttons that work, but the colour of the LED
> strip is not correct. It adds colours instead of changing to a new one. I
> hit red, it pulses red, I hit blue, it pulses red and blue, making purple.
>
>   It appears now my problem is more about Python usage than anything else,
> so I am asking for help here as well as having already asked elsewhere.
>
>   Tried using a go to black command (led.set_color(name="black")) and a
> turn off command (led.turn_off()) before the pulse command to reset the
> colour and these did not work. To see what would happen I removed the
> "while colour == 1:" (or == 2: or ==3:) line and it acted as expected.
> The LED pulsed once. However, it would pulse the correct colour, it would
> not add colours together.
>
>   So the while loop seems to be the cause of my problem, but it is needed
> to keep the pulse repeating as far I can know. Maybe Python has another
> way to repeat the function.
>
>   Here is the code I was working from:
>
> import atexit
> import time
> from blinkstick import blinkstick
> import RPi.GPIO as GPIO
>
> led = blinkstick.find_first()
> colour = 0
> time_red = 0
> time_yellow = 0
> time_blue = 0
> timestamp = time.strftime("%H:%M:%S")
>
> GPIO.setmode(GPIO.BCM)
> GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_UP)
> GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
> GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)
>
>
> def red_button(channel):
>      led.set_color(name="black")
>      colour = 1
>      while colour == 1:
>          led.pulse(red=255, green=0, blue=0, repeats=1, duration=3000,
> steps=50)
>
> def yellow_button(channel):
>      led.set_color(name="black")
>      colour = 2
>      while colour == 2:
>          led.pulse(red=255, green=255, blue=0, repeats=1, duration=3000,
> steps=50)
>
> def blue_button(channel):
>      led.set_color(name="black")
>      colour = 3
>      while colour == 3:
>          led.pulse(red=0, green=0, blue=255, repeats=1, duration=2000,
> steps=50)
>
>
> GPIO.add_event_detect(22, GPIO.FALLING, callback=red_button,
> bouncetime=200)
> GPIO.add_event_detect(23, GPIO.FALLING, callback=yellow_button,
> bouncetime=200)
> GPIO.add_event_detect(24, GPIO.FALLING, callback=blue_button,
> bouncetime=200)
>
>
> while True:
>      if colour == 1:
>          time_red += 1
>      elif colour == 2:
>          time_yellow += 1
>      elif colour == 3:
>          time_blue += 1
>      time.sleep(0.1)
>
>
> def exit_handler():
>      print "\033[0;41;37mRed Team:\033[0m ", time_red
>      print "\033[0;43;30mYellow Time:\033[0m ", time_yellow
>      print "\033[0;44;37mBlue Time:\033[0m ", time_blue
>      flog = open("flag1.log", "a")
>      flog.write(timestamp + "\n" + "Red Team: " + str(time_red) + "\n" +
> "Yellow Team: " + str(time_yellow) + "\n" + "Blue Team: " + str
> (time_blue) + "\n")
>      flog.close()
>      GPIO.cleanup()
> atexit.register(exit_handler)
>
>
>   Any advice about the while loop for the colour pulsing is appreciated.
>
It's the same problem as before, and it has the same answer.

In red_button, yellow_button and blue_button, 'colour' is a local
variable. It's set to a value and that value is never changed in the
loop, so it loops forever.

You should declare 'colour' to be global in all 3 functions, e.g.:

def red_button(channel):
     global colour

[toc] | [prev] | [next] | [standalone]


#96267

FromJohn McKenzie <davros@bellaliant.net>
Date2015-09-10 15:56 +0000
Message-ID<MKhIx.9889$6l6.5720@fx08.iad>
In reply to#95411
 MRAB:

 Thanks for replying. I got so hyper focused on solving my hardware 
problems, and excited that I did, that I forgot details from previous 
comments. Thanks for your post.

 Off to make things global...

[toc] | [prev] | [next] | [standalone]


#96362

FromJohn McKenzie <davros@bellaliant.net>
Date2015-09-11 18:24 +0000
Message-ID<V%EIx.91820$zz6.84582@fx04.iad>
In reply to#96267
 Hello.

 Thanks to the help of people here and in other newsgroups I seem to have 
something working doing the basics. (Buttons work, colours light up 
appropriately.)

 When I followed MRAB's instructions and read about scopes of variables 
that solved my most recent problem, but it introduced a bug. I think I 
fixed the bug but after all my stupid mistakes and forgetfulness that 
seems too good to be true. I expect there is a better, more elegant, or 
more Pythonic way to do what I did so please feel free to share on the 
subject.

 I had a problem where if I pressed a button while the LEDs were already 
flashing the colour of that button it would block a new colour from 
starting when I pressed a new button. So if the LED strip was red and I 
pressed the red button again nothing would happen when I pressed the blue 
or yellow button. Similar problem for the other two buttons.

 So inside my callbacks I added this code:

   if colour == 1:
        pass
    elif colour == 2 or 3:
        colour = 1


 Now it seems OK from my limited testing.


 Here is the code that has buttons and colours working and includes my 
bug fix:


import atexit 
import time 
from blinkstick import blinkstick 
import RPi.GPIO as GPIO   

led = blinkstick.find_first() 
colour = 0
time_red = 0
time_yellow = 0
time_blue = 0
timestamp = time.strftime("%H:%M:%S")

GPIO.setmode(GPIO.BCM)
GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)


def red_button(channel):
    global colour
    if colour == 1:
        pass
    elif colour == 2 or 3:
        colour = 1
        while colour == 1:
            led.pulse(red=255, green=0, blue=0, repeats=1, duration=2000, 
steps=50)
def yellow_button(channel):
    global colour
    if colour == 2:
        pass
    elif colour == 1 or 3:
        colour = 2
        while colour == 2:
            led.pulse(red=255, green=96, blue=0, repeats=1, 
duration=2000, steps=50)
def blue_button(channel):
    global colour
    if colour == 3:
        pass
    elif colour == 1 or 2:
        colour = 3
        while colour == 3:
            led.pulse(red=0, green=0, blue=255, repeats=1, duration=2000, 
steps=50)


GPIO.add_event_detect(22, GPIO.FALLING, callback=red_button, 
bouncetime=200)
GPIO.add_event_detect(23, GPIO.FALLING, callback=yellow_button, 
bouncetime=200)
GPIO.add_event_detect(24, GPIO.FALLING, callback=blue_button, 
bouncetime=200)


while True:
    if colour == 1:
        time_red += 1
    elif colour == 2:
        time_yellow += 1
    elif colour == 3:
        time_blue += 1

    time.sleep(0.1)


def exit_handler():
    print "\033[0;41;37mRed Team:\033[0m ", time_red
    print "\033[0;43;30mYellow Time:\033[0m ", time_yellow
    print "\033[0;44;37mBlue Time:\033[0m ", time_blue
    flog = open("flag1.log", "a")
    flog.write(timestamp + "\n" + "Red Team: " + str(time_red) + "\n" + 
"Yellow Team: " + str(time_yellow) + "\n" + "Blue Team: " + str
(time_blue) + "\n")
    flog.close()
    led.set_color(name="black")
atexit.register(exit_handler)
GPIO.cleanup()



 I think I am OK GPIO wise now, although always happy to improve the code 
and in the long term I want to do so.

 Will start new threads for more straight forward Python questions like 
help with saving a log of the results, timing, etc.

 Thanks for your help, everyone.

[toc] | [prev] | [next] | [standalone]


Page 1 of 2  [1] 2  Next page →

Back to top | Article view | comp.lang.python


csiph-web