Jump to content
 
  • entries
    7
  • comments
    6
  • views
    11,213

5. Another way to drive an LED (or two)


DavidB-AU

885 views

An earlier tutorial showed one way of driving an LED, connecting the anode side to the 3.3V rail and the cathode side to GPIO. As mentioned, the default state of the GPIO output is HIGH (3.3V) to setting it LOW (0V) allows power to flow through the circuit. Alternatively, the anode of the LED can be connected to GPIO and the cathode to GND. This changes the way to drive it, HIGH (True) to turn on, LOW (False) to turn off.

blogentry-6959-0-33305000-1359252339.png

GPIO.output(x, False) to turn on, GPIO.output(x, True) to turn off.

 

blogentry-6959-0-81586300-1359252344.png

GPIO.output(x, True) to turn on, GPIO.output(x, False) to turn off.

 

Both options can be useful depending on the application. Here's how the second one looks on the board.

blogentry-6959-0-43871700-1359252844.jpg

 

Crate a new program called ledtest4.py and add the following:

import RPi.GPIO as GPIOimport timeGPIO.setup(18, GPIO.OUT)while 1:  # Turn LED on  GPIO.output(18, True)  time.sleep(1)  # Turn LED off  GPIO.output(18, False)  time.sleep(1)

 

Run as root and the LED will flash on and off until you hit CTRL-C to stop the program.

pi@raspberrypi ~$ sudo python ledtest4.py

Now let's see both in action. Here is the set up with the red LED powered from GPIO24 (pin 18) and the cathode connected to GND, and the green LED powered from 3.3V and the cathode connected to GPIO25 (pin 22).

blogentry-6959-0-38315700-1359253517.jpg

 

This means that setting True on both pins will turn the red LED on and the green LED off, and setting False on both pins will turn the red LED off and the green LED on. By saving the state in a variable you can output the same variable to both pins. After waiting for a second, you can change the state and run the loop again. The not command will change the state from whatever it is to whatever it is not, i.e. if the state is True it will change to False and vice versa. Because there is no separate 'on' and 'off' sequence, the program gets a bit simpler. Create a new program called ledtest5.py with the following:

import RPi.GPIO as GPIOimport timeGPIO.setup(18, GPIO.OUT)GPIO.setup(22, GPIO.OUT)# Set up the initial statestate = Truewhile 1:  GPIO.output(18, state)  GPIO.output(22, state)  time.sleep(1)  state = not state         # Change the state

 

Run as root.

pi@raspberrypi ~$ sudo python ledtest5.py

The two LEDs should now flash alternately with with somewhat simpler code.

 

blogentry-6959-0-90777200-1359254268.png

  • Like 1

0 Comments


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...