Skip to content

Commit

Permalink
PWM.rst: Use a power-of-2 constants.
Browse files Browse the repository at this point in the history
Signed-off-by: IhorNehrutsa <[email protected]>
  • Loading branch information
IhorNehrutsa committed Jan 17, 2025
1 parent b953bc0 commit db2ef98
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 10 deletions.
10 changes: 5 additions & 5 deletions docs/esp32/tutorial/pwm.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ low all of the time.
from machine import Pin, PWM
try:
F = 10000 # Hz
D = 2**16 // 16 # 6.25%
D = 65536 // 16 # 6.25%
pins = (2, 4, 12, 13, 14, 15, 16, 18, 19, 22, 23, 25, 26, 27, 32, 33)
pwms = []
for i, pin in enumerate(pins):
f = F * (i // 2 + 1)
d = min(2**16 - 1, D * (i + 1))
d = min(65535, D * (i + 1))
pwms.append(PWM(pin, freq=f, duty_u16=d))
sleep(2/f)
print(pwms[i])
Expand Down Expand Up @@ -111,7 +111,7 @@ low all of the time.
from time import sleep
from machine import Pin, PWM

DUTY_MAX = 2**16 - 1
DUTY_MAX = 65535

duty_u16 = 0
delta_d = 256
Expand Down Expand Up @@ -172,10 +172,10 @@ low all of the time.
from machine import Pin, PWM

try:
DUTY_MAX = 2**16 - 1
DUTY_MAX = 65535

duty_u16 = 0
delta_d = 2**16 // 32
delta_d = 65536 // 32

pwm = PWM(Pin(27))
pwmi = PWM(Pin(32), invert=1)
Expand Down
10 changes: 5 additions & 5 deletions docs/library/machine.PWM.rst
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ Constructors
Setting *freq* may affect other PWM objects if the objects share the same
underlying PWM generator (this is hardware specific).
Only one of *duty_u16* and *duty_ns* should be specified at a time.
*invert* is available at RP2, i.MXRT, SAMD, nRF, ESP32 ports.
*invert* is available only on the RP2, i.MXRT, SAMD, nRF, ESP32 ports.

Methods
-------
Expand Down Expand Up @@ -76,10 +76,10 @@ Methods
Use functions like these to convert percentages to u16 and back::

def percents_to_u16(percents:int)->int:
return (percents * 2**16 + 50) // 100
return (percents * 65535 + 50) // 100

def u16_to_percents(u16:int)->int:
return (u16 * 100 + 2**15) // 2**16
return (u16 * 100 + 32767) // 65535

.. method:: PWM.duty_ns([value])

Expand Down Expand Up @@ -124,10 +124,10 @@ Limitations of PWM
resolution of 8 bit, not 16-bit as may be expected. In this case, the lowest
8 bits of *duty_u16* are insignificant. So::

pwm=PWM(Pin(13), freq=300_000, duty_u16=2**16//2)
pwm=PWM(Pin(13), freq=300_000, duty_u16=65536//2)

and::

pwm=PWM(Pin(13), freq=300_000, duty_u16=2**16//2 + 255)
pwm=PWM(Pin(13), freq=300_000, duty_u16=65536//2 + 255)

will generate PWM with the same 50% duty cycle.

0 comments on commit db2ef98

Please sign in to comment.