Project

General

Profile

Statistics
| Branch: | Revision:

scoutos / scout_avr / src / range.cpp @ ec9e417d

History | View | Annotate | Download (1.52 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
18
#if defined(__AVR_ATmega128RFA1__)
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
unsigned int range;
34

    
35
static void on_edge(int which)
36
{
37
  unsigned int time = TCNT1;
38
  if (read_INT0)
39
  {
40
    range[which].start = time;
41
  }
42
  else
43
  {
44
    // if timer overflowed since start, this arithmetic should still work out
45
    range[which].value = time - range[which].start;
46
  }
47
}
48

    
49
ISR(INT0_vect)
50
{
51
  on_edge(0);
52
}
53

    
54
ISR(INT1_vect)
55
{
56
  on_edge(1);
57
}
58

    
59
void range_init()
60
{
61
  // ISCx = 1, edge triggered
62
  EICRA |= _BV(ISC10) | _BV(ISC00);
63
  // enable INT0 and INT1
64
  EIMSK |= _BV(INT1) | _BV(INT0);
65
  
66
  // CS1 = 2, 1/8 prescaler
67
  TCCR1B = _BV(CS11);
68
  
69
  range = -1;
70
}
71

    
72
unsigned int range_get(int which)
73
{
74
  unsigned int ret;
75
  if (0 <= which && which <= 1)
76
  {
77
    cli();
78
    ret = range[which].value;
79
    sei();
80
    return ret;
81
  }
82
  else return 0xFFFF;
83
}