forked from elimbaum/TrinketPinball
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpwm.txt
59 lines (45 loc) · 1.9 KB
/
pwm.txt
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
[ PWM ]
We need to drive a motor and speaker with PWM.
Both are on timer0 (OC0A and OC0B) and can run at the same PWM frequency. millis() and friends also use timer0, so we can't change the PWM frequency.
For the motor, we want to be able to simply write a speed to the output compare register. Interrupt handler needn't do anything because the motor is on the output pin (direct hardware control).
The speaker is also on the output pin. However the tone function now needs to enable and disable the pwm... nope. It needs to update the PWM value. So I need to steal timer2 away from builtin tone library. That is, don't use built in tone. So I need a new tone function (PWM min/max) as well as an analog write to speaker function which the former will use.
So the user functions will be:
motorSpeed(byte speed);
speaker(byte value); ...swing between 0 and something small
tone(int frequency);
noTone();
Service Timer freq (prescale)
===================================
Servo 1 1.5 MHz (8)
spkr PWM 0
spkr Tone 2 variable
motor PWM 0 188 kHz (64)
timing 0 edit
If I use timer1 for tone, 12MHz / 64 prescaler, maybe?
freq = 12000000 / (64 * val)
val = 12000000 / (64 * freq)
Timer 0 (64 prescale, f = 188 kHz)
ovf builtin timing
A motor PWM (value 0 - 255, f = 730 Hz)
{ full hardware }
B servo PWM
{ software }
set register to current count + value
value 0 - 255 allows for 0 - 1.4 ms
187 ticks is about 1 ms.
150 ticks gives nice alignment (0.8 ms)
Procedure:
pin high
Set register to 150. Then, set register to value.
This allows 0.8 - 2.2 ms.
Then, set pin low.
Then, refresh is 20ms. So 14 cycles (count these).
Timer 1 (64 prescale, f = 188 kHz)
A speaker tone (CTC mode)
output freq = 12MHz / (64 * val), val = 12MHz / (64 * freq)
allows for full range of frequencies with pretty good resolution.
Timer 2 (1 prescale)
A speaker PWM (runs at 24 kHz)
toggleO
B motor
Servo now on 2.