Search code examples
arduinouser-inputservo

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


I want to control a servo with serial input in combination with a potentiometer. The servo can be controlled separately. If I comment a part of code like serial input, then I can control the servo via potentiometer, If I comment the part of code of potentiometer, then I can control the servo with serial input. But I want to control in combination.

I already tried the following: I made an integer to save the old value and made an if statement to check if the old value has been changed. Ofcourse it is changed because the program always reads the changed value which is potentiometers value

The code:

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);
    }
  }
}

I expect that if I input 150 then the servo goes to 150 and stays at 150 but if I change that value with potentiometer to 30, then te servo must go to 30 and stays there.

Any help would be appreciated.


Solution

  • Store the old value of the potentiometer and serial in separate variables.

    An analog input contains some noise. You should only use the potentiometer if the change is greater as some threshold:

    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);
        }
      }
    }