rocketchef
Posts: 13
Joined: Wed Oct 15, 2014 12:02 pm

switching LEDs on and off

Wed Oct 15, 2014 12:10 pm

Hello,

I've used this script here:
http://www.henryleach.com/2013/05/contr ... ry-pi.html
to make an RGB LED cycle through colours. Because it uses PWM, you can't just switch the LED pins on and off and leave them.

I'd like to use the LED cycling through colours to indicate an on/off in my project (a separate python script).

So my question is this: how can the other script call this one to make it switch on and off? I don't know python well enough.

Thanks!

User avatar
B.Goode
Posts: 10356
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: switching LEDs on and off

Wed Oct 15, 2014 1:22 pm

rocketchef wrote:Because it uses PWM, you can't just switch the LED pins on and off and leave them.
Why not?
I'd like to use the LED cycling through colours to indicate an on/off in my project (a separate python script).

So my question is this: how can the other script call this one to make it switch on and off? I don't know python well enough.
Why do you need two scripts? Why not base your own project around this working one? (Or alternatively incorporate the functions of the example you have given in your own script.)

In artificial code, not true python, something like

if project_is_on:
cycle the colours
else: #implies project is off
stop colour cycling

rocketchef
Posts: 13
Joined: Wed Oct 15, 2014 12:02 pm

Re: switching LEDs on and off

Wed Oct 15, 2014 1:34 pm

ah, OK, that makes sense. The bit I still need clarification on is how to turn on the LED and have it interrupted by other events (e.g. project_off), but I presume I can use the except in the following code?

Code: Select all

 try:  
     
   while 1:  
     for i in range(0, 720, 5):  
       colour( PosSinWave(50, i, 0.5),  
           PosSinWave(50, i, 1),  
           PosSinWave(50, i, 2),  
           0.1 )  
       
 except KeyboardInterrupt:  
   pass  

User avatar
paddyg
Posts: 2541
Joined: Sat Jan 28, 2012 11:57 am
Location: UK

Re: switching LEDs on and off

Wed Oct 15, 2014 10:33 pm

The keyboard interrupt will stop the program. Assuming you have incorporated your other code into this script so that the variable project_on can be used as a switch for the lights:

Code: Select all

try:  
   i = 0
   while 1: 
     ######### code doing other things here, setting project_on to True or False
     if project_on:
       colour(PosSinWave(50, i, 0.5), 
           PosSinWave(50, i, 1), 
           PosSinWave(50, i, 2), 
           0.1 )
       i = (i + 5) % 720
     else:
       colour(0, 0, 0, 0.1) # could just sleep(0.1) as colour will have turned them off
 except KeyboardInterrupt: 
   pass  
Once you've got it all working you might want to look at putting the light control into a different thread but don't worry about that to start with.
also https://groups.google.com/forum/?hl=en-GB&fromgroups=#!forum/pi3d

Return to “Python”