dott_ing
Posts: 6
Joined: Fri Dec 11, 2015 8:36 am

Blink LEDs python

Fri Dec 11, 2015 8:52 am

Hello, I have a problem that I can not find solution. I have to turn on the LEDs, with the GPIO interface, simultaneously but with different flashing frequencies using a python script. How can I do? Thank you all for answers

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Blink LEDs python

Fri Dec 11, 2015 9:14 am

What have you tried so far? You'll learn more if we help you with your own code rather than just give you an answer.

Is this a homework exercise?
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

Massi
Posts: 1691
Joined: Fri May 02, 2014 1:52 pm
Location: Italy

Re: Blink LEDs python

Fri Dec 11, 2015 9:21 am

dott_ing wrote:Hello, I have a problem that I can not find solution. I have to turn on the LEDs, with the GPIO interface, simultaneously but with different flashing frequencies using a python script. How can I do? Thank you all for answers
just to make it a little more interesting, i'd go with pigpio's waves.
afaik you can create different waves on different gpios (eventually chain them or repeat them if you need) and then start all of them together.
This would be nice :)

dott_ing
Posts: 6
Joined: Fri Dec 11, 2015 8:36 am

Re: Blink LEDs python

Fri Dec 11, 2015 9:35 am

elParaguayo wrote:What have you tried so far? You'll learn more if we help you with your own code rather than just give you an answer.

Is this a homework exercise?
It is for a personal project. The code I wrote only achieves a turn on the LEDs sequentially and not simultaneously.

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Blink LEDs python

Fri Dec 11, 2015 9:58 am

There are a few ways of doing it. Massi's suggested one which I've never used.

Other ideas could be:
  • Use the modulo operator to check whether a counter is a multiple of your desired interval (e.g. if you've got two LEDs, one flashes every 5 intervals and the other every 3 then you use the modulo operator on the counter and, when this equals zero, change the state of the LED).
  • Set up a separate thread for each LED. This may be overkill if you're new to python.
Why don't you post your code and we'll give you some pointers.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

Massi
Posts: 1691
Joined: Fri May 02, 2014 1:52 pm
Location: Italy

Re: Blink LEDs python

Fri Dec 11, 2015 10:08 am

elParaguayo wrote:There are a few ways of doing it. Massi's suggested one which I've never used.
me too
that's why i'd use it :) (*)
  • Use the modulo operator to check whether a counter is a multiple of your desired interval (e.g. if you've got two LEDs, one flashes every 5 intervals and the other every 3 then you use the modulo operator on the counter and, when this equals zero, change the state of the LED).
Yes, but:
- a common period can be difficult if he has many leds
- cpu wasting if you need to have a good precision
- in every case, it will not be very precise, since if you have to toggle more leds together you need to do that sequentially
[*]Set up a separate thread for each LED. This may be overkill if you're new to python.[/list]
Probably this is the correct way.

I think this is even far easier that build up waves :)


(*) i admit now i'm waiting for joan to join the topic and do his magic with some code :)

User avatar
RST8
Posts: 64
Joined: Tue Nov 25, 2014 1:57 pm

Re: Blink LEDs python

Fri Dec 11, 2015 10:12 am

dott_ing wrote:
elParaguayo wrote:What have you tried so far? You'll learn more if we help you with your own code rather than just give you an answer.

Is this a homework exercise?
It is for a personal project. The code I wrote only achieves a turn on the LEDs sequentially and not simultaneously.
There are a number of ways to do it, but how about running each LED on a different thread ?
You'd need to do some clean up to stop things and replace the print with your GPIO code, but this might be one approach:

Code: Select all

import threading
import time
class FlashLed(threading.Thread):

    def __init__(self, id,pauseTime):
        threading.Thread.__init__(self)
        self.pauseTime = pauseTime
        self .id = id

    def run (self):
        while True:
            print self.id, "On"
            print
            time.sleep(self.pauseTime)
            print self.id, "Off"
            print

for j in range (1,4):
    pauseTime = j*1.5
    led = FlashLed(str(j),pauseTime)
    led.daemon
    led.start()

time.sleep(30)

Joe

dott_ing
Posts: 6
Joined: Fri Dec 11, 2015 8:36 am

Re: Blink LEDs python

Fri Dec 11, 2015 10:23 am

This is my code:

Code: Select all

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)


def activateLED(pin,delay):
  GPIO.output(pin, GPIO.HIGH)
  time.sleep(delay)
  GPIO.output(pin, GPIO.LOW)
  time.sleep(delay)
  return;

while(1):
    activateLED(7,1)
    activateLED(11,2)
    activateLED(13,3)
    activateLED(15,4)

GPIO.cleanup()
How could I change to turn on 4 LEDs simultaneously?

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Blink LEDs python

Fri Dec 11, 2015 10:27 am

