Statistics
| Branch: | Revision:

root / scout_avr / src / range.cpp @ cc9ca04e

History | View | Annotate | Download (1.48 KB)

1 1c3c96ce Tom Mullins
extern "C"
2
{
3
#include <avr/io.h>
4
#include <avr/interrupt.h>
5
}
6 cc9ca04e Tom Mullins
#include "range.h"
7 1c3c96ce Tom Mullins
8
/* Ultrasonic Sensor:
9
 * -if RX pin is left open, it will continuously take readings
10
 * -PW output is 147us/in.
11
 * -PW will be high for a maximum of 37.5ms if no target is detected
12
 * 
13
 * 37.5ms * 8 MHz / 8 prescaler = 37500 max wait
14 cc9ca04e Tom Mullins
 * 37.5ms * 16 MHz / 8 prescaler = problem
15 1c3c96ce Tom Mullins
 */
16
17 ec9e417d Tom Mullins
struct range_t {
18
  unsigned int start; // timer value on rising edge
19
  unsigned int value; // last measured range
20
} range[2];
21
22
static void on_edge(int which)
23 1c3c96ce Tom Mullins
{
24 807483bf Tom Mullins
  unsigned char int_high;
25 812788aa Tom Mullins
  unsigned int time = TCNT5;
26 807483bf Tom Mullins
  
27
  if (which)
28
  {
29 cc9ca04e Tom Mullins
    int_high = PIN_SONAR_PWM & _BV(P_SONAR_PWM1);
30 807483bf Tom Mullins
  }
31
  else
32
  {
33 cc9ca04e Tom Mullins
    int_high = PIN_SONAR_PWM & _BV(P_SONAR_PWM0);
34 807483bf Tom Mullins
  }
35
  
36
  if (int_high)
37 1c3c96ce Tom Mullins
  {
38 ec9e417d Tom Mullins
    range[which].start = time;
39 1c3c96ce Tom Mullins
  }
40
  else
41
  {
42 ec9e417d Tom Mullins
    // if timer overflowed since start, this arithmetic should still work out
43
    range[which].value = time - range[which].start;
44 1c3c96ce Tom Mullins
  }
45
}
46
47 cc9ca04e Tom Mullins
ISR(INT3_vect)
48 ec9e417d Tom Mullins
{
49
  on_edge(0);
50
}
51
52 cc9ca04e Tom Mullins
ISR(INT2_vect)
53 ec9e417d Tom Mullins
{
54
  on_edge(1);
55
}
56
57 1c3c96ce Tom Mullins
void range_init()
58
{
59 ec9e417d Tom Mullins
  // ISCx = 1, edge triggered
60 cc9ca04e Tom Mullins
  EICRA |= _BV(ISC20) | _BV(ISC30);
61
  // enable INT2 and INT3
62
  EIMSK |= _BV(INT2) | _BV(INT3);
63 1c3c96ce Tom Mullins
  
64
  // CS1 = 2, 1/8 prescaler
65 f115416e Tom Mullins
  // if this is changed, remember to change recv_edge in bom.cpp!
66 812788aa Tom Mullins
  TCCR5B = _BV(CS51);
67 1c3c96ce Tom Mullins
  
68 230b1b7f Tom Mullins
  range[0].value = RANGE_ERR;
69
  range[1].value = RANGE_ERR;
70 1c3c96ce Tom Mullins
}
71
72 ec9e417d Tom Mullins
unsigned int range_get(int which)
73 1c3c96ce Tom Mullins
{
74 ec9e417d Tom Mullins
  unsigned int ret;
75
  if (0 <= which && which <= 1)
76
  {
77
    cli();
78
    ret = range[which].value;
79
    sei();
80
    return ret;
81
  }
82 230b1b7f Tom Mullins
  else return RANGE_ERR;
83 1c3c96ce Tom Mullins
}