You need to enable JavaScript to run this app. 如何在Arduino中通过串口输入调用对应的控制函数
优惠活动
大模型
产品
解决方案
定价
更多

如何在Arduino中通过串口输入调用对应的控制函数

问题原因

你代码中的核心问题是字符串比较逻辑错误:C语言中用==直接对比字符数组receivedChars和字符串常量(如"H")时,实际是在对比两个字符串的内存存储地址,而非字符串本身的内容,因此判断条件永远无法触发,对应的控制函数也就不会执行。

修复方法

将showNewData()函数内的所有字符串相等判断,替换为C标准库的strcmp()函数即可。strcmp()在两个字符串内容完全相同时返回值为0,修改后的代码如下:

void showNewData() {
  if (newData == true) {
    Serial.println(receivedChars);
    if (strcmp(receivedChars, "H") == 0) {
      upHeat();
    }
    else if (strcmp(receivedChars, "C") == 0) {
      downHeat();
    }
    else if (strcmp(receivedChars, "O") == 0) {
      heatOn();
    }
    else if (strcmp(receivedChars, "F") == 0) {
      heatOff();
    }
    else if (strcmp(receivedChars, "a") == 0) {
      servoPosOne();
    }
    else if (strcmp(receivedChars, "s") == 0) {
      servoPosTwo();
    }
    else if (strcmp(receivedChars, "d") == 0) {
      servoPosThree();
    }
    newData = false;
  }
}

可选优化

由于你所有的控制指令都是单字符,也可以直接判断字符数组首位的字符值,写法更简单执行效率更高,示例如下:

if (receivedChars[0] == 'H') {
  upHeat();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 13:45:03