0
0
Embedded Cprogramming~5 mins

Input capture mode in Embedded C

Choose your learning style9 modes available
Introduction
Input capture mode helps you measure the exact time when an event happens on a pin, like when a button is pressed.
You want to measure how long a button is pressed.
You need to record the time of a signal change, like a sensor output.
You want to measure the speed of a rotating wheel using a sensor.
You want to detect the exact moment a signal goes high or low.
Syntax
Embedded C
void InputCapture_Init(void) {
    // Configure timer for input capture
    // Set capture edge (rising/falling)
    // Enable input capture interrupt
}

void InputCapture_ISR(void) {
    // Read captured timer value
    // Process the captured time
    // Clear interrupt flag
}
Input capture uses a timer peripheral to record the timer value when an input event occurs.
You usually set which edge (rising or falling) triggers the capture.
Examples
Initialize input capture to record time when signal rises.
Embedded C
void InputCapture_Init(void) {
    // Set timer prescaler
    // Configure input capture on channel 1
    // Capture on rising edge
    // Enable interrupt
}
Interrupt service routine reads the captured timer value and clears the interrupt.
Embedded C
void InputCapture_ISR(void) {
    uint16_t capturedValue = TIMER_CAPTURE_REGISTER;
    // Use capturedValue to calculate pulse width
    CLEAR_INTERRUPT_FLAG();
}
Sample Program
This program simulates input capture by initializing, then simulating an event that triggers the interrupt and prints the captured timer value.
Embedded C
#include <stdint.h>
#include <stdio.h>

volatile uint16_t captured_time = 0;

// Simulated timer capture register
uint16_t TIMER_CAPTURE_REGISTER = 1234;

// Simulated interrupt flag
int INTERRUPT_FLAG = 0;

void InputCapture_Init(void) {
    // Normally hardware setup here
    printf("Input capture initialized.\n");
}

void InputCapture_ISR(void) {
    captured_time = TIMER_CAPTURE_REGISTER;
    INTERRUPT_FLAG = 0; // Clear interrupt
    printf("Captured time: %u\n", captured_time);
}

int main(void) {
    InputCapture_Init();
    // Simulate an input capture event
    INTERRUPT_FLAG = 1;
    if (INTERRUPT_FLAG) {
        InputCapture_ISR();
    }
    return 0;
}
OutputSuccess
Important Notes
Input capture depends on hardware timers and interrupts, so it may look different on various microcontrollers.
Always clear the interrupt flag inside the ISR to avoid repeated triggers.
Summary
Input capture mode records the timer value when an input event happens.
It helps measure timing of signals without missing events.
You set which edge triggers the capture and handle the event in an interrupt.