initial commit
[arduino/ultrasonic-sensor.git] / UltrasonicSensor / libraries / UltrasonicInterrupt / UltrasonicInterrupt.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "Arduino.h"
#include "UltrasonicInterrupt.h"
 
// initialise static vars
bool UltrasonicInterrupt::state = false;
bool UltrasonicInterrupt::active = false;
int UltrasonicInterrupt::interrupt = 0;
 
void (*UltrasonicInterrupt::onComplete)(unsigned long) = NULL;
 
 
/**
*
*
**/
void UltrasonicInterrupt::setup(void (*pulseComplete)(unsigned long), int customInterrupt ){
        onComplete      = pulseComplete;
        active          = false;
        interrupt   = customInterrupt;
}
 
 
/**
* @public
* Start listening on the desired interrupt for a pulse
*/
void UltrasonicInterrupt::begin(){
        state           = false;
        active          = true;
        attachInterrupt(interrupt, pinChange, RISING);
}
 
 
/**
* @public
* There's no timeout with this class: it will listen indefinitely for a change on the interrupt pin.
* Use abandon to stop waiting for a pulse.
*/
void UltrasonicInterrupt::abandon(){
        if(active){
                state =  active = false;
                detachInterrupt(interrupt);
        }
}
 
 
/**
* @static
* interrupt handler - called whenever the interrupt pin state changes
*/
void UltrasonicInterrupt::pinChange(){
 
        static unsigned long pulseStart = 0;
 
        state = !state;
 
        if(state){
                // interrupt pin has changed, a pulse has started
                pulseStart = micros(); // store the current microseconds
                attachInterrupt(interrupt, pinChange, FALLING); // now wait for the falling edge
        } else {
 
                // pulse complete, detach the interrupt...
                detachInterrupt(interrupt);
 
                // pin state changed again - pulse ended
                unsigned long duration = micros() - pulseStart; // get the pulse length
 
                active = false;
                onComplete(duration);
        }
}
comments