# Simplifying Code with Programmatically Constructed Function Calls

Hello All,

I currently have working code, but am upset that I have to type so much and my code is so ugly. I have two stepper motors that I want to move about (with limit switches at the end of lead screws) based on serial messages received. I can easily do this, but I need more than one if statement to deal with switching direction, etc. Is there a way to construct a call function? For example, this should turn my stepper motor til the stage hits a limit switch:

``````void moveToLimit(char axis, bool direction)
{
digitalWrite(stepPinAxis, direction);
bool limitOn = false;
while(limitOn == false)
{
stepAxis();
{
limitOn = true;
}
}
``````

The question about the above code is, how do I call stepX() or stepY() based on the char axis? And how do I get limitPinX or limitPinY instead of limitPinAxis. In other languages I could do something like

``````paste0("step", axis, "()");
``````

and the line would be stepX(); or stepY(); based on axis. Is there a way to do that in Arduino?

Thanks!

(deleted)

Yeah.. I have that correct in my actual Arduino code, just didn't write it properly here. Edited my above code.

c++ supports "if" statements....

Regards,
Ray L.

how do I call stepX() or stepY() based on the char axis?

if axis were 0 for the X axis and 1 for the Y axis instead of being a char then you could use it as an index to an array of structs that contained data such as the pin numbers of the limit switches, the stepper control pin numbers and the current step direction. The data could then be passed to a function to do the actual stepping, You don't even need a function for each axis

Thanks Bob, this works quite nicely! Or, it appears to; it'll take me a bit to figure out how to do it properly. But from what I've read in the past few minutes, it should make my code much prettier. I realize this was definitely a 'first world problem' of coding, but if I want to get good at coding, I should solve those problems too.

Rl4ndom:
Yeah.. I have that correct in my actual Arduino code, just didn't write it properly here. Edited my above code.

At the risk of pointing out the obvious....
In the Arduino IDE
Edit/Copy for forum.
Even puts the code tags in for you. No need to 'write' it here, just paste it in.