You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用XC8编译器开发PIC16时,C语言ssscanf无法捕获第二个参数

PIC16 XC8开发中ssscanf读取uint8_t变量的格式符问题

问题描述

使用MPLAB工具、XC8编译器为PIC16编写C代码,需从类似"115200,8,N,1"的字符串中提取波特率配置信息(奇偶校验N/O/E对应枚举值0/1/2)。编写的代码如下:

#include <stdint.h>

int main(void)
{
    uint32_t baudrate;
    uint8_t databits, parity, stopbits;

    char *input = "115200,8,0,1";

    sscanf(input, "%lu,%u,%u,%u", &baudrate, &databits, &parity, &stopbits); 
    printf("%lu - %u - %u - %u\n", baudrate, databits, parity, stopbits);

    return 0;
}

期望输出:

>> 115200 - 8 - 0 - 1

实际输出:

>> 115200 - 0 - 0 - 1

ssscanf始终无法正确捕获第二个参数(databits),值始终为0,怀疑是格式标识符使用错误,寻求正确的格式符。

问题原因与解决方法

在XC8编译器中,uint8_t的本质是unsigned char,而%u是对应unsigned int的格式符。直接使用%u读取uint8_t变量会因为类型不匹配导致内存读写错误,从而无法正确获取值。

正确的格式符应使用%hhu,这是C99标准中专门用于读取unsigned char类型的格式符,XC8编译器支持该格式符。

修正后的代码

#include <stdint.h>
#include <stdio.h>  // 必须包含stdio.h以确保sscanf、printf正常工作

int main(void)
{
    uint32_t baudrate;
    uint8_t databits, parity, stopbits;

    char *input = "115200,8,0,1";

    // 使用%hhu读取uint8_t类型变量
    sscanf(input, "%lu,%hhu,%hhu,%hhu", &baudrate, &databits, &parity, &stopbits); 
    printf("%lu - %u - %u - %u\n", baudrate, databits, parity, stopbits);

    return 0;
}

扩展:处理字符型奇偶校验(N/O/E)

如果输入字符串中的奇偶校验是字符形式(如"115200,8,N,1"),还需要额外添加字符转枚举值的逻辑,示例代码如下:

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

// 定义奇偶校验枚举类型
typedef enum {
    PARITY_NONE = 0,
    PARITY_ODD = 1,
    PARITY_EVEN = 2
} parity_t;

int main(void)
{
    uint32_t baudrate;
    uint8_t databits, stopbits;
    parity_t parity;
    char parity_char[2];  // 存储单个字符加字符串结束符

    char *input = "115200,8,N,1";

    // 用%1s读取单个奇偶校验字符
    sscanf(input, "%lu,%hhu,%1s,%hhu", &baudrate, &databits, parity_char, &stopbits); 
    
    // 将字符转换为枚举值
    if (strcmp(parity_char, "N") == 0) {
        parity = PARITY_NONE;
    } else if (strcmp(parity_char, "O") == 0) {
        parity = PARITY_ODD;
    } else if (strcmp(parity_char, "E") == 0) {
        parity = PARITY_EVEN;
    } else {
        // 处理无效输入,默认设为无校验
        parity = PARITY_NONE;
    }

    printf("%lu - %u - %u - %u\n", baudrate, databits, (uint8_t)parity, stopbits);

    return 0;
}

内容的提问来源于stack exchange,提问作者GeoReb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 10:17:40