Passing object as parameter to function

Im trying to pass an object as a parameter to a function when I press a button but it wont work as I expected. The code compiles but nothing happens when I press the button. When I pass no parameters and specifies the object it works fine however.

What is wrong? How can I pass an object as parameter?

#include <AccelStepper.h>

AccelStepper stepper1 = AccelStepper(AccelStepper::FULL4WIRE, 4, 5, 6, 7);
int resetPin = 3;

void setup() {
  Serial.begin(9600);
  pinMode(resetPin, INPUT);
  stepper1.setMaxSpeed(500);
  stepper1.setAcceleration(5000);
  stepper1.setSpeed(500);
  stepper1.moveTo(5000);
}

void loop() {
  stepper1.moveTo(1000);
  int resetVal = digitalRead(resetPin);

  if (resetVal == HIGH) {
    resetPosition(stepper1);
//    resetPosition();
  }

  stepper1.run();
  Serial.println(stepper1.currentPosition());
}

void resetPosition(AccelStepper stepper) {
  stepper.setCurrentPosition(0);
  Serial.println("RESETTED VAL: ");
  Serial.print(stepper.currentPosition());
}

// this works however
//void resetPosition() {
//  stepper1.setCurrentPosition(0);
//}

Try passing a reference to the object.

Hmm. Not in front of computer but like this?

void resetPosition(AccelStepper *stepper) {
  stepper.setCurrentPosition(0);
  Serial.println("RESETTED VAL: ");
  Serial.print(stepper.currentPosition());
}

When shall I use * and what is the differences between using * and &

&

and

*

Use &. Take a look at a C++ tutorial for the difference between reference and pointer.

No.. Like this.

if (resetVal == HIGH) {
    resetPosition(&stepper1);

Pass the address of the object here..

void resetPosition(AccelStepper* stepper) {
  stepper->setCurrentPosition(0);
  Serial.println("RESETTED VAL: ");
  Serial.print(stepper->currentPosition());
}

Notice all the stepper.method() calls are now stepper->method() calls.

-jim lee

jimLee:
No.. Like this.

if (resetVal == HIGH) {

resetPosition(&stepper1);




Pass the address of the object here..



void resetPosition(AccelStepper* stepper) {
 stepper->setCurrentPosition(0);
 Serial.println("RESETTED VAL: ");
 Serial.print(stepper->currentPosition());
}




Notice all the stepper.method() calls are now stepper->method() calls.

-jim lee

Why?

Just use a reference as suggested by wildbill. It results in cleaner code, and you don't have to take into account the possibility of stepper being null.

if (resetVal == HIGH) {
    resetPosition(stepper1);
void resetPosition(AccelStepper &stepper) {
  stepper.setCurrentPosition(0);
  Serial.println("RESETTED VAL: ");
  Serial.print(stepper.currentPosition());
}

Pieter

Why?

Just use a reference as suggested by wildbill. It results in cleaner code, and you don't have to take into account the possibility of stepper being null.

Because I like to do it that way.

-jim lee