Project

General

Profile

Statistics
| Branch: | Revision:

root / scout_avr / src / range.cpp @ 807483bf

History | View | Annotate | Download (1.71 KB)

1 1c3c96ce Tom Mullins
#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 807483bf Tom Mullins
// so that we can test on a 328 or the stk600
18
#if defined(__AVR_ATmega128RFA1__) || defined(__AVR_ATmega2560__)
19 1c3c96ce Tom Mullins
#  define read_INT0 (PIND & _BV(PD0))
20 ec9e417d Tom Mullins
#  define read_INT1 (PIND & _BV(PD1))
21 1c3c96ce Tom Mullins
#elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega328__)
22
#  define read_INT0 (PIND & _BV(PD2))
23 ec9e417d Tom Mullins
#  define read_INT1 (PIND & _BV(PD3))
24 1c3c96ce Tom Mullins
#else
25 ec9e417d Tom Mullins
#  error "Please define read_INTx for this device"
26 1c3c96ce Tom Mullins
#endif
27
28 ec9e417d Tom Mullins
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 1c3c96ce Tom Mullins
{
35 807483bf Tom Mullins
  unsigned char int_high;
36 ec9e417d Tom Mullins
  unsigned int time = TCNT1;
37 807483bf Tom Mullins
  
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 1c3c96ce Tom Mullins
  {
49 ec9e417d Tom Mullins
    range[which].start = time;
50 1c3c96ce Tom Mullins
  }
51
  else
52
  {
53 ec9e417d Tom Mullins
    // if timer overflowed since start, this arithmetic should still work out
54
    range[which].value = time - range[which].start;
55 1c3c96ce Tom Mullins
  }
56
}
57
58 ec9e417d Tom Mullins
ISR(INT0_vect)
59
{
60
  on_edge(0);
61
}
62
63
ISR(INT1_vect)
64
{
65
  on_edge(1);
66
}
67
68 1c3c96ce Tom Mullins
void range_init()
69
{
70 ec9e417d Tom Mullins
  // ISCx = 1, edge triggered
71
  EICRA |= _BV(ISC10) | _BV(ISC00);
72
  // enable INT0 and INT1
73
  EIMSK |= _BV(INT1) | _BV(INT0);
74 1c3c96ce Tom Mullins
  
75
  // CS1 = 2, 1/8 prescaler
76
  TCCR1B = _BV(CS11);
77
  
78 230b1b7f Tom Mullins
  range[0].value = RANGE_ERR;
79
  range[1].value = RANGE_ERR;
80 1c3c96ce Tom Mullins
}
81
82 ec9e417d Tom Mullins
unsigned int range_get(int which)
83 1c3c96ce Tom Mullins
{
84 ec9e417d Tom Mullins
  unsigned int ret;
85
  if (0 <= which && which <= 1)
86
  {
87
    cli();
88
    ret = range[which].value;
89
    sei();
90
    return ret;
91
  }
92 230b1b7f Tom Mullins
  else return RANGE_ERR;
93 1c3c96ce Tom Mullins
}