forked from B3AU/micropython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPDM.py
44 lines (34 loc) · 1.11 KB
/
PDM.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
__author__ = 'beau'
import pyb
class PDM():
def __init__(self,pout='X11',tim=4,freq=50):
"""
:param pout: output pin nr
:param tim: timer number
:param freq: frequency of the bitstream
"""
self.max = 2**24-1#2**31-1 crashes with larger ints? 24bit resolution is fine enough ;)
self.pout = pyb.Pin(pout, pyb.Pin.OUT_PP)
self.err = 0 # error accumulator
self.output = 0
self.freq = freq
self.tim = pyb.Timer(tim)
self.tim.init(freq=freq)
self.tim.callback(lambda t: self.call_me())
def set_output(self,out):
"""
:param out: desired output as a value between 0 and 1
"""
print ('setting output to '+str(out))
self.tim.deinit()
self.output = int(self.max*out)
self.tim.init(freq=self.freq)
self.tim.callback(lambda t: self.call_me())
def call_me(self):
if self.err >= 0:
self.pout.low()
self.err -= self.output
else:
self.pout.high()
self.err += self.max
self.err -= self.output