Input Signal Edge Detection using Software
In the digital design, sometimes we need to detect the transition from '0' to '1' or '1' to '0' of a signal.
For example, suppose you design a counter with a input pin connected to a push button. When you push the button every time, the counter will count by one. The circuit diagram is shown as Figure 1.
Figure 1: Digital Counter
In other words, the counter counts the number of times the switch transitions from open to close state. The pseudoscope is shown as follows:
if (SW1 from open to close) counter ++;
Some microcontrollers provide edge detect circuitry, and you can configure edge detection on the desired pins. In this example, we configure it on PA3. If the edge is detected, a flag will be set in the status register, or trigger an interrupt to the CPU. In your C code, you just need to check the status register, or implement an ISR function to increase the counter value. But here, we only discuss how to implement edge detection using software.
Implementation of Edge Detection Algorithms
Figure 2: Rising Edge and Falling Edge
If a digital signal rises from low (0) to high (1), this transition is called "rising edge". On the contrary, if it drop from high to low, it is called "falling edge". Each transition has two states — previous state and current state. Current state of input pins can be read from the port DATA register, but the previous state must be stored in a variable.
Every time you read the current input state, compare it to the previous state value. If current state is not equivalent to previous state, a transition had occurred. Before the next cycle starts to read the current input state, the previous state needs to be updated by the current state.
Implementation of Edge Detection in C
There are two methods to implement software edge detection:
- Simple if statement
- State machine
Figure 3: Falling Edge
The falling edge occurs when the signal drops from high (1) to low (0). Hence, if the previous state is high and the current state is low, then the falling edge had just happened.
For example, the following system will toggle LED when the user presses the SW1. Its means the LED will be lit when you press SW1. If user presses the SW1 again, the LED will be turned off.
Figure 4: An Example of Detecting the Falling Edge
Simple if Statement
In the code, two variables (swState, swPreState) are needed to store the previous and current states for SW1 button.
- Read current state of the SW1 button in variable swState.
- If previous state (swPreState) is logic 1 (that means the SW1 button was released) and current state (swState) is logic 0 (the SW1 button is pressed), the SW signal is on falling edge, and then changes the LED status.
- Update current state (swState) to previous state (swPreState), then go to step 1 to check the SW1 button again.
State machine also can be use in this case.
Figure 6: State Machine for Falling Edge Detection