Changing OOP Stuff inside a loop

Hi, everyone! I've got the following code for sweeping a servo thanks to Adafruit's multitasking tutorial, but I cannot for the life of me figure out how I can change the sweep speed from inside my loop. OOP is very new to me in this setting. I can change the sweep speed by setting a number of things up in setup and before setup, but can't figure out how to do so on my button press or anywhere in the loop. Any help would be appreciated. Thanks!

#include <Servo.h> 



class Sweeper
{
  Servo servo;              // the servo
  int pos;              // current servo position 
  int increment;        // increment to move for each interval
  int  updateInterval;      // interval between updates
  unsigned long lastUpdate; // last update of position

public: 
  Sweeper(int interval)
  {
    updateInterval = interval;
    increment = 1;
  }
  
  void Attach(int pin)
  {
    servo.attach(pin);
  }
  
  void Detach()
  {
    servo.detach();
  }
  
  void Update()
  {
    if((millis() - lastUpdate) > updateInterval)  // time to update
    {
      lastUpdate = millis();
      pos += increment;
      servo.write(pos);
      Serial.println(pos);
      if ((pos >= 180) || (pos <= 0)) // end of sweep
      {
        // reverse direction
        increment = -increment;
      }
    }
  }
};
 
 

Sweeper sweeper1(15);

 
void setup() 
{ 
  Serial.begin(9600);
  pinMode(2, INPUT_PULLUP); 
  sweeper1.Attach(9);
  
} 
 
 
void loop() 
{ 
  sweeper1.Update();
  
  if(digitalRead(2) == HIGH)
  {
     // make sweeper sweep more slowly 
     
  }
  
 
}```

Wouldn't you change sweeper1.updateInterval?

if(digitalRead(2) == HIGH)
  {
     // make sweeper sweep more slowly 
      sweeper1.updateInterval = 500;
  }

That usually means that the switch is wired to ground so the active state (button is pressed) is LOW.

If you only want to move a servo at a certain speed, you can just use a library that allows this. For example this library (I haven't used it personally, I just know about it).

Yes, but I think you need to make updateInterval public within the class first.

Good catch @red_car. Otherwise one would have to write a member function to change updateInterval.

Like:

  void SetInterval(int newInterval)
  {
    updateInteval = newInterval;
  }

Then you can call sweeper1.SetInterval(newvalue) to change the interval.

2 Likes

Thank you all SO much for the help. That worked perfectly. I will now read up on this new way of thinking with member functions and what can be done with OOP. I have been a delay-slinging hack for years without knowing there were options like these.

Thank you very much.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.