2

I've been tinkering around with a Raspberry Pi 2. I was working on a bike light project where I had to 'Pulse' all LEDs at the same time. I managed to get it done and working but, I struggled over the weekend to figure it out and when I did, the difference was (i) using GPIO.HIGH instead of True (or 1) in the GPIO.output method (ii) an extra sleep(0.1) after pulseOff() and (iii) using a 'while' instead of a 'for'. When I tried debugging the original code, the program always got stuck at the end of pulseOn() in the for loop and never went further.

The code before (original) the issue:

import RPi.GPIO as GPIO
from time import sleep

# Sets any warnings off
GPIO.setwarnings(False)

def channelOn():
    # to use Raspberry Pi board pin numbers
    GPIO.setmode(GPIO.BCM)
    for x in range(16, 24):
        # Setting to output
        GPIO.setup(x, GPIO.OUT)    

def pulseOn():    
    # Settings LED pins to outputs and switch ON
    for x in range(16, 24):
        GPIO.output(x, True)

def pulseOff():
    for x in range(16, 24):
        GPIO.output(x, False)


# Pulse i times
channelOn()
for i in range(0, 10):
    pulseOn()
    sleep(0.1)
    pulseOff()

The code after resolving the issue:

import RPi.GPIO as GPIO
from time import sleep

# Sets any warnings off
GPIO.setwarnings(False)

def channelOn():
    # to use Raspberry Pi board pin numbers
    GPIO.setmode(GPIO.BCM)
    for x in range(16, 24):
        # Setting to output
        GPIO.setup(x, GPIO.OUT)    

def pulseOn():    
    # Settings LED pins to outputs and switch ON
    for x in range(16, 24):
        GPIO.output(x, GPIO.HIGH)


def pulseOff():
    for x in range(16, 24):
        GPIO.output(x, GPIO.LOW)


# Pulse i times
channelOn()
while True:
    pulseOn()
    sleep(0.1)
    pulseOff()
    sleep(0.1)

My questions are:

  1. Is there a difference in using GPIO.HIGH/LOW versus True/False (1/0)?
  2. Or is it my looping choice?
  3. And why (for those more experienced than myself)?

Thanks in advance.

  • Is the first example missing a sleep statement at the end of the loop? Without that, it might appear to always be on as the 'off' step is nearly immediately reverted. – tobyd Mar 22 '17 at 21:23
3

All the Pi's GPIO are digital. They are either on (high, true, 1, on) or off (low, false, 0, off). It makes no difference which synonym you use provided that the library accepts the term.

for i in range(0, 10):
    pulseOn()
    sleep(0.1)
    pulseOff()

There is no delay between pulseOff() and the pulseOn().

It might be clearer if you write it without the for.

pulseOn()
sleep(0.1)
pulseOff()
pulseOn()
sleep(0.1)
pulseOff()
pulseOn()
sleep(0.1)
pulseOff()
pulseOn()
sleep(0.1)
pulseOff()
...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.