Using a variable name to control the next servo in loop

I am working on a candy drop machine that has 12 servos, one for each bag of candy to drop. When the dispense button is pressed, I want to have the first servo (servo1) drop. then at the end of the sequence I would use count++ to add 1 to the servo name so the next time the button is pressed the 2nd servo (servo2) would drop and so on until I hit 12, after 12, I want the count to reset to 1 again to start over after I re-load the drops. I'm good with the all the code to make the servos work, but not sure how to make the variable for the servo and to reset the count after 12. Any help would be appreciated. just starting to make my sketch so no examples yet.

This is my 5th year making my halloween candy dispenser and each year it's different. So excited to be using arduino and this community is fantastic!

Put the names of each servo into an array, and use a count to increment the array index from 0 to 11.

You are starting pretty early for Hallowe'en. Around here requests like this come closer to Oct 22 or so.

Instead of making, say, myServo1, myServo2, mySevo3 and so forth and putting those names in an array, you should make an array of servos like

Servo myServo[5];

and attach them in setup() like

  for (byte ii = 0; ii < 5;ii++) {
    myServo[ii].attach(servoPin[ii]);
  }

where I have assumed an array of servo pin numbers where they are attached.

Later, refer to a servo with an index number like

  myServo[3].write(42);

or using a variable (if you had for example a loop over all servos) like

// move all servos to 90 degrees
  for (byte ii = 0; ii < 5; ii++) {
    myServo[ii].write(90);
  }

I keep saying like because I am under the umbrella and cannot test the above, but it is close, you def wanna use an array of servos here.

When I get to the lab, I will test and correct this if someone hasn't beaten me to it.

HTH

a7

1 Like

Even better, here's a complete example in the wokwi simulator, if you don't know, now you know:

I believe you can see all the same syntax used to create, intialise and manage a buncha servos.

The author does "cheat" and exploits the fact that the servos are attached at consecutive output pins.

a7

3 Likes
if (count > 12)
  count = 1;

You could also consider using 'one spring' similar to those used by commercial dispensing machines ( so you'll need only one motor )

nicely done.

You are seeking to build a state machine.

You will want a global variable that drives the state of the machine, using switch/case control structure. The condition to increment (and then reset) the state of your machine is your button press.

Serial printing is great for debugging, as I'm sure you're aware.

As you can see in the following example, within each state (case 0, case 1 and so on), there is an associated function and within those functions is the instruction to the sketch to increment the state by one until it resets in void four().

Hopefully this sketch gives you a good idea at one way to do what you'd like to do.

Note, state machines are game changers, literally and figuratively. It's a very important concept to understand if you like building game-type things or props because it really allows you to break everything down and structure what the total end goal will look like, while avoiding code that is difficult for you or anyone else to follow down some time in the future.

Here's a great video to highlight exactly that by the popular YouTuber, Neshacker.

And here's the example code my daughter and I wrote to show her the same concept:

/* April 04, 2024
 *  by Tte
 *  State Machine - timed leveled events
 */

byte level;  // 0-255 possible levels
unsigned long currentTime = 0;
unsigned long lastTimeAround = 0;

void setup() {
  Serial.begin(115200);
  for (int i = 0; i < 20; i++) {
    Serial.println();  // 20 blank lines to clear Serial Monitor of lazy or leftover text
  }
  Serial.println("millisTimedFunctionsByTte\n");
  level = 0;
}

void loop() {
  // start free running timer
  currentTime = millis();
  /* set timer condition to check clock every second to
    see what level we're on and perform the associated function */
  if (currentTime - lastTimeAround > 1000) {
    switch (level) {
      case 0:
        zero();
        break;
      case 1:
        one();
        break;
      case 2:
        two();
        break;
      case 3:
        three();
        break;
      case 4:
        four();
        break;
      default:
        break;
    }
    // synch the time marker to the free running clock
    lastTimeAround = currentTime;
  }
}
void zero() {
  Serial.print("\tTte ");
  level += 1;
}
void one() {
  Serial.print("Loves ");
  level += 1;
}
void two() {
  Serial.print("Cats ");
  level += 1;
}
void three() {
  Serial.print("and ");
  level += 1;
}
void four() {
  Serial.println("Dogs:)");
  level = 0;
}

@J-M-L - TBC that's the work of @Koepel, early adopter and promoter of the simulator.

a7

1 Like

ah OK - kuddos to @Koepel then

1 Like

Thanks. The funny thing is that the positions of the servos are calculated in the sketch (which runs in Wokwi). It is the function "GenerateDiagram()" and its output is the circuit for Wokwi.

The Servo library uses a timer that triggers a interrupt routine. In the interrupt routine, all the PWM signals are made. It turns out that a basic Arduino board has no problems with many Servo signals.

1 Like

yeah I've seen that , it's cool :slight_smile:

Nice work! Your sim is so much fun to play around with. Thanks for sharing it!
Watching it makes me think of Eddie Van Halen playing a killer guitar solo.

@Koepel Thanks for the simulator sketch, it's pretty cool. I was having an issue with Pins 45 &46 on my Mega. I could not get any PWM output on them. How did you solve this problem? I see in the dissuasion you were talking about the timer function, which I know get's used on these pins I think. I've done a basic servo.attach for each servo as I'm just testing to make sure all wiring is correct before I move on to fancier things like arrays.

Pin 45 and 46 are just normal digital pins. There should be no reason for them to behave differently. Could there be something wrong with the hardware of the board ? A solder blob that creates a short circuit or a broken copper trace of the PCB ?

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