Changing the brightness of an LED using the rpi_gpio gem
The following code was used to change the brightness of a red LED from dim, to 10% brightness, to 50% brightness, and then to full brightness.
require 'rpi_gpio' PIN_NUM = 4 PWM_FREQ = 100 RPi::GPIO.set_numbering :bcm RPi::GPIO.setup PIN_NUM, :as => :output pwm = RPi::GPIO::PWM.new(PIN_NUM, PWM_FREQ) sleep 5 pwm.start 0.0001 pwm.frequency = 40 # dim (0.125..1).step(0.06) do |x| pwm.duty_cycle = x sleep 0.01 end sleep 2 # up to 10% duty cycle (bright) (1..10).step(0.125) do |x| pwm.duty_cycle = x sleep 0.0075 end sleep 2 # up to 50% duty cycle (brighter) (10..50).step(0.125) do |x| pwm.duty_cycle = x sleep 0.0015 end sleep 2 # up to 100% duty cycle (brightest) (50..100).step(0.25) do |x| pwm.duty_cycle = x sleep 0.0015 end sleep 3 pwm.stop
Output:
Here's a short video of the LED as it changes brightness.
Resources
- rpi_gpio[github.com]