Massi wrote:
elParaguayo wrote:
  • Use the modulo operator to check whether a counter is a multiple of your desired interval (e.g. if you've got two LEDs, one flashes every 5 intervals and the other every 3 then you use the modulo operator on the counter and, when this equals zero, change the state of the LED).
Yes, but:
- a common period can be difficult if he has many leds
- cpu wasting if you need to have a good precision
- in every case, it will not be very precise, since if you have to toggle more leds together you need to do that sequentially
Indeed. I wouldn't say it's perfect but, for a beginner it may be easier than threads and introduces some good basic skills.

If it was just two LEDs, you could do something like this:

Code: Select all

from time import sleep

int_a = 5  ## First interval
int_b = 3  ## Second interval

state_a = True  # Start with LED on
state_b = True  # Start with LED on

for x in range(100):
    print ("LED A: {}\tLED B: {}".format(state_a, state_b))
    
    # Use the modulus function to check if x is a multiple of our
    # deisred intervals. If it is, invert the state.
    if not x % int_a:
        state_a = not state_a
        
    if not x % int_b:
        state_b = not state_b
        
    sleep(0.05)
This should show LED A having a period of 5 and LED B a period of 3.

But I agree, the code would get unwieldy the more LEDs you wanted to add and the common period gets harder. If it were me, I'd go down the thread route, but I just wanted to put some options out there.
(*) i admit now i'm waiting for joan to join the topic and do his magic with some code :)
Me too.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Blink LEDs python

Fri Dec 11, 2015 10:29 am

RST8 wrote:

Code: Select all

import threading
import time
class FlashLed(threading.Thread):

    def __init__(self, id,pauseTime):
        threading.Thread.__init__(self)
        self.pauseTime = pauseTime
        self .id = id

    def run (self):
        while True:
            print self.id, "On"
            print
            time.sleep(self.pauseTime)
            print self.id, "Off"
            print

for j in range (1,4):
    pauseTime = j*1.5
    led = FlashLed(str(j),pauseTime)
    led.daemon
    led.start()

time.sleep(30)

Joe
I think you may need

Code: Select all

led.daemon = True
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

User avatar
RST8
Posts: 64
Joined: Tue Nov 25, 2014 1:57 pm

Re: Blink LEDs python

Fri Dec 11, 2015 10:48 am

elParaguayo wrote:
RST8 wrote:

Code: Select all

import threading
import time
class FlashLed(threading.Thread):

    def __init__(self, id,pauseTime):
        threading.Thread.__init__(self)
        self.pauseTime = pauseTime
        self .id = id

    def run (self):
        while True:
            print self.id, "On"
            print
            time.sleep(self.pauseTime)
            print self.id, "Off"
            print

for j in range (1,4):
    pauseTime = j*1.5
    led = FlashLed(str(j),pauseTime)
    led.daemon
    led.start()

time.sleep(30)

Joe
I think you may need

Code: Select all

led.daemon = True
Possibly, depending on when you want to exit and how you clean up the threads. Perhaps doing the while True wasn't the best example in this case, but just enough code to get going.

Joe

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Blink LEDs python

Fri Dec 11, 2015 11:07 am

What I meant was, doing "led.daemon" does nothing in your code. "daemon" is a property of the thread so your line is just retrieving that value rather than setting it.

The two ways (that I know of) to daemonise the thread are:

Code: Select all

led.daemon = True
# or
led.setDaemon(True)
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

dott_ing
Posts: 6
Joined: Fri Dec 11, 2015 8:36 am

Re: Blink LEDs python

Fri Dec 11, 2015 11:13 am

can anyone help me to modify the code I posted above? Thank you all

User avatar
RST8
Posts: 64
Joined: Tue Nov 25, 2014 1:57 pm

Re: Blink LEDs python

Fri Dec 11, 2015 11:50 am

elParaguayo wrote:What I meant was, doing "led.daemon" does nothing in your code. "daemon" is a property of the thread so your line is just retrieving that value rather than setting it.

The two ways (that I know of) to daemonise the thread are:

Code: Select all

led.daemon = True
# or
led.setDaemon(True)
Fair point, always good to have a code review before submission:-)

Joe

dott_ing
Posts: 6
Joined: Fri Dec 11, 2015 8:36 am

Re: Blink LEDs python

Fri Dec 11, 2015 12:54 pm

elParaguayo wrote:There are a few ways of doing it. Massi's suggested one which I've never used.

Other ideas could be:
  • Use the modulo operator to check whether a counter is a multiple of your desired interval (e.g. if you've got two LEDs, one flashes every 5 intervals and the other every 3 then you use the modulo operator on the counter and, when this equals zero, change the state of the LED).
  • Set up a separate thread for each LED. This may be overkill if you're new to python.
Why don't you post your code and we'll give you some pointers.
I can not change my code. I wanted to put an LED in thread. And then start 4 threads simultaneously. How can I do?

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Blink LEDs python

Fri Dec 11, 2015 12:59 pm

I don't like doing this as I'd much rather see you try to adapt your code. But try this...

Code: Select all

import threading
import time

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)

# This is a list in the form (pin number, delay)
LEDS = [(7, 1), (11, 2), (13, 3), (15,4)]


