Embedded Software – Microcontroller – Multi-Sensor Fusion Algorithm C Program

Core Design Concepts

  1. 1. Filter out invalid data: Exclude out-of-range values and sensor failures to prevent bad data from affecting results;
  2. 2. Branch processing based on valid data count: Dynamically adjust the fusion strategy according to the number of valid sensors, balancing accuracy and robustness;
  3. 3. Lightweight and efficient algorithm: Uses bubble sort + case-based calculations, no complex mathematical models required, easily portable to embedded devices.
/************************ Temperature Sensor Data Fusion Algorithm - PC Test Version ************************//* Applicable scenarios: Windows/Linux computers, compiled and tested with GCC/MinGW, no hardware required *//* Features: Can be compiled and run directly, results printed via terminal for easy algorithm logic verification *//**********************************************************************************/#include <stdio.h>#include <stdint.h>#include <string.h>/************************ Configurable Parameters (modify as needed) ************************/#define TEMP_MIN        -40.0f   // Minimum temperature (℃)#define TEMP_MAX        125.0f   // Maximum temperature (℃)#define SENSOR_NUM      4        // Total number of sensors (fixed at 4)#define TEMP_MAGIC      -200.0f  // Invalid data magic value/************************ Utility Functions ************************//** * @brief Bubble sort (ascending) - processes valid temperature array * @param arr Array to be sorted * @param len Length of the array */static void temp_sort(float *arr, uint8_t len){    uint8_t i, j;    float temp;    for (i = 0; i < len - 1; i++) {        for (j = 0; j < len - 1 - i; j++) {            if (arr[j] > arr[j + 1]) {                temp = arr[j];                arr[j] = arr[j + 1];                arr[j + 1] = temp;            }        }    }}/** * @brief Filter out invalid/out-of-range temperature data * @param raw_data Raw data from 4 sensors * @param valid_data Output array for valid data * @return Number of valid data */static uint8_t filter_invalid_temp(const float *raw_data, float *valid_data){    uint8_t i, valid_cnt = 0;    for (i = 0; i < SENSOR_NUM; i++) {        if (raw_data[i] != TEMP_MAGIC &&             raw_data[i] >= TEMP_MIN &&             raw_data[i] <= TEMP_MAX) {            valid_data[valid_cnt++] = raw_data[i];        }    }    return valid_cnt;}/************************ Core Fusion Algorithm ************************//** * @brief Fusion of 4-channel temperature sensor data (PC test only) * @param raw_temp 4-channel raw temperature data (input) * @param result Fused temperature result (output) * @return 0: success, -1: no valid data, -2: parameter error */int temp_fusion_algorithm(const float raw_temp[SENSOR_NUM], float *result){    float valid_temp[SENSOR_NUM] = {0};    uint8_t valid_cnt = 0;    // Parameter validation    if (raw_temp == NULL || result == NULL) {        fprintf(stderr, "[ERROR] raw_temp or result is NULL\n");        return -2;    }    // Filter invalid data    valid_cnt = filter_invalid_temp(raw_temp, valid_temp);    if (valid_cnt == 0) {        fprintf(stderr, "[ERROR] No valid temperature data\n");        return -1;    }    // Branch fusion    switch (valid_cnt) {        case 1:            *result = valid_temp[0];            break;        case 2:            *result = (valid_temp[0] + valid_temp[1]) / 2.0f;            break;        case 3:            temp_sort(valid_temp, valid_cnt);            *result = valid_temp[1];            break;        case 4:            temp_sort(valid_temp, valid_cnt);            *result = (valid_temp[1] + valid_temp[2]) / 2.0f;            break;        default:            fprintf(stderr, "[ERROR] Invalid valid data count\n");            return -1;    }    // Print result    printf("[SUCCESS] Valid count: %d, Fusion result: %.2f℃\n", valid_cnt, *result);    return 0;}/************************ Main Function (directly run for testing) ************************/int main(void){    printf("===== Temperature Fusion Algorithm Test =====\n");    // Test scenario 1: 4 valid (including 1 abnormal value)    float raw1[4] = {25.3f, 24.9f, 25.1f, 30.0f};    float res1 = 0.0f;    printf("\nTest Scene 1 (4 valid data): ");    temp_fusion_algorithm(raw1, &res1);  // Expected: 25.20℃    // Test scenario 2: 3 valid (including 1 invalid value)    float raw2[4] = {26.5f, TEMP_MAGIC, 26.7f, 26.6f};    float res2 = 0.0f;    printf("\nTest Scene 2 (3 valid data): ");    temp_fusion_algorithm(raw2, &res2);  // Expected: 26.60℃    // Test scenario 3: 1 valid (including 2 invalid values + 1 out-of-range)    float raw3[4] = {TEMP_MAGIC, 27.2f, TEMP_MAGIC, 150.0f};    float res3 = 0.0f;    printf("\nTest Scene 3 (1 valid data): ");    temp_fusion_algorithm(raw3, &res3);  // Expected: 27.20℃    // Test scenario 4: no valid data    float raw4[4] = {TEMP_MAGIC, 160.0f, -50.0f, TEMP_MAGIC};    float res4 = 0.0f;    printf("\nTest Scene 4 (0 valid data): ");    temp_fusion_algorithm(raw4, &res4);  // Expected: error    printf("\n===== Test End =====\n");    return 0;}

Key Design Highlights

1. Maximum Robustness

  • Parameter validation: Prevents program crashes due to null pointers;
  • Invalid data filtering: Isolates bad data caused by sensor failures and transmission errors;
  • Full scenario coverage: Even if only 1 sensor is valid, the system can still output data normally without crashing.

2. Balance of Accuracy and Efficiency

  • When 4 channels are valid: Exclude extreme values (maximum/minimum) to avoid random interference (e.g., wind, local heating);
  • When 3 channels are valid: Median strategy is more robust against outliers than the average;
  • Lightweight algorithm: Bubble sort + simple arithmetic operations, low memory usage, easily portable to embedded devices like STM32, Arduino.

3. Easy Maintenance and Expandability

  • Centralized parameter definition: Temperature range and number of sensors can be quickly modified;
  • Modular functions: Filtering, sorting, and fusion are separated, allowing for future replacement of sorting algorithms (e.g., quicksort) or optimization of fusion strategies (e.g., weighted average).

Porting and Testing Recommendations

  • Embedded platform: Directly copy the code, replace <span>fprintf</span> with serial print functions (e.g., <span>printf</span>, <span>HAL_UART_Transmit</span>);
  • Testing scenarios:
  1. Normal scenario: All 4 data are valid, verify the result is the average of the middle two;
  2. Abnormal scenario: Intentionally let 1 sensor output an out-of-range value, verify it is filtered;
  3. Extreme scenario: Only 1 sensor is valid, verify the system outputs data normally.

Conclusion

This 4-channel temperature sensor data fusion solution, centered on “simplicity, reliability, and efficiency,” implements temperature monitoring in embedded systems with a logic of “filtering – sorting – case-based fusion,” balancing accuracy and interference resistance. Whether for environmental temperature collection in industrial control or room temperature monitoring in smart homes, it can be directly ported and flexibly adjusted according to actual needs.

If you need to adapt to more sensors (e.g., 8 channels), optimize algorithm accuracy (e.g., introducing Kalman filtering), or have specific scenario questions, feel free to discuss in the comments!

Leave a Comment