Objects in an array

I have a project with 6 buttons and 6 servo's and was wondering if it was possible to define the buttons in an array somethings like buttons[5] and servo[5]
Any help would be appreciated,

Yes, it is. But it would be buttons[6] and servo[6].

Ok so would it be something like

#define buttons[6] = {A0,A1,A2,A3,A4,A5}

No. You can not use the preprocessor for that.

pinType buttons[] = {A0,A1,A2,A3,A4,A5};
int numberOfButtons = sizeof buttons[] / sizeof buttons[0];

and… if they’re related to each other they could be in an array of structs…

(the general idea…)

struct thingtype {
  int buttonPin;
  Servo servo;
}

thingtype MyThing[6];

void setup() {
  MyThing[0].buttonPin = 2;
  MyThing[0].write(180);
}

… and so on…

These two statements confuse me, how can one distinguish between the button and the servo

MyThing[0].buttonPin = 2; MyThing[0].write(180)

Sorry, my typo…

MyThing[0].servo.write(180):

example of syntax only.

Looks like this thread got twisted in the wind.
Take a look at how GolamMostafa solved the display matrix here:
https://forum.arduino.cc/t/4-digit-7-segment-display-stopwatch/618192/5

Input is very similar methodology.

it depends on how you set up your array.
if you have just a array of servo[5] than it is a simple

servo[0].write(180);

if you create your own structure or class combining the button with the servo and call it for example "myThing" than you would introduce somthing like

myThing[0].write(180);
currentButtonState=myThing[0].read();

it depends on how you create the functionality of your "myThing".

if you show your code - help might get clearer for you.

/*
   Model Railway Junction Robin/Ann

   Servo    5v
   Nano     ATMega328P (old bootloader) 5V (5V & gnd)
   Switch   3.3v

   Junction     Servo Pin     Switch pin
    1             D9            A0
    2             D8            A1
    3             D7            A2
    4             D5            A3
    5             D4            A4
    6             D3            A5
a
   Version 1.A
         REVIEWED:   Dec 12 2021


*/

#include <VarSpeedServo.h>

//BUTTONS
#define button1   A0
#define button2   A1

//SERVO OBJECTS
VarSpeedServo myServo1;
VarSpeedServo myServo2;

//BUTTON STATES
int prevbuttonState1;
int prevbuttonState2;
int currbuttonState1;
int currbuttonState2;

//SERVO SPEED
int Speed = 10;

//-----------------------------------------------------------------------------
void setup() {

  //switches
  pinMode(button1, OUTPUT);
  pinMode(button2, OUTPUT);

  //servo
  setServo();// set according to the position of the buttons when we start up

}//end of setup-----------------------------------------------------------------------------

void loop() {

  // button states
  currbuttonState1 = digitalRead(button1);
  currbuttonState2 = digitalRead(button2);

  // which junction
  if (currbuttonState1 == HIGH && currbuttonState1 != prevbuttonState1) doJunction1(1);
  if (currbuttonState1 == LOW  && currbuttonState1 != prevbuttonState1) doJunction1(2);

  if (currbuttonState2 == HIGH && currbuttonState2 != prevbuttonState2) doJunction2(1);
  if (currbuttonState2 == LOW  && currbuttonState2 != prevbuttonState2) doJunction2(2);

}//end of loop----------------------------------------------------------------

//FUNCTIONS

void doJunction1(int Direction) {

  switch (Direction) {
    case 1:
      //STRAIGHT
      myServo1.write(0, Speed, true); myServo1.stop();
      prevbuttonState1 = currbuttonState1;
      break;
    case 2:
      //TURN LEFT
      myServo1.write(10, Speed, true); myServo1.stop();
      prevbuttonState1 = currbuttonState1;
      break;
    default:
      break;
  }
}//end of doJunction1----------------------------------------------------------------

void doJunction2(int Direction) {

  switch (Direction) {
    case 1:
      //STRAIGHT
      myServo2.write(0, Speed, true); myServo2.stop();
      prevbuttonState2 = currbuttonState2;
      break;
    case 2:
      //TURN LEFT
      myServo2.write(10, Speed, true); myServo2.stop();
      prevbuttonState2 = currbuttonState2;
      break;
    default:
      break;
  }

}//end of doJunction2----------------------------------------------------------------

void setServo() { // set the servo according to the

  currbuttonState1 = digitalRead(button1);
  currbuttonState2 = digitalRead(button2);

  if (currbuttonState1 == HIGH ) {
    myServo1.write(0);
    myServo1.attach(9);
  }
  if (currbuttonState1 == LOW  ) {
    myServo1.write(10);
    myServo1.attach(9);
  }
  //------------------------------
  if (currbuttonState2 == HIGH ) {
    myServo2.write(0);
    myServo2.attach(8);
  }
  if (currbuttonState2 == LOW  ) {
    myServo2.write(10);
    myServo2.attach(8);
  }
  //------------------------------
}

//---------------------------------------------------------------------------------------

