Protocol for avoiding pointers

Currently I have 2 ways of programming a feature for my project: by using a kind of lengthy switch case or by using a pointer. Both work, but as a newbie I'm insecure about validity of me using pointers if I have an option not to.

What is the common consensus on pointers? Are they to be avoided at all times unless necessary or is it more of a preference?

Pointers are perfectly safe to use if you do it properly and understand them

Please post example sketches using the two approaches

From the Arduino style guide:

When forced to choose between technically simple and technically efficient, choose the former.

https://docs.arduino.cc/learn/contributions/arduino-writing-style-guide/

The biggest advantages to pointers is that the same function can change different variables from different calling functions.

The simple way of avoiding pointers is to make all variables global.

they can massively simplify the code. Learn how to use them and use them properly

see Pointers and Arrays in The C Programming Language

In Algorithms + Data Structure = Programs, Niklaus Wirth showed how they could be used to manage data more efficiently.

function pointers can add another level of simplification

I have several stepper motors connected to Arduino and a python tkinter GUI to control them. Buttons in tkinter are bound to run motor when pressed and stop when released.

This behavior is handled by one function at the end of the loop:

void runMotor() {
  if (activeMotor.run) { //If in active phase:
    digitalWrite(activeMotor.dirPin, activeMotor.direction); //Set the direction.
    long speed = ((60000000L) / ((long)activeMotor.RPM * ((long)MOTOR_REV * (long)DRIVER_MODE))) / 2; //Calculate the signal period for speed.
    digitalWrite(activeMotor.stepPin, HIGH); //Pulse ON.
    delayMicroseconds(speed); //Period halftime.
    digitalWrite(activeMotor.stepPin, LOW); //Pulse OFF.
    delayMicroseconds(speed); //Period halftime.
  } else {
    digitalWrite(activeMotor.stepPin, LOW); //Pulse OFF.
  }
}

At the top of the loop I have a switch case that handles different serial commands sent by GUI and a function that changes which motor should be currently active/inactive.

void setActiveMotor(bool is_running, int step_pin=-1, int dir_pin=-1, int direction=-1) {
  activeMotor.run = is_running; //Set active/inactive phase.
  activeMotor.stepPin = step_pin; //Set step pin.
  activeMotor.dirPin = dir_pin; //Set direction pin.
  activeMotor.direction = direction; //Set direction for the stepper motor.
}

Both use a struct for an active motor:

struct ActiveMotor {
  int stepPin;
  int dirPin;
  int direction;
  int RPM;
  bool run;
};
ActiveMotor activeMotor;

Now I want the GUI to display how many total steps were made by each motor on its button release and I want another struct to hold these values:

struct TotalSteps {
  float motor1;
  float motor2;
  float motor3;
  float motor4;
};
TotalSteps totalSteps;

I can do that by either creating another variable for activeMotor struct and using pointer to point to the variable of the currently used motor:

struct ActiveMotor {
  int stepPin;
  int dirPin;
  int direction;
  int RPM;
  bool run;
  float *steps;
};

void setActiveMotor(bool is_running, float &motorTotalSteps, int step_pin=-1, int dir_pin=-1, int direction=-1) {
  activeMotor.run = is_running; //Set active/inactive phase.
  activeMotor.stepPin = step_pin; //Set step/pulse pin.
  activeMotor.dirPin = dir_pin; //Set direction pin.
  activeMotor.direction = direction; //Set direction for the stepper motor.
  activeMotor.steps = &motorTotalSteps;
}

void runMotor() {
  if (activeMotor.run) { //If in active phase:
    digitalWrite(activeMotor.dirPin, activeMotor.direction); //Set the direction.
    long speed = ((60000000L) / ((long)activeMotor.RPM * ((long)MOTOR_REV * (long)DRIVER_MODE))) / 2; //Calculate the signal period for speed.
    digitalWrite(activeMotor.stepPin, HIGH); //Pulse ON.
    delayMicroseconds(speed); //Period halftime.
    digitalWrite(activeMotor.stepPin, LOW); //Pulse OFF.
    delayMicroseconds(speed); //Period halftime.
    *activeMotor.steps += MICROSTEP_SIZE; //Add 1/8 step (motor driver step mode.) 
  } else {
    digitalWrite(activeMotor.stepPin, LOW); //Pulse OFF.
  }
}

Or by making a global variable that will contain an "id" of an active motor and then processing it with two switch cases:

int activeMotorID;

void setActiveMotor(bool is_running, int motor_id, int step_pin=-1, int dir_pin=-1, int direction=-1) {
  activeMotor.run = is_running; //Set active/inactive phase.
  activeMotor.stepPin = step_pin; //Set step/pulse pin.
  activeMotor.dirPin = dir_pin; //Set direction pin.
  activeMotor.direction = direction; //Set direction for the stepper motor.

  switch (motor_id) {
    case 1:
      activeMotorID = 1;
      break;
    case 2:
      activeMotorID = 2;
      break;
    case 3:
      activeMotorID = 3;
      break;
    case 4:
      activeMotorID = 4;
      break;
  }
}

