Raspberry Analog Signal in Circuit 2 the Use of PWM
PWM is short for pulse width modulation. Where, “pulse" refers to the pulse signal, which is a digital signal sent out at periodic continuous on and off patterns by the microcontroller. Because the signal sent out by the transistor only has two states, on and off, the signal switches only between high level and low level. PWM pulse signal is mainly defined by three components: cycle, duty cycle and frequency.
As shown in the figure below, cycle (T) is the total time for a pulse signal to go through a high-level state (T1) and a low-level state (T2), that is, cycle (T) = T1 + T2. Duty cycle represents the ratio of the time when the signal is at a high level to the cycle in a cycle, so a duty cycle can be calculated as cycle (T) / T1.
Frequency represents the number of cycles per second (1000 Hz means 1000 cycles per second). The shorter the cycle, the higher the frequency.
The objective of pulse width modulation is to modulate the duty cycle of the pulse signal according to the demand without changing other parameters of the pulse signal, so as to disguise a digital signal as a constant voltage analog signal.
So how is pulse width modulation realized? Take controlling the brightness of LED as an example. When we input a PWM signal to the LED, the LED actually receives a digital signal that constantly switches between high level and low level. This digital signal makes the LED turn on and off constantly.
When the frequency of on and off is fast enough, that is, the frequency of PWM is high enough, this flashing of light will not be recognized by human eyes.
At this time, under the conditions of a constant cycle, we only need to change the ratio of the time when the LED is turned on relative to the time that it is turned off. Thus, by adjusting the duty cycle, we can then change the brightness of the LED.
You can better understand this concept by bringing in some numbers. If the LED is turned on in 0.5 ms and turned off in 0.5 ms within 1 ms, you will not notice the light flashing since the frequency is too fast. You will instead only observe the brightness of the light as reduced to half of its always-on state. On the other hand, when the light turned on in 0.1 ms and turned off in 0.9 ms in a 1 ms cycle, the light perceived by your eyes will be only one tenth of its original brightness.
To operate on the duty cycle, you need to use arithmetic operators.