Advertisement
uwezi

AVR find PWM frequency settings

Aug 13th, 2022 (edited)
1,088
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | Software | 0 0
  1. '''
  2. This script analyzes a list of given quartz crystal frequencies for the
  3. possibility to create an 8-bit PWM signal with a given frequency f0
  4. within a a given tolerance on a typical microcontroller timer with given
  5. prescalers and a clear-on-timer-compare CTC functionality
  6.  
  7. Uwe Zimmermann, 2022
  8. '''
  9.  
  10. f0 = 7000
  11. tolerance = 2/100
  12.  
  13. xtals      = [1e6, 1.8432e6, 2e6, 3.2768e6, 3.575e6, 3.579545e6, 3.580e6, 3.6864e6,
  14.               4e6, 4.194304e6, 4.9152e6, 5e6, 6e6, 7.3728e6, 8e6, 9.216e6, 9.8304e6,
  15.               10e6, 10.245e6, 10.738635e6, 11.0592e6, 12e6, 12.5e6, 13.56e6, 14.31818e6,
  16.               14.7456e6, 15e6, 16e6, 17.73447e6, 18e6, 18.432e6, 18.8696e6, 19.6608e6,
  17.               20e6, 20.48e6, 21e6, 24e6, 24.576e6]
  18.  
  19. prescalers = [1,8,64,256,1024]
  20.  
  21. results = []
  22.  
  23. for p in prescalers:
  24.     for n in range(255):
  25.         xtal = f0 * p * n
  26.         for xt in xtals:
  27.             if abs(xtal - xt)/xt <= tolerance:
  28.                 f = xt/(p*n)
  29.                 df = (f-f0)/f0*100  # percent
  30.                 results.append((f, df, n, p, xt))
  31.                
  32. def get_df(item):
  33.     return abs(item[1])
  34.  
  35. if results:
  36.     results.sort(key=get_df)
  37.     for res in results:
  38.         print("prescaler ={:4d}  n={:4d}  xtal = {:7.4f} MHz  actual f = {:.3f}  Δf = {:+3.2f}%".format(res[3], res[2], res[4]/1e6, res[0], res[1]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement