#include <stdio.h>
#include <string.h>

// 将字符串分割成单个字符,并存储到output数组中
void splitString(const char* input, char* output[], int* count) {
    *count = strlen(input);
    for (int i = 0; i < *count; i++) {
        output[i] = malloc(2); // 为每个字符分配2字节空间
        snprintf(output[i], 2, "%c", input[i]); // 将字符格式化输出到output[i]
    }
}

// 循环识别颜色,直到识别到预期颜色
void recognizeColor(int color, int expectedColor) {
    while (1) {
        if (color == expectedColor) {
            print(1); // 假设print函数用于输出识别结果
            break;
        } else {
            // 识别程序
            HAL_UART_Transmit(&huart2, (uint8_t*)message7, strlen(message7), 100);
            HAL_UART_Receive(&huart2, &color, 1, HAL_MAX_DELAY);
        }
    }
}

int main(void) {
    uint8_t receiveData[7];
    uint8_t receiveDatacolor;

    int a, b, c, d, e, f;
    char* ste[7];

    // 接收串口数据
    HAL_UART_Receive(&huart2, receiveData, 7, HAL_MAX_DELAY);

    // 对接收的数据进行分割
    splitString((const char*)receiveData, ste, &f);

    // 将分割后的字符串转换为整数
    a = atoi(ste[0]);
    b = atoi(ste[1]);
    c = atoi(ste[2]);
    d = atoi(ste[4]);
    e = atoi(ste[5]);
    f = atoi(ste[6]);

    // 第一次识别
    HAL_UART_Transmit(&huart2, (uint8_t*)message7, strlen(message7), 100);
    HAL_UART_Receive(&huart2, &receiveDatacolor, 1, HAL_MAX_DELAY);
    int color = (int)receiveDatacolor;
    recognizeColor(color, a);

    // 第二次识别
    HAL_Delay(1000);
    HAL_UART_Transmit(&huart2, (uint8_t*)message7, strlen(message7), 100);
    HAL_UART_Receive(&huart2, &receiveDatacolor, 1, HAL_MAX_DELAY);
    color = (int)receiveDatacolor;
    recognizeColor(color, b);

    // 第三次识别
    HAL_Delay(1000);
    HAL_UART_Transmit(&huart2, (uint8_t*)message7, strlen(message7), 100);
    HAL_UART_Receive(&huart2, &receiveDatacolor, 1, HAL_MAX_DELAY);
    color = (int)receiveDatacolor;
    recognizeColor(color, c);

    return 0;
}
C语言字符串分割与串口颜色识别

原文地址: http://www.cveoy.top/t/topic/hx6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录