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 an 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 in Figure 1.

SoftwareEdgeDectector s
Figure 1
: Digital Counter

In other words, the counter counts the number of times the switch transitions from open to the closed state. The pseudoscope is shown as follows:

if (SW1 from open to close) counter ++;

Some microcontrollers provide edge detection 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 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 the 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 drops from high to low, it is called a "falling edge." Each transition has two states — previous state and current state. The 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 the current state is not equivalent to the 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:

  1. Simple if statement
  2. State machine