#!/usr/bin/env python
#
# pwm_sinewave
#
# Calculate values for generate a PWM table for a Sinewave
# Used on a AVR ATMEGA 328
#
# 2023-07-10    tom@dl7bj.de	Tom, DL7BJ
#
import sys 
import matplotlib.pyplot as plot
from math import pi, sin, cos, asin, acos

pwmbit = 63 
zerobeat = 0
peaktopeak = 254

def compute_sinewave(pwmbit, fpeaktopeak, zerobeat):
    t = 0
    ul = []
    tl = []
    l = 0
    while t <= pwmbit:
        u = sin(2*pi*t/pwmbit)
        u = u * fpeaktopeak/2
        u = u + zerobeat
        u = int(round(u))
        if t < pwmbit:
            print(format(u,'#04x'),',',sep='',end='')
        else:
            print(format(u,'#04x'),' ',sep='',end='')
        l = l + 1
        if l == 16: 
            print(' // ', t + 1) 
            l = 0
        ul.append(u)
        tl.append(t)
        t = t + 1
    return ul,tl

print("Zerobeat on PWM step ", zerobeat)
print("Peak to peak on PWM  ", peaktopeak)
print("const unsigned char sinewave[] PROGMEM = {")
ulist,tlist = compute_sinewave(pwmbit,peaktopeak,zerobeat)
print("};")

plot.plot(tlist,ulist)
plot.savefig('../Pictures/sinewave-line.jpg')
plot.plot(tlist,ulist,linestyle=':',marker='.')
plot.savefig('../Pictures/sinewave-dots.jpg')
print("Ready.")
