Arduino Nano代码在Arduino IDE可编译但VSC报ai0/ai1未声明问题咨询
问题原因
- 你碰到的
'ai0' was not declared in this scope'ai1' was not declared in this scope报错的核心是Arduino IDE和VS Code的编译预处理逻辑存在差异:Arduino IDE会自动为所有用户定义的函数生成前置声明,不需要手动编写,所以代码能正常编译;但VS Code中使用的Arduino编译工具链(包括PlatformIO、官方Arduino扩展的默认编译逻辑)没有这个自动处理步骤,函数如果在定义之前被调用,就会报未声明的错误。 - 另外当前代码还缺少全局变量
counter和temp的定义,解决完函数声明的问题后还会报这两个变量未声明的错误,需要同步修复。
修复方案
在代码最开头、setup()函数之前补充函数前置声明和全局变量定义即可,完整修复后的代码如下:
// 补充全局变量定义,中断内修改的变量需要加volatile防止编译器优化 volatile int counter = 0; int temp = 0; // 补充中断函数的前置声明 void ai0(); void ai1(); void setup() { Serial.begin (9600); pinMode(2, INPUT_PULLUP); // internal pullup input pin 2 pinMode(3, INPUT_PULLUP); // internal pullup input pin 3 //Setting up interrupt //A rising pulse from encodenren activated ai0(). AttachInterrupt 0 is DigitalPin nr 2 on moust Arduino. attachInterrupt(0, ai0, RISING); //B rising pulse from encodenren activated ai1(). AttachInterrupt 1 is DigitalPin nr 3 on moust Arduino. attachInterrupt(1, ai1, RISING); } void loop() { // Send the value of counter if( counter != temp ){ Serial.println (counter); temp = counter; } } void ai0() { // ai0 is activated if DigitalPin nr 2 is going from LOW to HIGH // Check pin 3 to determine the direction if(digitalRead(3)==LOW) { counter++; }else{ counter--; } } void ai1() { // ai1 is activated if DigitalPin nr 3 is going from LOW to HIGH // Check with pin 2 to determine the direction if(digitalRead(2)==LOW) { counter--; }else{ counter++; } }
内容的提问来源于stack exchange,提问作者Al1er
相关产品推荐
相关产品推荐

