Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Inspiriert von
- BitBastelei #398 - Die "Magie" hinter PWM (analogWrite, Timer, Preload, etc)
- https://www.youtube.com/watch?v=nf8MB7FkRaI
- """
- import math
- from collections import namedtuple
- class Frequency:
- def __init__(self, value):
- self.value = value
- def __float__(self):
- return float(self.value)
- def __index__(self):
- return int(self.value)
- def __str__(self):
- units = ("Hz", "kHz", "MHz")
- value = self.value
- for unit in units:
- if value < 1000:
- break
- value /= 1000
- return f"{value:.3f} {unit}"
- def __repr__(self):
- return f"{self.__class__.__name__}({self.value})"
- def pwm_calc(freq, bits=8, board_freq=16_000_000):
- result = namedtuple(
- "Configuration",
- "board_freq scaled_freq prescaler count_bits count_start target_freq",
- )
- increments = 2 ** bits
- counter_max = increments - 1
- for prescaler in (2 ** n for n in range(11)):
- if (current_freq := board_freq / prescaler / increments) < freq:
- break
- # math.ceil aufrunden, math.floor abrunden
- offset = round(counter_max * current_freq / freq)
- resulting_freq = current_freq / offset * counter_max
- return result(
- Frequency(board_freq),
- Frequency(current_freq),
- prescaler,
- bits,
- counter_max - offset,
- Frequency(resulting_freq),
- )
- result = pwm_calc(420)
- print("Prescaler:", result.prescaler)
- print("Frequency:", result.target_freq)
- print("Counter-Start:", result.count_start)
- # Prescaler: 256
- # Frequency: 420.648 Hz
- # Counter-Start: 107
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement