LoginSignup
1
0

More than 3 years have passed since last update.

Raspberry Pi でPWM信号使ってLEDの明るさを変更する

Posted at

Raspberry Pi でPWM信号使ってLEDの明るさを変更する

PWM信号

周期的にオンとオフが切り替わる信号で、1波長の中でのオンの時間とオフの時間の割合を調整するで、
一連の流れの中での出力を変更できる信号

PWM.pngPWM2.png

Raspberry Pi とLEDを接続する

今回はたまたま家にあった赤色LEDをつかった。
電圧は Raspberry Pi からのPWMの3.3Vで足りるため、アノードにそのまま接続。
( 今回は18番のPINを使用 )
pi_GPIO_PWM.png
PWM_LED.png

PWMを出力するコードを書く

  • 以下のコードでは、10%の出力と100%の出力を約3秒ごとに2回繰り返す
import RPi.GPIO as GPIO
import time


def main():
    frequency = 200
    repeat_count = 600
    gpio_pin = 18

    GPIO.setmode(GPIO.BCM)
    GPIO.setup(gpio_pin, GPIO.OUT)

    for i in [10, 100, 10, 100]:
        if 0 == i:
            on_time = 0
            off_time = (1 / frequency)
        else:
            on_time = (1 / frequency) * (i / 100)
            off_time = (1 / frequency) * (1 - (i / 100))

        for rc in range(repeat_count):
            GPIO.output(gpio_pin, True)
            time.sleep(on_time)
            GPIO.output(gpio_pin, False)
            time.sleep(off_time)

    GPIO.cleanup()


if __name__ == '__main__':
    main()
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0