Function Pulse Width Modulation (PWM)

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/qq_23320955/article/details/79452748

Glossary

PWM is the abbreviation of Pulse Width Modulation, its Chinese name is pulse width modulation , which utilizes a microprocessor to perform the digital output of the analog control circuit, in fact, achieve the effect of a digital signal using an analog signal.

First, from the point of view of its name, pulse width modulation, the pulse width is changed to achieve different effects. Let's look at three different pulse signals shown in Figure 10-1.
PWM
Photos from the c language Chinese network

This is a period is 10ms, i.e., the frequency is 100Hz waveform, but each cycle, the high and low pulse width varies, which is the essence of the PWM. Here we have to remember a concept called "duty cycle." High duty cycle means a time period ratio of the total. For example a first portion of the duty cycle of the waveform is 40%, the second portion of the waveform duty cycle is 60%, the third portion of the waveform duty cycle of 80%, which is the PWM explanation.

If we continue to decrease this interval, is reduced to our eyes can not be seen, the frequency is 100Hz or more, this time a small lamp is manifested phenomenon while maintaining the bright state, but the brightness and no LED = 0; when the high brightness. That we continue to change the time parameter, so that LED = 0; the time is greater than or less than the LED = 1; time, you will find the brightness is different, this is the feeling of analog circuits, and is no longer a purely 0 and 1, and changing brightness.

Function explanation

1. RPI.GPIO module pulse width modulation (PWM) function

Create a PWM instance:

p = GPIO.PWM(channel, frequency)

Enable PWM:

p.start (dc) # dc representative of the duty ratio (range: 0.0 <= dc> = 100.0)

Change Frequency:

p.ChangeFrequency (freq) # freq for the new frequency set in Hz

Changing duty:

p.ChangeDutyCycle (dc) # range: 0.0 <= dc> = 100.0

Stop PWM:

p.stop()

注意,如果实例中的变量“p”超出范围,也会导致 PWM 停止。

The sample code

The following is an example that the once every two seconds flashing LED:

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)

p = GPIO.PWM(12, 0.5)
p.start(1)
input('点击回车停止:')   # 在 Python 2 中需要使用 raw_input
p.stop()
GPIO.cleanup()

The following is an example between the LED light / dark switching:

import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)

p = GPIO.PWM(12, 50)  # 通道为 12 频率为 50Hz
p.start(0)
try:
    while 1:
        for dc in range(0, 101, 5):
            p.ChangeDutyCycle(dc)
            time.sleep(0.1)
        for dc in range(100, -1, -5):
            p.ChangeDutyCycle(dc)
            time.sleep(0.1)
except KeyboardInterrupt:
    pass
p.stop()
GPIO.cleanup()

Guess you like

Origin blog.csdn.net/qq_23320955/article/details/79452748