I can think of two problems you may be having. As was previously mentioned, you may want to try 'debouncing' your input signal.
You may also want to check if your external input is floating; that is to say, does your input have a pullup or pulldown resistor attached, allowing the signal to be pulled high or low respectively when no signal is present? If it doesn't, your input is floating.
Adding a pullup or pulldown resistor eliminates most chances of having random noise affect your signal. Debouncing removes error caused by the actual input itself triggering your microcontroller multiple times.
Here is an example of Debouncing:
Let's use a simple momentary switch as an example. When the switch is first closed, the signal won't go cleanly from OFF to ON. There will be a very, very short period of time where the signal is stabilizing.
** refer to this very interesting image from an oscilloscope, showing approximately how a mechanical switch behaves when it is first closed:
https://a.pololu-files.com/picture/0J790.600.jpg?c2e19ae7a5387b0870b4dbacf5cb7055
If you think about how a microcontroller interprets this signal, it sees multiple spikes before everything is stable. These spikes are totally unpredictable, and so we need to come up with a work-around.
Solution:
Debouncing.
There are plenty of sophisticated algorithms used to debounce hardware, but there is a simple procedure you can follow to create your own debounce function.
- Interrupt detected, input value recorded
- Wait (try 10-20us for starters)
- Check the input again.
- Is the previously recorded input value the same as the current input value? If so, the signal has stabilized: Register a successful read. If the signal is different, you have detected noise. Wait for the next interrupt, register nothing.
This is a very basic debounce, but the methodology doesn't change that much as they become more advanced.
I hope this helps answer your question.