//attach(pin )  - Attaches a servo motor to an i/o pin.
//attach(pin, min, max  ) - Attaches to a pin setting min and max values in microseconds
//default min is 544, max is 2400
//
//write(value)     - Sets the servo angle in degrees.  (invalid angle that is valid as pulse in microseconds is treated as microseconds)
//write(value, speed) - speed varies the speed of the move to new position 0=full speed, 1-255 slower to faster
//write(value, speed, wait) - wait is a boolean that, if true, causes the function call to block until move is complete
//
//writeMicroseconds() - Sets the servo pulse width in microseconds
//read()      - Gets the last written servo pulse width as an angle between 0 and 180.
//readMicroseconds()  - Gets the last written servo pulse width in microseconds. (was read_us() in first release)
//attached()  - Returns true if there is a servo attached.
//detach()    - Stops an attached servos from pulsing its i/o pin.
//
//slowmove(value, speed) - The same as write(value, speed), retained for compatibility with Korman's version
//
//stop() - stops the servo at the current position
//
//sequencePlay(sequence, sequencePositions); // play a looping sequence starting at position 0
//sequencePlay(sequence, sequencePositions, loop, startPosition); // play sequence with number of positions, loop if true, start at position
//sequenceStop(); // stop sequence at current position
//wait(); // wait for movement to finish
//isMoving()  // return true if servo is still moving.

This is the code i think it should be simpler but still easy to maintain - a lot could be in arrays and for next loops. Just not sure on how to define the buttons, servo's in an array.
I have only coded the first two buttons as yet

Thank you for showing code - it helps.

Nevertheless I don't like to reverse engineer sketches.

Can you please describe what your software should do.
Please use as short sentences as possible.

and further on: please describe where
#include <VarSpeedServo.h>

does come from. If it is an external library, give as an description where we can download it.

When a switch button is HIGH it turns a servo to the zero position, when LOW it turns the servo to set position in this case 10.
I can put most of the code in a for next loop with an array but am not sure how to do the button and servo objects.

https://forum.arduino.cc/t/varspeedservo-a-modified-servo-library-with-speed-control/61404

This is the link I used to obtain VARSPEEDSERVO

Thank you for your help.

I hope you understand, that I will not download a 10 year old library.

Anyway, for a short PoC the Servo lib provided in the IDE should do its job also.
This is a short procedural demo:

// When a switch button is HIGH it turns a servo to the one position, when LOW it turns the servo to set position in another position
// the sketch should be able to use several buttons/switches
// https://forum.arduino.cc/t/objects-in-an-array/935241/10
// by noiasca

#include <Servo.h>

constexpr byte left = 0;
constexpr byte right = 10;

struct Group {
  const byte buttonPin;
  const byte servoPin;
  int previousButtonState = LOW;
  Servo servo;
// constructor because of "missing" initialized variable servo
  Group(const byte buttonPin, const byte servoPin) :
    buttonPin(buttonPin), servoPin(servoPin)
  {}
};

Group group[] {
  {A0, 9},
  {A1, 8},
  {A2, 2},
  {A3, 3}
};

void readAndWrite()
{
  for (auto & i : group)
  {
    int currentButtonState = digitalRead(i.buttonPin);
    if (i.previousButtonState != currentButtonState)
    {
      i.previousButtonState = currentButtonState;
      Serial.print(F("set servo pin "));
      Serial.print(i.servoPin);
      if (currentButtonState == LOW)
      {
        Serial.println(F(" to left"));
        i.servo.write(left);
      }
      else
      {
        Serial.println(F(" to right"));
        i.servo.write(right);
      }
    }
  }
}

void setup() {
  Serial.begin(115200);
  Serial.println(F("lot of servos"));
  for (auto & i : group)
  {
    i.servo.attach(i.servoPin);
    pinMode(i.buttonPin, INPUT_PULLUP);
  }
  //group[0].servo.write(left);   // you could set the servos
  //group[1].servo.write(right);
}

void loop() {
  readAndWrite();
}

some comments:

  • you define a structure Group with all member variables you need for each instance of your button-servo combination
  • the structure needs a constructor also, - you will see why in the next step,
  • the group is an array of type Group. You initialize it with all your pins. previousButtonState gets initialized to LOW. But for "servo" you will need the constructor also, otherwise you will get a compiler warning.
  • readAndWrite() reads the switch/button and writes to the servo if there was a state change.
  • you do that for all instances - in my example for all four switch/servo in group.
  • please notice that I'm using the INPUT_PULLUP for the buttons/switches. You can change that according to your hardware/wiring to INPUT also.
  • you see: with arrays one more button/servo is only ONE line to add ...
  • finally, if you see that the first time
 for (auto & i : group)

google for "auto range based for c++" ( I call it poor mans foreach ... but get serious explanations with your research).

I have learned from this posting and thank you for it. I was quite blown away when i saw this :

I did google it - would it be possible for you to interpret it into a standard for/next loop to help in understanding..
Thanks again for all your help .

Standard (whatever that means) for loop implementation

Then change all the 'i' references in the loop to "group[i]"

1 Like

great now I get it - thanks