#!/usr/bin/python
#
# pwm_sinewave
#
# Calculate values for generate a PWM table for a Sinewave
# Used on a AVR ATMEGA 328
#
# 2013-02-24	tom@dl7bj.de	Tom, DL7BJ
#
frequency = 488
cpuclock = 8000000
pwmbit = 32
maxdutycycle = 98
mindutycycle = 2

def compute_sinewave(pwmbit, fpeaktopeak, zerobeat):
	t = 1
	ul = []
	tl = []
	while t <= pwmbit:
		u = sin(2*pi*t/pwmbit)
		u = u * fpeaktopeak/2
		u = u + zerobeat
		u = int(round(u))
		print(' ',u,',\t//',t)
		ul.append(u)
		tl.append(t)
		t = t + 1
	return ul,tl

import sys
from math import pi, sin
from scitools.std import *



if maxdutycycle <= mindutycycle:
	print("Error - maxdutycycle must be greater than mindutycycle")

if maxdutycycle == 100:
	maxamplitude = pwmbit - 1
else:
	maxamplitude = int((round(pwmbit * maxdutycycle/100.0)))

if mindutycycle == 0:
	minamplitude = 1
else:
	minamplitude = int((round(pwmbit * mindutycycle/100.0)))	

peaktopeak = maxamplitude - minamplitude
print("Amplitude from ", minamplitude, " to ", maxamplitude, "(", peaktopeak," Schritte)")

zerobeat = int(round((minamplitude + maxamplitude)/2.0))
print("Zerobeat on PWM step ", zerobeat)

fpeaktopeak = float(peaktopeak)

ulist,tlist = compute_sinewave(pwmbit,fpeaktopeak,zerobeat)
plot(tlist,ulist)

savefig('tmp.eps')

print("Ready.")
