首页 文章

Arduino串口显示器上的垃圾 . 怎么解决?

提问于
浏览
0

我正在使用I2C eeprom和Arduino . 现在我尝试创建将启动特定功能的简单键盘 . 我想写串口监视器电位器值,但我得到垃圾而不是它 . 怎么解决?我的职责:

int *readPot() ///read potentiometer value
{
   int tempValue = analogRead(A0);
   int *potValue = &tempValue;
   return potValue;
}
void keyboardProcess() ///process keyboard input
{
    int *potValue = readPot();
    for(int i = 0; i < 2; i++)
    {
       btnReadings[i] = digitalRead(keysPins[i]);
    }
    if(btnReadings[0] == HIGH)
    {
        Serial.println("Potentiometer reading:" + *potValue); 

    }
 }

Serial Monitor

1 回答

  • 1

    一个明显的问题是您将地址返回到局部变量:

    int *readPot() ///read potentiometer value
    {
       int tempValue = analogRead(A0);
       int *potValue = &tempValue;
       return potValue;
    }
    

    这里,返回的指针指向 tempValue 的地址 . 一旦函数返回,这就不再有效 . 只需使用 int

    int readPot() ///read potentiometer value
    {
       return analogRead(A0);
    }
    

    接下来,我怀疑这是 Serial.println 的有效参数:

    Serial.println("Potentiometer reading:" + *potValue);
    

    但这应该有效:

    int potValue = readPot();
    Serial.print("Potentiometer reading: ");
    Serial.println(potValue);
    

相关问题