void runMotor() {
  if (activeMotor.run) { //If in active phase:
    digitalWrite(activeMotor.dirPin, activeMotor.direction); //Set the direction.
    long speed = ((60000000L) / ((long)activeMotor.RPM * ((long)MOTOR_REV * (long)DRIVER_MODE))) / 2; //Calculate the signal period for speed.
    digitalWrite(activeMotor.stepPin, HIGH); //Pulse ON.
    delayMicroseconds(speed); //Period halftime.
    digitalWrite(activeMotor.stepPin, LOW); //Pulse OFF.
    delayMicroseconds(speed); //Period halftime.

    switch (activeMotorID) {
      case 1:
        totalSteps.motor1 += MICROSTEP_SIZE;
        break;
      case 2:
        totalSteps.motor2 += MICROSTEP_SIZE;
        break;
      case 3:
        totalSteps.motor1 += MICROSTEP_SIZE;
        break;
      case 4:
        totalSteps.motor1 += MICROSTEP_SIZE;
        break;
    }

  } else {
    digitalWrite(activeMotor.stepPin, LOW); //Pulse OFF.
  }
}

So what exactly is your question?
If the code is just for you, then do it any way you like.

I recently completed work on code that was almost all pointers. I learned to code in machine language, then assembler, then PL/1, so pointers were natural to me. Use the language in a way that yields the easiest-to-understand code. Only then consider other optimizations.

Pointers or no, this kind of code is low hanging fruit:

  switch (motor_id) {
    case 1:
      activeMotorID = 1;
      break;
    case 2:
      activeMotorID = 2;
      break;
    case 3:
      activeMotorID = 3;
      break;
    case 4:
      activeMotorID = 4;
      break;
  }

It also looks at a glance like you've missed opportunities to use arrays instead of variables made distinct by appending an increasing letter or digit.

You shoukd not be afraid of language features, just keep learning and use stuff you've gained a degree of familiarity about and confidence in.

a7

why not the same structure with the motor parameters?

struct ActiveMotor {
  int stepPin;
  int dirPin;
  int direction;
  int RPM;
  bool run;
  int  currentStep;
};

the above seems awkward. the delay between steps should be something like half of 1 / speed where speed is steps/sec

and instead of using activeMote.dirPin, why not

void runMotor (
    ActiveMotor *pMot )     // or just Motor
{
  if (pMot->run) {
    digitalWrite        (pMot->dirPin, pMot->direction);

    int usecPerStep = 1000000 / (StepsPerRevolution * RPM / 60):

    digitalWrite        (pMot->stepPin, HIGH);  //Pulse ON.
    delayMicroseconds   (usecPerStep/2);        //Period halftime.
    digitalWrite        (pMot->stepPin, LOW);   //Pulse OFF.
    delayMicroseconds   (usecPerStep/2);
  }
}

could provide more feedback seeing the whole code

Counting should be done with integer types (uint32_t for example). Not with float! And why not an array of total_steps?
And an array of structs for your motors would even be way easier...
Using references is safer than using pointers... so, you should at least consider using them...

somehow funny to discuss pointers as long as you have a structure with pins in signed multi byte variables.

consider an uint8_t instead.

@alto777 @gcjr @build_1971 @noiasca

Thanks a lot for the comments on my code. A lot of things you are talking about I didn't know existed! I'll update my project using new information.

or pass variables by reference if in a function.

Could you please elaborate on this?

Pointers are useful. It is the core of C and C++. You must be fluent in it.

You can practice on Windows (using GCC from Cygwin or MinGW) or on Linux using native GCC, write small programms, play with pointers. The point of this is that these OS will catch 99.9% of your "pointer bugs" by briefly informing you, that "core dumped"

Not the first time I hear that "pointers are not for newbies". They are. They are for everyone. It is the foundation of the language.

it is sometimes useful: you can use negative values as special cases.

Something like:

struct Motor {
  int stepPin;
  int dirPin;
  int direction;
  int RPM;
  bool run;
  int steps;
};

Motor myMotors[4];

myMotor[0].stepPin=13;

Be aware that arrays start counting at 0!

This can be simplified down to

  activeMotorID = motor_id;

or, better


if (motor_id < 5 && motor_id > 0)
  activeMotorID = motor_id;
else
  Serial.printf("Bad motor_id %d\r\n",motor_id);

The switch/case statement has hidden powers, but you don't use them :slight_smile:

They are (assuming we are all using GCC-based compilers)

  1. case ranges: e.g. case 1...10:
  2. ability to fallthrough from one "case" to another
  3. "default" statement

What happens to an interface which accepts an uint8_t and you hand over “a negative value”?

Do you really think this kind of magic number handling is of any good and others should be encouraged to do so?