I have a vibration sensor that outputs HIGH on vibration. Typically, output switches between HIGH and LOW multiple times within a second. I would like to measure total HIGH time in a second or so. How can I do this? I am not asking for a complete sketch. Just the overall approach so that I can start off. attachInterrupt seems to be the right command but I cannot understand the Arduino reference article. Would someone kindly explain it in plain terms? Thank you.
Basically the interrupt is a system that will call your function when a certain event happens. You can choose to be called when a pin goes HIGH (rising) or LOW (falling) or either (change). Whatever code was being executed (probably something in your loop() function) gets interrupted in the middle. The state of the processor and important registers get saved on the stack, so they can be restored when your interrupt function is done. Your interrupt function does what you need it to do, as quickly as possible, and then it returns. The interrupt system restores the important registers and the state of the processor, and continues with whatever was executing before.
The problem is that you never know when you're going to be interrupted. Which means there are some things you have to be careful about. Any global variables that you use in the interrupt function must be declared volatile. Otherwise the compiler may do some optimizations and your code might not work. Also, any two or four byte variables that you update in the interrupt function that are also used outside the function need to be bracketed with critical section code. Otherwise an interrupt might happen right in the middle of some math and give you weird results.
There are things you can't do in an interrupt function. No delay() calls. No Serial.print() calls.
There are things you CAN do that are very useful. Check the time with millis() or micros(). Set or check global flags. Update global sums.
It really is perfect for your need. If you register your interrupt function to be called on both edges, it can be very simple. You just check to see whether the pin is high or low. If it is high, it was a rising edge and you just save the current millis or micros in a time stamp. If it was low, it was a falling edge, and the difference between the current time and the saved time stamp is the high time for this pulse. You can just calculate that and add it to a global total.
Thank you for the explanation. I think I can start off from your note.