Pulse Width Modulation (PWM) can be used to generate a digital square wave signal, that again can be used as kind of analog voltage, because the digital signal will be smoothed out either directly or through a low pass filter.
Using the analogWrite(pin, value) function you can set the duty cycle or percentage, the pin will be high, i.e. 3,3 V.
You can also change the number of bits used for generating the PWM signal using the analogWriteResolution(bits) function. By default the PWM is using 8 bits (0-255) resolution. but it can go up to 12 bits (0-4095) providing a finer resolution .
The default PWM frequency is 732 Hz originating from 48 MHz divided by a 16 bits prescaler (65535). You can also see the Arduino PWM tutorial for more information about the use of PWM.
Below is an example of eight PWM signals applied to pin D0 to D7, with the same duty cycle in pairs D0/D4, D1/D5, D2/D6 and D3/D7, but using different PWM resolutions, where D0 to D3 use 8 bits and D4 to D7 use 12 bits.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// RFzero include and object creation #include <RFzero.h> // MUST ALWAYS be included for RFzero void setup() { // Default PWM resolution is 8 bits analogWrite(0, 31); // Duty cycle = 31 / 255 = 12% analogWrite(1, 63); // Duty cycle = 63 / 255 = 25% analogWrite(2, 127); // Duty cycle = 127 / 255 = 50% analogWrite(3, 255); // Duty cycle = 255 / 255 = 100% analogWriteResolution(12); // Change the PWM resolution to 12 bits analogWrite(4, 511); // Duty cycle = 511 / 4095 = 12% analogWrite(5, 1023); // Duty cycle = 1023 / 4095 = 25% analogWrite(6, 2047); // Duty cycle = 2047 / 4095 = 50% analogWrite(7, 4095); // Duty cycle = 4095 / 4095 = 100% } void loop() { } |
If you want to use the above example on your Arduino Zero or Arduino M0 please note that the pins don’t match directly with the RFzero as the below table shows. But if you rename them accordingly and omit those that are not available the above example will work.
Pin | Arduino Zero pin name | Arduino M0 pin name |
---|---|---|
0 | 2 | 4 |
1 | 3 | 3 |
2 | 1 | 1 |
3 | 0 | 0 |
4 | Not available | Not available |
5 | Not available | Not available |
6 | 4 | 2 |
7 | 5 | 5 |
Instead of PWM you can also use the RFzero to make a real analog voltage by using the DAC output.