Saturday, May 7, 2016

How to turn LED dim and bright back again, using PWM On Raspberry Pi.

Code in Python:

Here I am using the Raspberry Pi Model B, connected to my Mac Laptop.
This was an experiment to try out using the PWM option available on the Raspberry.

The LEDs are connected to physical Pins 11

The white LED at one end is connected to Pin 11, ( i.e the GPIO17 ) , hence I'm using GPIO.BOARD in the python definition.

pi@raspberrypi~ $cat servo.py
import RPi.GPIO as GPIO # always needed with RPi.GPIO  
from time import sleep  # pull in the sleep function from time module  
 
GPIO.setmode(GPIO.BOARD)  # choose BCM or BOARD numbering schemes. I use BCM  
 
GPIO.setup(11, GPIO.OUT)# set GPIO 11 as output for white led  
 
white = GPIO.PWM(11, 100)    # create object white for PWM on port 11 at 100 Hertz  
 
white.start(0)              # start white led on 0 percent duty cycle (off)  
 
# now the fun starts, we'll vary the duty cycle to  
# dim/brighten the leds, so one is bright while the other is dim  
 
pause_time = 0.02           # you can change this to slow down/speed up  
 
try:  
    while True:  
        for i in range(0,101):      # 101 because it stops when it finishes 100  
            white.ChangeDutyCycle(i)  
            sleep(pause_time)  
        for i in range(100,-1,-1):      # from 100 to zero in steps of -1  
            white.ChangeDutyCycle(i)  
            sleep(pause_time)  
 
except KeyboardInterrupt:  
    white.stop()            # stop the white PWM output  
    GPIO.cleanup()          # clean up GPIO on CTRL+C exit

Thursday, May 5, 2016