【編集中】HardwareなPWM と SoftwareなPWM


Hardware PWM (WiringPi2 for Python)


編集中
import wiringpi2 as pi

brightness = 0

pi.wiringPiSetupGpio()
pi.pinMode(18, 2)    # 18:GPIO18 2:PWM_OUTPUT
pi.pwmWrite(18, 500) # 0 - 1023



Software PWM (WiringPi2 for Python)

参考 https://github.com/Gadgetoid/WiringPi2-Python/blob/master/examples/softpwm.py


import wiringpi2 as pi

brightness = 0

pi.wiringPiSetupGpio()
pi.pinMode(23, 1) # 23:GPIO23
pi.softPwmCreate(23, brightness, 100)

try:
        while True:
                print brightness
                pi.softPwmWrite(23, brightness) # Change PWM duty cycle
                pi.delay(100) # 0.2 seconds
                brightness += 1
                if brightness > 60:
                        brightness = 0

except KeyboardInterrupt:
        p.stop()
        GPIO.cleanup()


Software PWM (RPi)


import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)
GPIO.setup(16, GPIO.OUT) # 16:GPIO23

freq = 50
brightness = 0
t = 1

p = GPIO.PWM(16, freq) # 16:GPIO23
p.start(brightness)

try:
        while True:
                p.ChangeDutyCycle(brightness)
                print('PERCENT:', brightness)
                time.sleep(0.1)
                brightness = brightness + (5 * t)
                if (brightness > 60):
                        brightness = 60
                        t = -1
                elif (brightness < 10):
                        brightness = 10
                        t = 1

except KeyboardInterrupt:
        p.stop()
        GPIO.cleanup()

Written on February 7, 2015