0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RGBフルカラーLEDの色調整をソフトウェアPWM(pigpio)で実現する

Posted at

「カラー図解 最新 Raspberry Piで学ぶ電子工作」に載っている、ボリューム抵抗の値をADコンバータで読み取り、その値を元にPWMでRGBフルカラーLEDの色調整をやってみました。

Raspberry pi3書籍ではGPIO.PWMでPWM信号を出力していますが、精度が低いというのが気になって、高精度のソフトウェアPWMが利用できるpigpioを使う方法に変えてみました。pigpioのPWM出力精度についてはRPi.GPIO と pigpio のパルス幅の精度を測定を参照してください。

なお、書籍ではADコンバータの読み取りをGPIOの制御で実現していますが、こちらもspidevを使う方法に変えてあります。(前回の記事参照)

使用機材

  • Raspberry pi 3 model B+
  • 12bit 8ch ADコンバータ MCP3208
  • RGBフルカラーLED カソードコモン
  • ボリューム抵抗 10kΩ

配線図

image.png

仕組み

それぞれのボリューム抵抗を回すと、RGBフルカラーLEDをに送られるR,G,Bの信号のそれぞれのデューティ比が変化します。
この配線図では、次のように対応しています。

ボリューム抵抗(左) ボリューム抵抗(中) ボリューム抵抗(右)
ADコンバータの入力Ch Ch0 Ch1 Ch2
制御するGPIO GPIO 25 GPIO 24 GPIO 23
RGBとの対応 Blue Green Red

Pythonコード

pigpioを使う場合の約束として、最初にsudo pigpiodを行う必要があります。

# -*- coding: utf-8 -*-
import pigpio
import time
import spidev

LED_PIN = [25,24,23]
FREQ = 50
RANGE = 255

pi = pigpio.pi()


# MCP3208からSPI通信で12ビットのデジタル値を取得。0から7の8チャンネル使用可
def readadc_spidev(adcnum):
    if ((adcnum > 7) or (adcnum < 0)):
        return -1
    command1 = 0x6 | (adcnum & 0x4)>>2
    command2 = (adcnum & 0x3)<<6
    ret=spi.xfer2([command1,command2,0])
    adcout = (ret[1]&0xf)<<8 | ret[2]
    return adcout



spi=spidev.SpiDev()
spi.open(0, 0) # bus0, CE0
spi.max_speed_hz = 1000000 # 1MHz

for j in range(3):
    pi.set_mode(LED_PIN[j], pigpio.OUTPUT)  #pigpioで制御するピンの指定
    pi.set_PWM_frequency(LED_PIN[j], FREQ)  #PWMの周波数(Hz)を指定。デフォルトは800。
    pi.set_PWM_range(LED_PIN[j], RANGE)  #PWM値(μs)の最大値を指定。指定可能な値は25〜40000。デフォルトは255。


inputVal = [0,0,0]
inputDuty = [0,0,0]

try:
    while True:
        for i in range(3):
            inputVal[i] = readadc_spidev(i)
            inputDuty[i] = inputVal[i]*100/4095
            print(inputDuty)
            pi.set_PWM_dutycycle(LED_PIN[i], inputDuty[i]*2.55) #デューティー比変更
        time.sleep(0.5)

except KeyboardInterrupt:
    pass

spi.close()
pi.stop()


pigpioを使ったPWMは簡単で使いやすいので気に入ってます。

参考

Raspberry PiのGPIO制御の決定版 pigpio を試す
Raspberry PiのハードウェアPWMをpigpioで出力する
Raspberry Pi 3 pigpioを使ってLチカ PWMパラメータ確認編

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?