root / scout_avr / src / range.cpp @ 807483bf
History | View | Annotate | Download (1.71 KB)
1 |
#include "range.h" |
---|---|
2 |
|
3 |
extern "C" |
4 |
{ |
5 |
#include <avr/io.h> |
6 |
#include <avr/interrupt.h> |
7 |
} |
8 |
|
9 |
/* Ultrasonic Sensor:
|
10 |
* -if RX pin is left open, it will continuously take readings
|
11 |
* -PW output is 147us/in.
|
12 |
* -PW will be high for a maximum of 37.5ms if no target is detected
|
13 |
*
|
14 |
* 37.5ms * 8 MHz / 8 prescaler = 37500 max wait
|
15 |
*/
|
16 |
|
17 |
// so that we can test on a 328 or the stk600
|
18 |
#if defined(__AVR_ATmega128RFA1__) || defined(__AVR_ATmega2560__)
|
19 |
# define read_INT0 (PIND & _BV(PD0))
|
20 |
# define read_INT1 (PIND & _BV(PD1))
|
21 |
#elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega328__)
|
22 |
# define read_INT0 (PIND & _BV(PD2))
|
23 |
# define read_INT1 (PIND & _BV(PD3))
|
24 |
#else
|
25 |
# error "Please define read_INTx for this device" |
26 |
#endif
|
27 |
|
28 |
struct range_t {
|
29 |
unsigned int start; // timer value on rising edge |
30 |
unsigned int value; // last measured range |
31 |
} range[2];
|
32 |
|
33 |
static void on_edge(int which) |
34 |
{ |
35 |
unsigned char int_high; |
36 |
unsigned int time = TCNT1; |
37 |
|
38 |
if (which)
|
39 |
{ |
40 |
int_high = read_INT1; |
41 |
} |
42 |
else
|
43 |
{ |
44 |
int_high = read_INT0; |
45 |
} |
46 |
|
47 |
if (int_high)
|
48 |
{ |
49 |
range[which].start = time; |
50 |
} |
51 |
else
|
52 |
{ |
53 |
// if timer overflowed since start, this arithmetic should still work out
|
54 |
range[which].value = time - range[which].start; |
55 |
} |
56 |
} |
57 |
|
58 |
ISR(INT0_vect) |
59 |
{ |
60 |
on_edge(0);
|
61 |
} |
62 |
|
63 |
ISR(INT1_vect) |
64 |
{ |
65 |
on_edge(1);
|
66 |
} |
67 |
|
68 |
void range_init()
|
69 |
{ |
70 |
// ISCx = 1, edge triggered
|
71 |
EICRA |= _BV(ISC10) | _BV(ISC00); |
72 |
// enable INT0 and INT1
|
73 |
EIMSK |= _BV(INT1) | _BV(INT0); |
74 |
|
75 |
// CS1 = 2, 1/8 prescaler
|
76 |
TCCR1B = _BV(CS11); |
77 |
|
78 |
range[0].value = RANGE_ERR;
|
79 |
range[1].value = RANGE_ERR;
|
80 |
} |
81 |
|
82 |
unsigned int range_get(int which) |
83 |
{ |
84 |
unsigned int ret; |
85 |
if (0 <= which && which <= 1) |
86 |
{ |
87 |
cli(); |
88 |
ret = range[which].value; |
89 |
sei(); |
90 |
return ret;
|
91 |
} |
92 |
else return RANGE_ERR; |
93 |
} |