Arduino IDE编译报错:函数不允许在此处定义,可运行代码无法修改
问题根因
报错核心原因是C/C++语法不支持嵌套函数定义,你将noteOn函数写在了loop()函数的大括号内部,触发两个连锁错误:
- 编译器先检测到函数内部定义函数的语法错误,直接抛出
a function-definition is not allowed here报错 - 代码前半段调用
noteOn时,编译器还未识别到该函数的定义,因此抛出not declared in this scope报错
该问题和缩进、括号缺失无关。
修复后可正常编译的完整代码
// define pins const int switchPin1 = 2; const int switchPin2 = 3; // midi notes char note1 = 60; //Middle C char note2 = 62; //D // variables int switchState1 = LOW; int switchState2 = LOW; int currentSwitchState1 = LOW; int currentSwitchState2 = LOW; // noteOn函数移至loop()外部全局位置 void noteOn(char cmd, char data1, char data2) { Serial.print(cmd); Serial.print(data1); Serial.print(data2); } void setup() { // set the states of the I/O pins: pinMode(switchPin1, INPUT); pinMode(switchPin2, INPUT); // set MIDI baud rate : Serial.begin(31250); } void loop() { currentSwitchState1 = digitalRead(switchPin1); currentSwitchState2 = digitalRead(switchPin2); // button 1 push if (currentSwitchState1 == HIGH && switchState1 == LOW) { noteOn(0x94, note1, 0x45); delay(100); noteOn(0x94, note1, 0x00); switchState1 = HIGH; } // button 1 release if (currentSwitchState1 == LOW && switchState1 == HIGH) { switchState1 = LOW; } // button 2 push if (currentSwitchState2 == HIGH && switchState2 == LOW) { noteOn(0x94, note2, 0x45); delay(100); noteOn(0x94, note2, 0x00); switchState2 = HIGH; } // button 2 release if (currentSwitchState2 == LOW && switchState2 == HIGH) { switchState2 = LOW; } }
注:你之前提到代码曾正常运行,大概率是之前修改代码时误将
noteOn函数剪切到了loop内部,调整位置即可恢复正常编译。
内容的提问来源于stack exchange,提问作者Cesar Andersen Lindholm
相关产品推荐
相关产品推荐

