2 #include <aversive/wait.h>
9 static struct servo servo_table[] = {
35 #define NB_SERVO (sizeof(servo_table)/sizeof(*servo_table))
37 static uint8_t bypass;
38 static volatile uint8_t done;
39 static uint8_t portval;
42 static uint8_t icp_idx = NB_SERVO;
43 static uint16_t icp_servos[NB_SERVO];
44 static uint16_t icp_prev;
46 #define BYPASS_ENABLE 14
47 #define BYPASS_DISABLE 15
49 #define LED_ON() do { PORTB |= 0x02; } while(0)
50 #define LED_OFF() do { PORTB &= ~0x02; } while(0)
55 * A command is stored on 2 bytes. The first one has its msb to 0, and the
56 * second one to 1. The first received byte contains the command number, and the
57 * msb of the servo value. The second byte contains the lsb of the servo value.
59 * Commands 0 to NB_SERVO are to set the value of servo.
60 * Command 14 is to enable bypass mode.
61 * Command 15 is to disable bypass mode.
66 /* inverted: little endian */
76 /* inverted: little endian */
82 SIGNAL(TIMER1_COMPA_vect)
85 TIMSK1 &= ~_BV(OCIE1A);
89 static void poll_spi(void)
93 /* reception complete ? */
94 if (!(SPSR & (1<<SPIF)))
98 if ((rxidx == 0) && (c & 0x80)) {
102 if ((rxidx == 1) && ((c & 0x80) == 0)) {
115 /* process command */
117 if (byte0.cmd_num < NB_SERVO) {
118 val = (uint16_t)byte0.val_msb << 7;
119 val += byte1.val_lsb;
120 servo_table[byte0.cmd_num].command = val;
122 else if (byte0.cmd_num == BYPASS_ENABLE) {
125 else if (byte0.cmd_num == BYPASS_DISABLE) {
133 static void poll_input_capture(void)
138 /* no new sample, return */
139 if ((TIFR1 & _BV(ICF1)) == 0)
146 rising = TCCR1B & _BV(ICES1);
148 /* change the edge type */
149 TCCR1B ^= _BV(ICES1);
152 TIFR1 = TIFR1 | _BV(ICF1);
154 diff = icp - icp_prev;
157 /* a rising edge with at least 2ms of state 0 means that we
158 * get the first servo */
159 if (rising == 1 && diff > 2000) {
164 /* get the value for the servo */
165 if (rising == 0 && icp_idx < NB_SERVO) {
167 icp_servos[icp_idx] = 0;
169 icp_servos[icp_idx] = diff - 1000;
174 static void poll(void)
177 poll_input_capture();
180 static void load_timer_at(uint16_t t)
183 TIMSK1 |= _BV(OCIE1A);
186 static void do_one_servo(struct servo *s)
192 //portval = PORTC | (1 << s->bit);
193 portval = (1 << s->bit);
195 load_timer_at(t + 20);
202 //portval = PORTC & (~(1 << s->bit));
203 load_timer_at(t + 20 + 1000 + s->command);
214 /* use pull-up for inputs */
220 #if 0 /* LED debug */
229 /* servo outputs PD2-PD7 */
232 /* start timer1 at clk/8 (1Mhz), enable noise canceler on
233 * input capture, capture rising edge */
235 TCCR1B = _BV(CS11) | _BV(ICNC1) | _BV(ICES1);
237 /* start timer0 at clk/1024 (~8Khz) */
239 TCCR0B = _BV(CS02) | _BV(CS00);
241 /* enable spi (don't set unused MISO as output) */
249 for (i = 0; i < NB_SERVO; i++) {
250 do_one_servo(&servo_table[i]);
263 while (bypass == 1) {