class FlashLed(threading.Thread):

    def __init__(self, pin, pauseTime):
        threading.Thread.__init__(self)
        self.pauseTime = pauseTime
        self.pin = pin
        GPIO.setup(self.pin, GPIO.OUT)

    def run (self):
        while True:
            GPIO.output(self.pin, GPIO.HIGH)
            time.sleep(self.pauseTime)
            GPIO.output(self.pin, GPIO.LOW)
            time.sleep(self.pauseTime)


for pin, delay in LEDS:
    led = FlashLed(pin, delay)
    led.daemon = True
    led.start()

try:
    while True:
        time.sleep(1)
    
except KeyboardInterrupt:
    print "User pressed ctrl+c"
        
finally:
    GPIO.cleanup()
I can't test it so there may be typos.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

dott_ing
Posts: 6
Joined: Fri Dec 11, 2015 8:36 am

Re: Blink LEDs python

Fri Dec 11, 2015 1:26 pm

elParaguayo wrote:I don't like doing this as I'd much rather see you try to adapt your code. But try this...

Code: Select all

import threading
import time

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)

# This is a list in the form (pin number, delay)
LEDS = [(7, 1), (11, 2), (13, 3), (15,4)]


class FlashLed(threading.Thread):

    def __init__(self, pin, pauseTime):
        threading.Thread.__init__(self)
        self.pauseTime = pauseTime
        self.pin = pin
        GPIO.setup(self.pin, GPIO.OUT)

    def run (self):
        while True:
            GPIO.output(self.pin, GPIO.HIGH)
            time.sleep(self.pauseTime)
            GPIO.output(self.pin, GPIO.LOW)
            time.sleep(self.pauseTime)


for pin, delay in LEDS:
    led = FlashLed(pin, delay)
    led.daemon = True
    led.start()

try:
    while True:
        time.sleep(1)
    
except KeyboardInterrupt:
    print "User pressed ctrl+c"
        
finally:
    GPIO.cleanup()
I can't test it so there may be typos.
Thank you very much. Now I try and let you know.

gordon77
Posts: 5036
Joined: Sun Aug 05, 2012 3:12 pm

Re: Blink LEDs python

Fri Dec 11, 2015 2:01 pm

Here's a program l did a while ago it may give you some ideas

Code: Select all

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(25,GPIO.OUT)
GPIO.setup(24,GPIO.OUT)
GPIO.setup(23,GPIO.IN)

# set timings
t1h = 5
t1l = 1
t2 = 1.5
t3 = 1
t4 = .5
t5 = 1
t6 = .5
t7 = 1

led25 = False
start = 0

print "  Press Ctrl & C to Quit"


def time25(led25,t1h,t1l,start):
   if (led25 == True and time.time() - start > t1h) or (led25 == False and time.time() - start > t1l):
      if led25 == True:
         led25 = False
      else:
         led25 = True
      GPIO.output(25, led25)
      start = time.time()
   return (led25,start)

def time24(th,tl,led25,t1h,t1l,start):
   GPIO.output(24, True)
   now = time.time()
   while time.time() - now < th:
      led25,start = time25(led25,t1h,t1l,start)
   GPIO.output(24, False)
   now = time.time()
   while time.time() - now < tl:
      led25,start = time25(led25,t1h,t1l,start)
   return(led25,start)

try:
   while True:
      led25,start = time25(led25,t1h,t1l,start)
      if GPIO.input(23)== False:
         led25,start = time24(t2,t3,led25,t1h,t1l,start)
         led25,start = time24(t4,t5,led25,t1h,t1l,start)
         led25,start = time24(t6,t7,led25,t1h,t1l,start)

          
except KeyboardInterrupt:
  print "  Quit"
  GPIO.cleanup() 

bentejuy
Posts: 25
Joined: Thu Nov 26, 2015 1:25 pm
Location: Canary Islands, Spain
Contact: Website

Re: Blink LEDs python

Sat Dec 12, 2015 12:03 am

I'm developing a module that can simulate this effect or other effects more complex easily, but first you need have installed the raspybot module.

This is an example:

Code: Select all

import time

from raspybot.devices.logic import Blinker
from raspybot.io.interface import InterfaceManager, InterfaceGPIO


# This function is a callback of the "Blinker" object and receives two 
# parameters each time the value must change. Each bit of the value 
# represents a channel, you can change the state of a channel simply 
# changed the value at the bit level.

def do_effect(value, count):
	result = 0
	
	result |= 0b0001 if count % 2 else 0
	result |= 0b0010 if count % 3 else 0
	result |= 0b0100 if count % 5 else 0
	result |= 0b1000 if count % 7 else 0
	
	return result
	
manager = InterfaceManager()											# Initializes the interfaces manager
iface = InterfaceGPIO(manager, pinout=(19, 16, 26, 20))					# Defines the GPIO output channels

try:
	# Create and associate the "Blinker" object with the interface and its channels

	blinker = Blinker(iface, delay=.5, initial=0, checker=do_effect)	
	blinker.start()
	
	while True:
		time.sleep(1)

except KeyboardInterrupt:
	pass

finally:
	manager.delete(iface)
	manager.cleanup()
On this page you can see more example how it works : http://raspybot.com/articles/2015/04/09 ... art-i.html

Cheers!.

Return to “Python”