如何结合电位器控制串行输入的伺服

How to control a servo with serial input in combination with potentiometer

我想通过串行输入结合电位器来控制舵机。伺服可以单独控制。如果我注释掉串口输入的部分代码,那么我就可以通过电位器控制舵机,如果我注释掉电位器的部分代码,那么我就可以通过串口输入来控制舵机。但是我想组合控制。

我已经尝试过以下方法:我做了一个整数来保存旧值,并做了一个 if 语句来检查旧值是否已被更改。当然它被改变了,因为程序总是读取改变的值,即电位器值

代码:

void loop()
{
  controlMeter();
}

void controlMeter()
{
  int potValue = map(analogRead(aiPot), 0, 1023, 0, 180);
  int keyValue = 0;

  if(Serial.available())
  {
    String SkeyValue = Serial.readStringUntil('\n');
    keyValue = SkeyValue.toInt();
    Serial.println("There is something in serial!");
    if (oldValue != keyValue)
    {
      oldValue = keyValue;
      Serial.print("keyValue: ");
      Serial.println(keyValue);
      servo.write(oldValue);
      delay(2000);
    }
  }
  else
  {
    if (oldValue != potValue)
    {
      oldValue = potValue;
      Serial.print("potValue: ");
      Serial.println(potValue);
      servo.write(oldValue);
      delay(2000);
    }
  }
}

我希望如果我输入 150,那么伺服将变为 150 并保持在 150,但是如果我用电位器将该值更改为 30,那么伺服必须变为 30 并保持在那里。

如有任何帮助,我们将不胜感激。

将电位器和串行的旧值存储在单独的变量中。

模拟输入包含一些噪音。如果变化大于某个阈值,您应该只使用电位计:

void loop()
{
  controlMeter();
}

int oldValue_Pot = -1;
int oldValue_Ser = -1;

int treshold = 5;

void controlMeter()
{
  int potValue = map(analogRead(aiPot), 0, 1023, 0, 180);
  int keyValue = 0;

  if(Serial.available())
  {
    String SkeyValue = Serial.readStringUntil('\n');
    keyValue = SkeyValue.toInt();
    Serial.println("There is something in serial!");
    if (oldValue_Ser != keyValue)
    {
      oldValue_Ser = keyValue;
      Serial.print("keyValue: ");
      Serial.println(keyValue);
      servo.write(oldValue_Ser);
      delay(2000);
    }
  }
  else
  {
    if (abs(oldValue_Pot - potValue) > treshold)
    {
      oldValue_Pot = potValue;
      Serial.print("potValue: ");
      Serial.println(potValue);
      servo.write(oldValue_Pot);
      delay(2000);
    }
  }
}