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

Arduino中Loop内调用自定义函数编译失败求助

问题解决:Arduino自定义函数编译失败的修复方案

错误原因分析

你的代码编译失败核心有两个问题:

  • 函数参数未声明类型:Arduino基于C++,自定义函数的参数必须明确指定数据类型,不能省略。
  • 命名冲突:参数名delay和Arduino内置的delay()函数重名,编译器无法区分两者,导致歧义。

另外还有一个功能缺陷:调用tone()后未停止发声,会导致声音持续输出,影响后续音调切换。

修复后的完整代码

void setup() {
  for(int i = 2 ; i<=9; i++){
    pinMode(i, OUTPUT);
  }
}

int C4 = 262; // LED 4
int D4 = 294; // LED 5
int E4 = 330; // LED 6
int F4 = 349; // LED 7
int G4 = 392; // LED 8
int C5 = 523; // LED 9

// 修复参数类型,并重命名delay参数为delayTime避免冲突
void sonar(int numeroPin, int sonido, unsigned long delayTime) {
  tone(2, sonido);
  digitalWrite(numeroPin, HIGH);
  delay(delayTime); // 使用重命名后的参数
  digitalWrite(numeroPin, LOW);
  noTone(2); // 停止发声,确保下一次tone调用正常工作
}

void loop() {
  sonar(4, C4, 1000);
  sonar(5, D4, 1000);
  sonar(6, F4, 167);
  sonar(7, E4, 167);
  sonar(5, D4, 167);
  sonar(8, C5, 1000);
  sonar(9, G4, 500);
}

关键修复点说明

  • 参数类型声明:给sonar函数的三个参数分别加上int、int、unsigned long类型(和内置delay函数的参数类型保持一致,规范且避免隐式转换问题)。
  • 参数重命名:把delay改成delayTime,彻底解决和内置函数的命名冲突。
  • 添加noTone:每次发声结束后调用noTone(2),关闭引脚2的音调输出,防止声音叠加或持续播放。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:15:56