Kmdf Hid Minidriver For Touch I2c Device Calibration Info
For a KMDF HID minidriver targeting an I2C touch device, calibration is typically handled at the operating system level via standard Windows tools or by injecting specific registry parameters that the driver reads to modify incoming raw coordinates. 1. Identify Calibration Registry Path
Windows stores calibration data for touch devices in a specific registry location. If your driver needs to apply a static offset or scale factor at boot, it should query this path or its own device parameters.
Registry Path: HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\TOUCH\CalibrationData.
Driver Implementation: Use WdfRegistryOpenKey and WdfRegistryQueryValue in your EvtDeviceAdd or a specialized initialization function to read these values. 2. Implement Coordinate Transformation
In your minidriver’s HID Report processing logic, apply the calibration math before passing the data to the HID class driver. Read Raw Data: Receive the I2C packet containing Xrawcap X sub r a w end-sub Yrawcap Y sub r a w end-sub
Apply Transformation: Use a linear transformation matrix to adjust for rotation, inversion, or scaling issues. Inversion Example: If the -axis is flipped,
Coordinate Mapping: Ensure the coordinates match the logical range defined in your HID Report Descriptor (e.g., 0 to 4095). 3. Use Windows Native Calibration Tool
The preferred method for user-driven calibration is the built-in Windows tool. This generates the necessary registry entries that the OS uses to map HID inputs to screen pixels. Process: Open Control Panel. Select Tablet PC Settings. Click Calibrate under the Display tab.
Resetting: If calibration becomes corrupted, use the Reset button in the same menu to clear the registry data and return to the driver's default mapping. 4. Verify HID Report Descriptors
Calibration issues are often caused by mismatches in the HID Report Descriptor. Ensure your descriptor accurately defines the physical and logical extents of the touch surface.
Logical Maximum: Must match the highest coordinate value your firmware can produce.
Physical Maximum: Should represent the actual physical size (e.g., in millimeters) to help Windows scale the input correctly. 5. Troubleshooting Common Issues Uninstalled KMDF HID Minidriver for Touch I2C Device
The KMDF (Kernel-Mode Driver Framework) HID minidriver serves as the critical communication bridge between a Touch I2C controller and the Windows Input Stack. When dealing with touch hardware, raw electrical signals must be translated into precise screen coordinates. Without proper calibration, a user’s tap may register inches away from the actual contact point.
This guide explores the architecture, implementation, and calibration strategies for developing a KMDF HID minidriver for I2C touch devices. 1. Architecture of a HID I2C Minidriver
In the Windows Driver Model, a HID minidriver does not act alone. It fits into a specific stack:
HID Class Driver (mshidkmdf.sys): Provided by Microsoft, this handles the heavy lifting of HID report parsing and interfacing with the operating system.
Your KMDF Minidriver: This is the "glue" code. It talks to the I2C controller using the SPB (Simple Peripheral Bus) framework and reports data back to the HID Class Driver.
I2C Controller Driver: Manages the physical clock and data lines (SDA/SCL) on the SoC.
Your primary goal is to map the specific I2C registers of your touch hardware into standard HID Input Reports. 2. Defining the HID Report Descriptor kmdf hid minidriver for touch i2c device calibration
Before calibration can happen, the OS must understand what the device is. The HID Report Descriptor defines the touch surface's capabilities:
Logical Minimum/Maximum: The raw range of the ADC (e.g., 0 to 4095).
Physical Minimum/Maximum: The actual size of the panel in millimeters. Usage Page: Digitizers (0x0D). Usage: Touch Screen (0x04).
Calibration Tip: If your hardware raw values don't match the aspect ratio of the screen, the HID descriptor is where you first define the "Logical" boundaries to prevent initial distortion. 3. Implementing Calibration Logic
Calibration for touch devices generally addresses three issues: Scaling, Offset, and Orientation. Scaling and Resolution Mapping
Most I2C touch controllers output raw coordinates based on the internal resolution of the touch IC (e.g., 12-bit depth). To calibrate this in the minidriver:
Capture Raw Data: Read the X and Y bytes from the I2C register.
Apply Gains: Multiply the raw value by a calibration factor if the active touch area is smaller than the sensor grid.
Normalization: Convert the raw data to the Logical Maximum defined in your HID descriptor. Offset Correction
Mechanical misalignment can cause a constant shift in coordinates. Formula: Calculated_X = (Raw_X - X_Offset)
Implementation: These offsets should ideally be stored in the Registry or an ACPI _DSD (Device Specific Data) method so the driver can load them at boot without hardcoding values. Axis Inversion and Swapping
Depending on how the touch panel is mounted (0°, 90°, 180°, 270°), you may need to: Swap X and Y. Invert an axis: Final_X = Logical_Max_X - Calculated_X. 4. Handling Interrupts and Data Retrieval
Touch devices are interrupt-driven. Your KMDF driver must implement an EvtInterruptIsr or a Passive-level interrupt handling strategy:
Interrupt Fires: The touch hardware pulls the GPIO line low.
Work Item/DPC: The driver schedules a read operation over the I2C bus.
I2C Read: Retrieve the "Touch Digit" packet (usually containing Status, X-coord, Y-coord, and Contact ID).
Calibration Transformation: Apply the math discussed in Section 3.
Complete the Request: Send the processed HID report up the stack via WdfRequestComplete. 5. Storing Calibration Data For a KMDF HID minidriver targeting an I2C
Hardcoding calibration values is poor practice. Use one of these three methods for a professional KMDF implementation:
Registry Keys: Use WdfDeviceOpenRegistryKey. This allows user-space calibration tools (like a "Calibrate your screen" app) to write values that the driver reads during EvtDeviceSelfManagedIoInit.
ACPI Tables: For embedded systems, the BIOS/Firmware can pass calibration constants via the _DSD method in the ACPI table.
Configuration Files: Some drivers read a .ini or .bin file from System32\Drivers, though this is less common in modern KMDF designs. 6. Testing and Validation
Once the minidriver is deployed, use these tools to verify calibration:
HIDView: A tool to inspect the raw HID reports reaching the OS.
Digitizer Calibration Tool (Windows): Found in the Control Panel, this allows for a 4-point or 16-point calibration that creates an overlay transformation in the OS.
Input Test Tool: Part of the Windows Hardware Lab Kit (HLK), used to ensure the device meets "Windows Touch" certification standards for linearity and latency. Conclusion
Developing a KMDF HID minidriver for a touch I2C device requires a deep understanding of both the SPB framework and the HID specification. By implementing robust calibration logic—handling scaling, offsets, and orientation within the driver—you ensure a seamless and intuitive user experience. Always prioritize moving calibration constants out of the code and into the firmware or registry to allow for hardware variance across different production batches.
To help you refine the calibration logic, would you like to see a C++ code snippet for the coordinate transformation function or a sample HID Report Descriptor for a multi-touch device?
2.1 The HID Stack Overview
- HID Class Driver (
hidclass.sys): Manages HID collections, reports, and device topology.
- HID Transport Minidriver: A lower-level driver that communicates with the physical hardware (USB, I2C, Bluetooth, etc.).
- HIDI2C Driver (
hidi2c.sys): Microsoft’s built-in minidriver for I2C HID devices.
In most cases, hidi2c.sys is sufficient. However, it does NOT support custom calibration. It forwards raw HID reports directly from the I2C device to the HID class driver. To inject calibration, we must replace or layer our own KMDF HID Minidriver.
6.1 Driver Verification
- Use WDK Device Console (
devcon) to install TouchCalibMini.sys on a test machine.
- Enable KMDF Verifier to catch locking and I/O errors.
- Use I2C Spy logic analyzer to ensure raw I2C reads are correct.
4.6 Dynamic Calibration – IOCTL Interface
To support calibration changes at runtime (e.g., from a user-mode calibration app), you implement a custom IOCTL handler:
NTSTATUS TouchCalibEvtIoDeviceControl(WDFQUEUE Queue, WDFREQUEST Request, ...)
switch (ControlCode)
case IOCTL_SET_TOUCH_CALIBRATION:
// Read calibration matrix from user buffer
WdfRequestRetrieveInputBuffer(Request, sizeof(CALIB_PARAMS), ¶ms, &length);
// Store in device context safely
WdfDeviceGetDeviceContext(Device)->CalibParams = updatedParams;
break;
The user-mode calibration tool can then call DeviceIoControl to update coefficients without a driver reload.
Part 8: Deployment and Certification
Why This Feature is Critical
- Reliability: I2C Touch devices are often connected via internal buses that reset during sleep/wake cycles. Without this feature, the touch screen might lose sensitivity or accuracy after the laptop lid is closed and reopened.
- Windows Hardware Compatibility: Microsoft's HID I2C specifications encourage storing calibration data in ACPI tables (
_DSM) or utilizing a Registry backing store. Implementing this makes the driver compliant with modern Windows design principles.
- User Experience: It eliminates the need for end-users to manually run calibration tools (which are often inaccurate compared to factory data).
KMDF HID Minidriver for Touch I2C Device Calibration
Touchscreens and other capacitive/precision touch controllers are now standard in laptops, tablets, kiosks, and embedded systems. Making those devices feel smooth and accurate across different units, environments, and physical tolerances requires reliable calibration. For Windows drivers that expose touch controllers through the HID class and communicate over I2C, a KMDF HID minidriver is a common and robust pattern. This article explains the architecture, calibration considerations, and practical implementation patterns for building a KMDF HID minidriver that supports touch I2C device calibration — focusing on reliability, maintainability, and a solid user experience.
Contents
- Why HID + KMDF for touch I2C devices
- Calibration goals and challenges
- Driver architecture overview
- Initialization and hardware probing
- Exposing HID reports and handling IO
- Calibration data: formats, storage, and versioning
- Calibration workflows (factory, field, automatic)
- Implementing calibration routines in KMDF
- Handling power, suspend/resume, and system events
- Validation, diagnostics, and manufacturing test
- Security, robustness and update considerations
- Summary checklist
Why HID + KMDF for touch I2C devices
- HID is the native Windows class for human interface devices; using HID means built-in support for input processing, cursor/touch composition, and compatibility with Windows gestures and APIs.
- KMDF (Kernel-Mode Driver Framework) provides a structured, safer model for kernel drivers with event-driven callbacks, queuing, and automatic resource lifetime management.
- For I2C-connected touch controllers, a KMDF HID minidriver sits on top of the SPB (Simple Peripheral Bus) / I2C stack and translates between device registers/transactions and HID reports Windows expects.
- A minidriver lets you implement device-specific initialization, calibration, and power handling while delegating standard HID protocol handling to the framework and HID class driver.
Calibration goals and challenges
- Accuracy: Touch coordinates must map reliably to screen coordinates with low error across the active area.
- Repeatability: Calibration should be stable across temperature, supply variation, and mechanical tolerances.
- Performance: Calibration actions (and their storage/retrieval) must not introduce visible latency in normal input processing.
- Persistence and compatibility: Calibration data must survive reboots, driver updates, and minor firmware changes while allowing safe migration.
- User & factory workflows: Support one-time factory calibration; support field recalibration (user/maintenance); possibly auto-calibration to compensate for drift.
- Minimal system impact: Calibration should not block other devices, should behave correctly during suspend/resume, and must be robust against partial failures.
Driver architecture overview
- Layers:
- I2C/SPB client (WDFQUEUE for synchronous/async transfers)
- Device initialization / firmware loader (if required)
- HID minidriver layer (HID descriptor, report descriptor, report parsing)
- Calibration module (calibration math, storage, versioning, apply/rollback)
- Power/state management hooks
- Diagnostics/logging and vendor commands (for manufacturing tools)
- Use KMDF constructs:
- WDFDEVICE for device object
- WDFQUEUE(s) for HID read/write/report handling and for internal calibration requests
- WDFWORKITEM or KMDF DPCs for non-blocking calibration computations
- WDF I/O targets for the SPB/I2C target
Initialization and hardware probing
- Probe sequence:
- Create WDFDEVICE and open a WDFIOTARGET to the SPB/I2C peripheral.
- Read device ID/firmware version to ensure compatibility.
- Query controller capabilities (resolution, max contacts, axis range, touch type).
- Load (or generate) HID descriptor/report descriptor dynamically if device capabilities vary.
- Read persisted calibration data (from nonvolatile device memory and/or registry).
- Validate calibration version/CRC; if invalid, fall back to safe defaults or trigger recalibration.
- Best practice: Keep probe short; defer heavier work (firmware loads, complex self-tests) to a low-priority worker so PnP/boot isn't delayed.
Exposing HID reports and handling IO
- Build a HID report descriptor that matches device capabilities: multi-touch, tips, pressure, gestures, tilt if supported.
- KMDF HID minidriver typically implements:
- EvtDevicePrepareHardware / EvtDeviceReleaseHardware
- EvtDeviceD0Entry / EvtDeviceD0Exit for power transitions
- HID requests handling: Create standard IO queues for IOCTLs (HID read/feature/report IO)
- Handling input:
- Input reports should be produced as promptly as possible from controller interrupts or polling.
- Calibration transforms should be applied in-path just before constructing the HID input report so Windows receives corrected coordinates.
- Keep the transform low-cost (integer arithmetic or small LUT) to avoid adding latency to each report.
- Feature reports:
- Expose calibration controls via HID feature reports or vendor-defined IOCTLs for factory/maintenance tools.
- Include commands for: start calibration, commit calibration, get calibration status, rollback, and diagnostic logs.
Calibration data: formats, storage, and versioning
- Decide where calibration is stored:
- Device NV memory (EEPROM/flash) is ideal for portability across OS installations.
- Registry (HKLM\System\CurrentControlSet\Services\…\Parameters or a vendor subkey) can be used when device NV is limited.
- Hybrid: primary on-device, backup in registry for recovery.
- Data format:
- Include metadata: version, timestamp, calibration algorithm id, CRC/checksum, and possibly hardware identifiers.
- Store transformation parameters (e.g., affine matrix coefficients), per-axis gains/offsets, touch-specific compensation maps, or a small calibration LUT/grid.
- Versioning and migration:
- Maintain a version number; on driver load, validate and migrate older formats programmatically.
- Always retain the ability to revert to the previous known-good calibration in case a migration fails.
Common calibration models
- Affine transform: A 3x3 matrix (usually 2x3 sufficient) to map raw coordinates to screen coordinates. Good for homogeneous, linear misalignments.
- Piecewise linear / polynomial: Use when nonlinearity exists (e.g., screen flex or lens distortion).
- Grid-based LUT with interpolation: Divide the surface into a grid, store offsets per cell, and bilinear interpolate — useful for spatially varying errors.
- Per-contact compensation: For some controllers, calibration may include touch-size or pressure thresholds per contact.
Calibration workflows (factory, field, automatic)
- Factory calibration:
- Highly controlled environment, use precise patterns and high sampling.
- Save final calibration to device NV with metadata and sign-off.
- Expose a vendor feature report or tool to read/verify calibration data.
- Field/user calibration:
- Simpler UX (tap targets, crosshairs). Collect fewer samples and compute a robust transform (often affine).
- Optionally blend new calibration with stored one to avoid large jumps (smooth transition).
- Automatic/self-calibration:
- Opportunistic background recalibration using user interactions if certain conditions are met (low-motion, calibration-heavy events).
- Be conservative: avoid degrading accuracy by overfitting transient user behavior.
- Require confidence metrics and a rollback mechanism.
Implementing calibration routines in KMDF
- Collection:
- For interactive calibration, queue sample collection in a WDFQUEUE and process on a WDFWORKITEM.
- Debounce and filter noisy samples (median filters, outlier rejection).
- Computation:
- Implement calibration math in a small, testable module (C/C++) that returns both parameters and confidence metrics.
- Use fixed-point arithmetic if needed for kernel efficiency; however, small floating-point use is acceptable if consistent and tested carefully.
- Applying:
- Apply transform just before generating HID input.
- Keep a copy of active parameters in WDFDEVICE context with appropriate synchronization (spinlock or WDFWAITLOCK) for per-input access.
- Commit:
- Provide an atomic write flow to persist calibration: write to device NV and then to registry backup; confirm CRC.
- If NV writes are slow or can fail, use async workers and present an interim state to minimize blocking.
- Rollback:
- Store previous calibration until new persistent write succeeds; allow explicit rollback via feature report.
Handling power, suspend/resume, and system events
- Calibration must survive suspend/resume:
- Re-apply calibration after resume if hardware resets during S3/S4.
- Re-validate device NV storage at resume and fall back if corruption detected.
- Low-power modes:
- If controller calibrations depend on supply or temperature, consider triggers to revalidate when thresholds change.
- Driver updates:
- When updating driver/firmware, run migration code that preserves calibration or migrates safely; always keep a recovery path.
Validation, diagnostics, and manufacturing test
- Provide diagnostics:
- Feature reports or vendor IOCTLs to dump raw samples, active calibration parameters, and confidence metrics.
- Support a manufacturing test mode with higher sampling and logs for QA.
- Logging:
- Use WPP tracing for detailed logs without impacting performance in production; keep verbose tracing gated by debug builds or registry flags.
- Automated tests:
- Unit test the calibration math (affine solve, interpolation, outlier rejection).
- Integration test on reference hardware with known offsets.
- Fuzz raw input to ensure stability and no crashes.
Security, robustness, and update considerations
- Input validation:
- Treat all device and host-supplied data as untrusted; validate sizes, ranges, and capability reports.
- Atomicity:
- Make persistence atomic: write new calibration to a temp slot, validate, then flip the active pointer.
- Firmware authentication:
- If calibration depends on firmware features, ensure firmware updates are authenticated and compatible.
- Driver signing and update:
- When changing calibration formats, follow a careful rollout strategy (driver fallback, migration tools).
- Least privilege:
- Avoid exposing dangerous vendor operations to unprivileged user-mode apps; gate factory/diagnostic commands behind signed tools or require admin privileges.
Example: Simple affine calibration implementation (conceptual)
- Collect at least three non-collinear sample pairs (raw_x, raw_y) ↔ (screen_x, screen_y).
- Solve for transform:
- screen_x = a00raw_x + a01raw_y + a02
- screen_y = a10raw_x + a11raw_y + a12
- Use a small linear solver (least-squares for more samples) in the kernel or compute in user-space tool and send results via a feature report.
- Store six parameters plus version and CRC.
UX tips for calibration
- Keep interactive calibration short (3–9 tap points).
- Use clear visual targets and provide immediate feedback for each tap.
- Offer an “auto-calibrate” or “recalibrate” option in driver settings for field service.
- Report confidence and an easy way to revert if user perceives worse performance.
Manufacturing and field tools
- Provide a cross-platform calibration tool that:
- Communicates via HID feature reports or a vendor-signed utility.
- Automates sample collection and validation.
- Signs and commits calibration with metadata.
- Include an automated checklist and expected metrics for factory acceptance.
Summary checklist
- Implement robust probe with capability query and rapid failover.
- Apply calibration transforms at input-report time with minimal overhead.
- Store calibration persistently with versioning, CRCs, and rollback.
- Provide feature reports for factory/field calibration and diagnostics.
- Ensure safe suspend/resume and driver update behavior.
- Unit-test math and perform integration tests on hardware.
- Expose guarded vendor operations and prevent accidental misuse.
Final note
A KMDF HID minidriver for an I2C touch controller succeeds when it combines low-latency input processing with robust and easily maintainable calibration infrastructure. Prioritize clear data formats, atomic persistence, good diagnostics, and conservative automatic calibration so the device stays accurate and dependable across its lifetime.
Based on your request, the most valuable feature to implement for a KMDF HID Minidriver for a Touch I2C device is a Driver-Managed Factory Calibration Storage & Restoration Mechanism.
9.2 Checking HID Descriptor
Use Device Manager → Human Interface Devices → Properties → Details → "Hardware IDs" to confirm driver attachment.
Use HIDClient or HidDig tool to dump feature reports.