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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
|
// Servo control for ATTiny2313 @ 8MHz.
/* Multi-servo control using hardware timer interrupts.
* Pulses each of the pins on PORTB sequentially, setting
* the interrupt to fire when the pulse is over.
*
/
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#define PWM_REFRESH_RATE_US 20000 // refresh rate in microseconds.20ms is norm,so 20,000.
#define ULIM 2600
#define LLIM 600
#define CTR 1600 // (ULIM-(ULIM-LLIM))/2+(ULIM-LLIM)
int channel = 0;
int pwm[8] = { LLIM,LLIM,CTR,CTR,CTR,CTR,CTR,CTR }; // pwm defined in ticks. range= 600-2600
int pwm_remainder;
ISR (SIG_OUTPUT_COMPARE1A)
{
if (channel<=7)
{
PORTB = (1<<channel);
OCR1A = pwm[channel];
channel++;
}
else
{
channel=0;
PORTB=0x00;
OCR1A=pwm_remainder;
}
}
void init_servos()
{
pwm_remainder=PWM_REFRESH_RATE_US-(pwm[0]+pwm[1]+pwm[2]+pwm[3]+pwm[4]+pwm[5]+pwm[6]+pwm[7]);
TIMSK = _BV(OCIE1A);
TCCR1B = _BV(CS11) // sysclk/8 prescale: convenient @ sysclk 8MHZ
// because it means 1 tick/us
// with a 16 bit timer MAXOCR1A is 65536 or 65ms
// while our max cycle time should be 20ms... it fits!
| _BV(WGM12); // CTC mode, TOP = OCR1A
OCR1A = 512; // count up to TOP
}
void stop_servos()
{
TCCR1B = 0x00;
}
void set_servo(int pin, int usec) // sets given a value from 0-2000;
// no checking...slows stuff down.
{
pwm[pin] = usec-600;
// keep pwm refresh rate constant. if not necessary, comment out.
pwm_remainder=PWM_REFRESH_RATE_US-(pwm[0]+pwm[1]+pwm[2]+pwm[3]+pwm[4]+pwm[5]+pwm[6]+pwm[7]);
}
int main()
{
// -----------------------------------------------------------------------------
CLKPR = 0x80; // set the CLKPCE bit to allow a change
CLKPR = 0x00; // set clock divider ratio to 1; enables 8MHZ sysclock
DDRB = 0xFF; // enable output
DDRD=0x00; //using D pins as input
PORTD=0xFF; // pullups on portd
PORTA = 0xFF;
PORTB = 0xFF;
//int lpctr = 2000;
init_servos();
sei();
while (1)
{
pwm[1] = 2500;
// if(bit_is_clear(PIND,0)) PORTB =0xFF;
// else PORTB = 0x00;
if(bit_is_clear(PIND,0)) pwm[0] = ULIM;
else pwm[0] = LLIM;
}
return(0);
}
|