code 2010
[aversive.git] / projects / microb2010 / tests / beacon_tsop / main.c
1 /*  
2  *  Copyright Droids Corporation (2010)
3  *  Olivier Matz <zer0@droids-corp.org>
4  * 
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program; if not, write to the Free Software
17  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  *
19  *  Revision : $Id: main.c,v 1.8 2009-05-02 10:08:09 zer0 Exp $
20  *
21  */
22
23 #include <math.h>
24
25 #include <aversive.h>
26 #include <aversive/wait.h>
27
28 #include <uart.h>
29 #include <pid.h>
30 #include <pwm_ng.h>
31 #include <parse.h>
32 #include <rdline.h>
33 #include <vect_base.h>
34 #include <lines.h>
35 #include <circles.h>
36
37 #include "cmdline.h"
38 #include "uart_proto.h"
39 #include "trigo.h"
40 #include "main.h"
41
42 #define BOARD2010
43 //#define BOARD2006
44
45 #ifdef BOARD2010
46 #include "board2010.h"
47 #else
48 #include "board2006.h"
49 #endif
50
51 /******************* TSOP */
52
53 struct detected_frame {
54         uint16_t frame;
55         uint16_t ref_time;
56         uint16_t time;
57         uint16_t tick;
58 };
59
60 /* frame */
61 struct frame_status {
62         uint8_t led_cpt;
63         uint16_t ref_time;
64         uint16_t start_time;
65         uint16_t frame;
66         uint16_t mask;
67         uint16_t prev_time;
68         uint16_t time_long;
69         uint16_t time_short;
70         uint8_t prev_tsop;
71         uint8_t len;
72         uint8_t frame_len;
73         uint8_t val;
74 #define FRAME_RING_ORDER 4
75 #define FRAME_RING_SIZE  (1<<FRAME_RING_ORDER)
76 #define FRAME_RING_MASK  (FRAME_RING_SIZE-1)
77         uint8_t head;
78         uint8_t tail;
79         struct detected_frame ring[FRAME_RING_SIZE];
80 };
81
82 static struct frame_status static_beacon;
83 static struct frame_status opp_beacon;
84 static uint16_t tick = 0;
85
86 #define MIN_DIST 200.
87 #define MAX_DIST 3500.
88
89 /* in ticks (=CS_PERIOD), age before the entry is removed from ring */
90 #define MAX_CAP_AGE 30
91
92 /********************** CS */
93
94 /* 8ms, easier if it's a pow of 2 */
95 #define CS_PERIOD_US (8192)
96 #define CS_PERIOD ((uint16_t)(CS_PERIOD_US/4))
97 #define CPT_ICR_MAX (uint8_t)((1000000UL/(uint32_t)CS_PERIOD_US)) /* too slow = 1 tr/s */
98 #define CPT_ICR_MIN (uint8_t)((10000UL/(uint32_t)CS_PERIOD_US))   /* too fast = 100 tr/s */
99
100 /* in tr / 1000s */
101 #define CS_CONSIGN (15 * 1000L)
102
103 /* 5% tolerance to validate captures, period is in  */
104 #define TIM3_UNIT 250000000L
105 #define MOTOR_PERIOD_MIN ((uint32_t)((250000000L/CS_CONSIGN) * 0.95))
106 #define MOTOR_PERIOD_MAX ((uint32_t)((250000000L/CS_CONSIGN) * 1.05))
107
108 /* pwm for laser:
109  *  - clear on timer compare (CTC)
110  *  - Toggle OC0 on compare match
111  *  - prescaler = 1 */
112 #define LASER_ON() do { TCCR0 = _BV(WGM01) | _BV(COM00) | _BV(CS00); } while (0)
113 #define LASER_OFF() do { TCCR0 = 0; } while (0)
114
115 struct beacon_tsop beacon_tsop;
116 uint32_t cs_consign = CS_CONSIGN;
117
118 static uint32_t current_motor_period;
119
120 void debug_serial(void)
121 {
122 #if 0
123         while (1) {
124                 int16_t c;
125                 c = uart_recv_nowait(0);
126                 if (c != -1) 
127                         printf("%c", (char)(c+1));
128                 LED1_ON();
129                 wait_ms(500);
130                 LED1_OFF();
131                 wait_ms(500);
132         }
133 #endif
134 }
135                   
136 void debug_tsop(void)
137 {
138 #if 0
139         while (1) {
140                 if (TSOP_READ())
141                         LED1_OFF();
142                 else {
143                         LED1_ON();
144                         wait_ms(500);
145                 }
146         }
147 #endif
148 }
149
150 /* val is 16 bits, including 4 bits-cksum in MSB, return 0xFFFF is
151  * cksum is wrong, or the 12 bits value on success. */
152 static uint16_t verify_cksum(uint16_t val)
153 {
154         uint16_t x, cksum;
155
156         x = (val & 0xfff);
157         /* add the four 4-bits blocks of val together */
158         cksum = val & 0xf;
159         val = val >> 4;
160         cksum += val & 0xf;
161         cksum = (cksum & 0xf) + ((cksum & 0xf0) >> 4);
162         val = val >> 4;
163         cksum += val & 0xf;
164         cksum = (cksum & 0xf) + ((cksum & 0xf0) >> 4);
165         val = val >> 4;
166         cksum += val & 0xf;
167         cksum = (cksum & 0xf) + ((cksum & 0xf0) >> 4);
168         if (cksum == 0xf)
169                 return x;
170         return 0xffff; /* wrong cksum */
171 }
172
173 static inline void decode_frame(struct frame_status *status,
174                                 uint16_t ref_time, uint16_t cur_time, uint8_t cur_tsop)
175 {
176         uint16_t diff_time = cur_time - status->prev_time;
177
178         /* first rising edge */
179         if (status->len == 0 && cur_tsop && diff_time > status->time_long) {
180                 status->len = 1;
181                 status->val = 1;
182                 status->frame = 0;
183                 status->start_time = cur_time;
184                 status->ref_time = ref_time;
185                 status->mask = 1;
186         }
187         /* any short edge */
188         else if (status->len != 0 && diff_time < status->time_short) {
189                 if (status->len & 1) {
190                         if (status->val)
191                                 status->frame |= status->mask;
192                         status->mask <<= 1;
193                 }
194                 status->len ++;
195         }
196         /* any long edge */
197         else if (status->len != 0 && diff_time < status->time_long) {
198                 status->val = !status->val;
199                 if (status->val)
200                         status->frame |= status->mask;
201                 status->mask <<= 1;
202                 status->len += 2;
203         }
204         /* error case, reset */
205         else {
206                 status->len = 0;
207         }
208
209         /* end of frame */
210         if (status->len == status->frame_len*2) {
211                 uint8_t tail_next = (status->tail+1) & FRAME_RING_MASK;
212                 uint16_t frame_mask;
213
214                 frame_mask = (1 << status->frame_len) - 1;
215
216                 if (tail_next != status->head) {
217                         status->ring[status->tail].frame = (status->frame & frame_mask);
218                         status->ring[status->tail].ref_time = status->ref_time;
219                         status->ring[status->tail].time = status->start_time;
220                         status->ring[status->tail].tick = tick;
221                         status->tail = tail_next;
222                         if ((status->led_cpt & 0x7) == 0)
223                                 LED3_TOGGLE();
224                         status->led_cpt ++;
225                 }
226                 status->len = 0;
227         }
228
229         status->prev_time = cur_time;
230         status->prev_tsop = cur_tsop;
231 }
232
233 /* decode frame */
234 SIGNAL(SIG_TSOP_STA) {
235         static uint8_t running = 0;
236
237         /* tsop status */
238         uint8_t cur_tsop;
239         uint16_t ref_time;
240         uint16_t cur_time;
241
242         ref_time = ICR3;
243         cur_time = TCNT3;
244         cur_tsop = TSOP_STA_READ();
245
246         /* avoid interruption stacking */
247         if (running)
248                 return;
249         running = 1;
250         sei();
251
252         if (cur_tsop)
253                 LED5_ON();
254         else
255                 LED5_OFF();
256
257         decode_frame(&static_beacon, ref_time, cur_time, cur_tsop);
258
259         running = 0;
260 }
261
262 /* decode frame */
263 SIGNAL(SIG_TSOP_OPP) {
264         static uint8_t running = 0;
265
266         /* tsop status */
267         uint8_t cur_tsop;
268         uint16_t ref_time;
269         uint16_t cur_time;
270
271         ref_time = ICR3;
272         cur_time = TCNT3;
273         cur_tsop = TSOP_OPP_READ();
274
275         /* avoid interruption stacking */
276         if (running)
277                 return;
278         running = 1;
279         sei();
280
281         if (cur_tsop)
282                 LED6_ON();
283         else
284                 LED6_OFF();
285
286         decode_frame(&opp_beacon, ref_time, cur_time, cur_tsop);
287
288         running = 0;
289 }
290
291 /* absolute value */
292 static inline int32_t AbS(int32_t x)
293 {
294         if (x > 0)
295                 return x;
296         else
297                 return -x;
298 }
299
300 /* Get the speed of motor (tr / 1000s)
301  * - icr_cpt is the number of CS period between 2 ICR updates
302  * - icr_diff is the difference of ICR values between the ICR updates
303  *   (modulo 65536 obviously) */
304 static inline int32_t get_speed(uint8_t icr_cpt, uint16_t icr_diff)
305 {
306 #if 0
307         int32_t best_diff = 65536L;
308         int8_t best_cpt = -2;
309         int32_t diff;
310         int8_t i;
311
312         /* too slow (less than 1 tr/s) */
313         if (icr_cpt > CPT_ICR_MAX)
314                 return 1000L;
315
316         /* too fast (more than 100 tr/s) */
317         if (icr_cpt < CPT_ICR_MIN)
318                 return 100000L;
319
320         /* try to get the real time knowning icr_cpt and icr_diff */
321         for (i=-1; i<2; i++) {
322                 diff = ((icr_cpt+i)&3) * 16384L;
323                 diff += (icr_diff & 0x3fff);
324                 diff -= icr_diff;
325                 if (diff > 32768L)
326                         diff -= 65536L;
327                 if (diff < -32768)
328                         diff += 65536L;
329         
330                 if (AbS(diff) < AbS(best_diff)) {
331                         best_diff = diff;
332                         best_cpt = icr_cpt + i;
333                 }
334         }
335
336         /* real time difference in timer unit (resolution 4us) */
337         diff = (best_cpt * 16384L) + (icr_diff & 0x3fff);
338         current_motor_period = diff; /* save it in global var */
339 #endif
340
341         /* too slow (less than 1 tr/s) */
342         if (icr_cpt >= CPT_ICR_MAX)
343                 return 1000L;
344
345         /* too fast (more than 100 tr/s) */
346         if (icr_cpt <= CPT_ICR_MIN)
347                 return 100000L;
348
349         /* XXX test */
350         if (icr_cpt > 25)
351                 return icr_cpt * 8192UL;
352
353         return TIM3_UNIT/icr_diff;
354 }
355
356 /* process the received frame ring */
357 static void process_sta_ring(struct frame_status *status)
358 {
359         uint8_t head, head_next;
360         uint16_t frame, frametick;
361         uint8_t found = 0;
362         uint8_t beacon_id;
363
364         /* beacon 0 */
365         uint16_t data0, time0, ref_time0;
366         double angle0;
367         double dist0;
368
369         /* beacon 1 */
370         uint16_t data1, time1, ref_time1;
371         double angle1;
372         double dist1;
373
374         point_t pos;
375         double a;
376
377         /* remove too old captures from the ring */
378         while (status->head != status->tail) {
379                 head_next = (status->head+1) & FRAME_RING_MASK;
380                 frametick = status->ring[status->head].tick;
381                 if ((uint16_t)(tick - frametick) < MAX_CAP_AGE)
382                         break;
383                 status->head = head_next;
384         }
385
386         head = status->head;
387         /* after CS, check if we have a new frame in ring */
388         while (head != status->tail) {
389                 head_next = (head+1) & FRAME_RING_MASK;
390                 frame = status->ring[head].frame;
391
392                 /* ignore bad cksum */
393                 if (verify_cksum(frame) == 0xFFFF)
394                         continue;
395
396                 beacon_id = (frame >> TSOP_STA_BEACON_ID_SHIFT) & TSOP_STA_BEACON_ID_MASK;
397                 if (beacon_id != TSOP_STA_BEACON_ID0 &&
398                     beacon_id != TSOP_STA_BEACON_ID1)
399                         continue;
400
401                 /* if motor speed is not good, skip values  */
402                 if (current_motor_period < MOTOR_PERIOD_MIN)
403                         continue;
404                 if (current_motor_period > MOTOR_PERIOD_MAX)
405                         continue;
406
407                 /* display if needed */
408                 if (beacon_tsop.debug_frame) {
409                         printf("STA ID=%d time=%d\r\n",
410                                beacon_id, status->ring[head].time);
411                 }
412
413                 if (beacon_id == TSOP_STA_BEACON_ID0) {
414                         found |= 0x1;
415                         data0 = (frame >> TSOP_STA_FRAME_DATA_SHIFT) & TSOP_STA_FRAME_DATA_MASK;
416                         time0 = status->ring[head].time;
417                         ref_time0 = status->ring[head].ref_time;
418                 }
419                 else if (beacon_id == TSOP_STA_BEACON_ID1) {
420                         found |= 0x2;
421                         data1 = (frame >> TSOP_STA_FRAME_DATA_SHIFT) & TSOP_STA_FRAME_DATA_MASK;
422                         time1 = status->ring[head].time;
423                         ref_time1 = status->ring[head].ref_time;
424                 }
425
426                 head = head_next;
427         }
428
429         /* if we didn't found beacon 0 and 1, return */
430         if (found != 0x3)
431                 return;
432
433         /* update ring head */
434         status->head = head;
435
436         /* beacon 0 */
437         dist0 = data0;
438         dist0 /= 512.;
439         dist0 *= (MAX_DIST-MIN_DIST);
440         dist0 += MIN_DIST;
441
442         time0 = time0 - ref_time0;
443         angle0 = (double)time0 / (double)current_motor_period;
444         if (angle0 > 1.)
445                 angle0 -= 1.;
446         if (angle0 > 1.)
447                 return; /* fail */
448         angle0 *= (2 * M_PI);
449         if (angle0 > M_PI)
450                 angle0 -= M_PI;
451
452         /* beacon 1 */
453         dist1 = data1;
454         dist1 /= 512.;
455         dist1 *= (MAX_DIST-MIN_DIST);
456         dist1 += MIN_DIST;
457
458         time1 = time1 - ref_time1;
459         angle1 = (double)time1 / (double)current_motor_period;
460         if (angle1 > 1.)
461                 angle1 -= 1.;
462         if (angle1 > 1.)
463                 return; /* fail */
464         angle1 *= (2 * M_PI);
465         if (angle0 > M_PI)
466                 angle0 -= M_PI;
467
468         if (ad_to_posxya(&pos, &a, 0, &beacon0, &beacon1, angle0, dist0,
469                          angle1, dist1) < 0)
470                 return;
471
472         xmit_static((uint16_t)pos.x, (uint16_t)pos.y, (uint16_t)a);
473 }
474
475 /* process the received frame ring */
476 static void process_opp_ring(struct frame_status *status)
477 {
478         uint8_t head_next;
479         uint16_t frame;
480         uint8_t found = 0;
481         uint8_t beacon_id;
482         uint16_t data, time, ref_time;
483         double angle;
484         double dist;
485                                 
486         /* after CS, check if we have a new frame in ring */
487         while (status->head != status->tail) {
488                 head_next = (status->head+1) & FRAME_RING_MASK;
489                 frame = status->ring[status->head].frame;
490
491                 /* ignore bad cksum */
492                 if (verify_cksum(frame) == 0xFFFF)
493                         continue;
494
495                 beacon_id = (frame >> TSOP_OPP_BEACON_ID_SHIFT) & TSOP_OPP_BEACON_ID_MASK;
496                 if (beacon_id != TSOP_OPP_BEACON_ID)
497                         continue;
498
499                 /* if motor speed is not good, skip values  */
500                 if (current_motor_period < MOTOR_PERIOD_MIN)
501                         continue;
502                 if (current_motor_period > MOTOR_PERIOD_MAX)
503                         continue;
504
505                 found = 1;
506                 data = (frame >> TSOP_OPP_FRAME_DATA_SHIFT) & TSOP_OPP_FRAME_DATA_MASK;
507                 time = status->ring[status->head].time;
508                 ref_time = status->ring[status->head].ref_time;
509
510                 /* display if needed */
511                 if (beacon_tsop.debug_frame) {
512                         printf("OPP ID=%d data=%d time=%d\r\n",
513                                beacon_id, data,
514                                status->ring[status->head].time);
515                 }
516                 status->head = head_next;
517         }
518
519         if (found == 0)
520                 return;
521
522         dist = data;
523         dist /= 512.;
524         dist *= (MAX_DIST-MIN_DIST);
525         dist += MIN_DIST;
526
527         time = time - ref_time;
528         angle = (double)time / (double)current_motor_period;
529         if (angle > 1.)
530                 angle -= 1.;
531         if (angle > 1.)
532                 return; /* fail */
533         angle *= 3600; /* angle in 1/10 deg */
534
535         xmit_opp((uint16_t)dist, (uint16_t)angle);
536 }
537
538 int main(void)
539 {
540         uint16_t prev_cs = 0;
541         uint16_t prev_icr = 0;
542         uint16_t icr = 0;
543         uint16_t diff_icr = 0;
544         uint8_t cpt_icr = 0;
545         uint8_t cpt = 0;
546         int32_t speed = 0, out, err;
547         uint16_t tcnt3;
548         uint8_t x = 0; /* debug display counter */
549
550         opp_beacon.frame_len = TSOP_OPP_FRAME_LEN;
551         opp_beacon.time_long = TSOP_OPP_TIME_LONG;
552         opp_beacon.time_short = TSOP_OPP_TIME_SHORT;
553
554         static_beacon.frame_len = TSOP_STA_FRAME_LEN;
555         static_beacon.time_long = TSOP_STA_TIME_LONG;
556         static_beacon.time_short = TSOP_STA_TIME_SHORT;
557
558         /* LEDS */
559         LED_DDR_INIT();
560         DDRB |= 0x10; /* OC0 (laser pwm) */
561
562         /* PID init */
563         pid_init(&beacon_tsop.pid);
564         pid_set_gains(&beacon_tsop.pid, 700, 10, 0);
565         pid_set_maximums(&beacon_tsop.pid, 0, 200000, 4095);
566         pid_set_out_shift(&beacon_tsop.pid, 10);
567         pid_set_derivate_filter(&beacon_tsop.pid, 4);
568
569         uart_init();
570 #if CMDLINE_UART == 0
571         fdevopen(uart0_dev_send, uart0_dev_recv);
572 #elif CMDLINE_UART == 1
573         fdevopen(uart1_dev_send, uart1_dev_recv);
574 #endif
575
576         rdline_init(&beacon_tsop.rdl, write_char, valid_buffer, complete_buffer);
577         snprintf(beacon_tsop.prompt, sizeof(beacon_tsop.prompt), "beacon > ");  
578         rdline_newline(&beacon_tsop.rdl, beacon_tsop.prompt);
579
580         debug_tsop();
581         debug_serial();
582
583         /* configure external interrupt for TSOP */
584         EICRx_TSOP |= _BV(ISCx0_TSOP_STA) | _BV(ISCx0_TSOP_OPP);
585         EIMSK |= _BV(INTx_TSOP_STA) | _BV(INTx_TSOP_OPP);
586
587         /* pwm for motor */
588         PWM_NG_TIMER_16BITS_INIT(1, TIMER_16_MODE_PWM_10, 
589                                  TIMER1_PRESCALER_DIV_1);
590 #ifdef BOARD2010
591         PWM_NG_INIT16(&beacon_tsop.pwm_motor, 1, C, 10, 0, NULL, 0);
592 #else
593         PWM_NG_INIT16(&beacon_tsop.pwm_motor, 1, A, 10, 0, NULL, 0);
594 #endif
595
596         /* pwm for laser:
597          *  - clear on timer compare (CTC)
598          *  - Toggle OC0 on compare match
599          *  - prescaler = 1 */
600         TCCR0 = _BV(WGM01) | _BV(COM00) | _BV(CS00);
601         OCR0 = 18; /* f ~= 420 khz at 16 Mhz */
602
603         /* configure timer 3: CLK/64
604          * it is used as a reference time
605          * enable noise canceller for ICP3 */
606         TCCR3B = _BV(CS11) | _BV(CS10);
607
608         sei();
609
610         /* Control system will be done in main loop */
611         while (1) {
612
613                 /* process pending bytes on uart */
614                 cmdline_process();
615
616                 /* monitor the value of ICR (which is modified
617                  * automatically on TT rising edge). If the value
618                  * changed, process the time difference. */
619                 if (ETIFR & _BV(ICF3)) {
620                         cli();
621                         icr = ICR3;
622                         sei();
623                         ETIFR = _BV(ICF3);
624
625                         LED2_TOGGLE();
626                         diff_icr = (icr - prev_icr);
627                         cpt_icr = cpt;
628                         prev_icr = icr;
629                         cpt = 0;
630                         speed = get_speed(cpt_icr, diff_icr);
631                 }
632
633                 /* read time reference */
634                 cli();
635                 tcnt3 = TCNT3;
636                 sei();
637
638                 /* wait cs period */
639                 if (tcnt3 - prev_cs < CS_PERIOD)
640                         continue;
641
642                 /* CS LED */
643                 if (x & 0x80)
644                         LED1_ON();
645                 else
646                         LED1_OFF();
647                 x++;
648
649                 /* process CS... maybe we don't need to use
650                  * control_system_manager, just PID is enough */
651
652                 if (cpt == CPT_ICR_MAX)
653                         speed = 0;
654                 
655                 /* enabled laser when rotation speed if at least 5tr/s */
656                 if (speed > 5000)
657                         LASER_ON();
658                 else
659                         LASER_OFF();
660
661                 err = cs_consign - speed;
662                 out = pid_do_filter(&beacon_tsop.pid, err);
663                 if (out < 0)
664                         out = 0;
665                 /* XXX */
666                 if (out > 3000)
667                         out = 3000;
668
669                 if (x == 0 && beacon_tsop.debug_speed)
670                         printf("%ld %ld %u %u / %u\n",
671                                speed, out, diff_icr, cpt_icr, cpt);
672
673                 pwm_ng_set(&beacon_tsop.pwm_motor, out);
674
675                 prev_cs = tcnt3;
676
677                 /* count the number of CS period between 2 ICR
678                  * captures */
679                 if (cpt < CPT_ICR_MAX)
680                         cpt ++;
681
682                 process_sta_ring(&static_beacon);
683                 process_opp_ring(&opp_beacon);
684                 cli();
685                 tick ++; /* global imprecise time reference */
686                 sei();
687         }
688
689         return 0;
690 }