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

Arduino蓝牙键盘模拟器发送异常ASCII字符问题求助

问题解决:设备2蓝牙发送字母显示异常

问题原因

核心是变量类型不匹配+数组越界:

  • 原代码中newMaxVal作为整数索引,用来从numbers数组(仅10个元素,索引0-9)取字符。
  • 给设备2的newMaxVal直接赋值'q'这类字符时,实际是把字符的ASCII码(比如'q'=113)存入整数变量,后续用numbers[newMaxVal]会直接越界读取内存垃圾值,也就是你看到的“|”。
  • 赋值数字5-9时看似正常,是因为越界后偶然读到了对应字符,属于错误写法。

修正方案(两种任选,推荐方案1)

方案1:复用现有numbers数组(简洁不易错)

直接给设备2的索引加偏移量,利用数组里已有的字母:

if(boxNumber == 2) {
    // 设备2用数组第5-9位(索引5-9),对应q/w/e/r/t
    newMaxVal += 5;
}
// 后续发送逻辑不变,仍然用 numbers[newMaxVal] 获取要发送的字符

方案2:直接指定发送字符(修正类型逻辑)

如果要保留逐个判断的写法,单独定义字符变量存储要发送的内容,避免混淆整数索引和字符:

char sendChar; // 新增字符变量存要发送的内容
if(boxNumber == 2) {
    if(newMaxVal == 0) {
        sendChar = 'q';
    } else if(newMaxVal == 1) {
        sendChar = 'w';
    } else if(newMaxVal == 2) {
        sendChar = 'e';
    } else if(newMaxVal == 3) {
        sendChar = 'r';
    } else if(newMaxVal == 4) {
        sendChar = 't';
    }
    // 这里发送sendChar,而不是newMaxVal
} else {
    // 设备1发送数字,用 numbers[newMaxVal] 即可
    sendChar = numbers[newMaxVal];
}
// 执行蓝牙发送 sendChar 的代码

内容的提问来源于stack exchange,提问作者grace.cutler

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 10:42:34