Hi,
For a 3-axis stepper motor Arduino Mega project, I wish to set up a 2D table holding the various motor and switches pin numbers.
I want to address the table pin values by names rather that by numbers, example:
byte Pinnumber = [Motor1][direction];
After building a test program I noticed that I can not make it work: Addressing the items by names does no bring the expected result, as can be seen in the attached code example.
The main problem seems to be passing a row name to select a raw.
Can any one suggest a remedy or a better way?
(To test run the attached, just serial send one byte of X,Y or Z ASCII (88,89, 90 dec, or 0x58, 0x59, 0x5A at 115200).
Thanks
// Test program to designate Arduino Mega pin numbers for 3-axis stepper motors and end-switches.
enum axis {X, Y, Z};
enum function { dir, enable, steps, home, out, gnd };
byte pin[3][6]; //Define 2D 3X6 "pin" array
void setup(void)
{
Serial.begin(115200);
// Set XYZ motors pin numbers for Arduino Mega
pin[X][gnd] = 23;
pin[X][enable] =25;
pin[X][dir] = 27;
pin[X][steps] = 29;
pin[X][home] = 14;
pin[X][out] = 15;
pin[Y][gnd] = 31;
pin[Y][enable] =33;
pin[Y][dir] = 35;
pin[Y][steps] = 37;
pin[Y][home] = 16;
pin[Y][out] = 17;
pin[Z][gnd] = 39;
pin[Z][enable] =41;
pin[Z][dir] = 43;
pin[Z][steps] = 45;
pin[Z][home] = 18;
pin[Z][out] = 19;
}
void loop()
{
if (Serial.available()) // Send HEX ASCII of X,Y or Z = 0x58, 0x59, 0x5A
{
byte val = Serial.read();
Serial.print(" val="); Serial.println(val);
RunTest(val); //88 dec = char X.
}
}
void RunTest(byte motor) //ASCII of X,Y,Z
{
char ax = char(motor);
Serial.print(" ax="); Serial.println(ax); // OK. Disp X
Serial.print(" pin X="); Serial.println(pin[X][steps]); // OK. Disp correct pin number
Serial.print(" pin num="); Serial.println(pin[ax][steps]); // Expect correct pin number ???
digitalWrite(pin[ax][steps], ! digitalRead(pin[ax][steps])); // Negate X steps
Serial.print(" ax dir="); Serial.println(digitalRead(pin[ax][steps])); // Expect 1,0,1,0
}
Character 'X' is not the same as the X of your axis enum, which is just a named constant with a value of 0 ( Y is 1 and Z is 2 )
What you could do however in this particular case, is to substract 'X' from the character received from Serial, so, 'X' - 'X' is 0, 'Y' - 'X' is 1 and 'Z' - 'X' is 2 .
Of course, this won't work with names from the function enum
Thanks guix.
Yes, I realized the 'X' was anew one, not the one I receoved in the function, but I thought there is a way to get the original 'X'. Your suggestion is nice and I can use it. In the meantime I simply used pure numbers (0,1,2 for XYZ, similar to your suggestion).
As for the columns' names, there is no problem as they do not change in the program and I use them as they are and it runs nicely.
Thanks for nice reply. Same idea as guix.
As for your edit: I simply replaced the X with Z and it solves the problem.
byte ax = 'Z' - actual gives the same as your edit byte ax = actual - 'X'; //edited.