system
April 14, 2013, 7:27pm
1
Hi all,
I'm trying to measure the time between two pulses for a speedometer I am currently building.
I'm using an interrupt to do so, but it just won't work. Every time the magnet form the wheel
comes by the reed relais, it sends out an 5V pulse. So if I know the time between those pulses I
can calculate the speed. Here is the code:
unsigned long elapsed;
unsigned long previous;
void setup() {
attachInterrupt(0, elapse, RISING);
Serial.begin(9600);
previous = millis();
}
void loop() {
Serial.println("--");
}
void elapse(){
elapsed = millis() - previous;
previous = millis();
Serial.println(elapsed);
}
Can someone please help me with this? Also, if there is a better way
to do this, please let me know.
Bob
system
April 14, 2013, 7:28pm
2
Don't do serial I/O in an interrupt.
system
April 14, 2013, 7:34pm
3
Thanks man,
I changed the code to this:
unsigned long elapsed = 0;
unsigned long previous;
void setup() {
attachInterrupt(0, elapse, RISING);
Serial.begin(9600);
previous = millis();
}
void loop() {
Serial.println(elapsed);
}
void elapse(){
elapsed = millis() - previous;
previous = millis();
}
I'm still getting a lot of "0" in my serial monitor, even though I have printed some other
millis on it. I'm confused.
Any help?
system
April 14, 2013, 7:40pm
4
I'd put a simple counter in the interrupt, and print the value of that, to check you're getting interrupts.
system
April 14, 2013, 8:04pm
5
Hi, thanks for the tip.
I just put a simple counter in there, and it appears
that it triggers multiple times at one stroke of a magnet.
Code:
unsigned long elapsed = 0;
unsigned long previous;
void setup() {
attachInterrupt(0, elapse, RISING);
Serial.begin(9600);
previous = millis();
}
void loop() {
Serial.println(elapsed);
delay(400);
}
void elapse(){
elapsed = elapsed++;
}
Serial Monitor:
0
0
0
0
0
4
4
7
7
10
10
14
14
14
14
18
18
18
18
18
18
18
34
34
34
41
44
44
I tried debouncing it, but obviously, it was to no avail. It seems the delay
isn't working with the interrupt.
Any more tips?
Arrch
April 14, 2013, 8:50pm
6
Look at the debounce example to see the concepts on debouncing an input.
elapsed = elapsed++;
should be
elapsed++;
system
April 14, 2013, 10:44pm
7
I tried debouncing it
Really? How?
It seems the delay
isn't working with the interrupt.
Of course not. That is NOT how to debounce a switch, anyway.
The blink without delay example is another good resource. Has it been a reasonable length of time since the last interrupt? Should I count, or not, this interrupt?