Hii everyone,
im working on a project and i need to enter the PWM speed into a function and find the direction of the movement, so if PWM is positive my direction is 1 and if its negative my direction is 0 (if PWM is zero then the direction is 2). i need to do this over 12 times in each loop so i decided to use a function instead:
void axisDirFinder (double spd, int dir){
if (spd > 0){
dir = 1;
}
else if (spd < 0){
dir = 0;
}
else{
dir = 2;
}
}
the weird thing is that the code itself is super simple and works if I use the if statement directly in my code, but when I call this functions instead, nothing happens. I've been trying to figure this out for hours now but I can't seem to see the problem. any help would be highly appreciated.
That's going to have something to do with where "dir" is declared.
You have "int dir" in the call to the function (not sure why, since surely you're not passing dir in anyway?) so the "dir" which gets given the value 0, 1 or 2 in the function is local to the function.
I'm going to guess you have another "dir" declared somewhere else and that's the one you think is getting changed, but only the one inside the function is changed.
So lose the "int dir" in the function call and have "dir" declared elsewhere as a global..
For bonus marks, don't make the function void, but have it return dir rather.
Just use this code- It is super simple. I understand what are you trying to do in the code. You don't have to use void function, you need to use the int function. Just put my code at the start of your code.
int dir(double spd)
{
if (spd > 0){
dir = 1;
}
else if (spd < 0){
dir = 0;
}
else{
dir = 2;
}
return dir;
}
The return dir is the most important function to get the dir.
evadne:
That's going to have something to do with where "dir" is declared.
You have "int dir" in the call to the function (not sure why, since surely you're not passing dir in anyway?) so the "dir" which gets given the value 0, 1 or 2 in the function is local to the function.
I'm going to guess you have another "dir" declared somewhere else and that's the one you think is getting changed, but only the one inside the function is changed.
So lose the "int dir" in the function call and have "dir" declared elsewhere as a global..
For bonus marks, don't make the function void, but have it return dir rather.
that makes so much sense thanks! i have three axes (r, theta, and z) and i declare their direction at the top of my code before the setup function.
ArnavPawarAA:
Just use this code- It is super simple. I understand what are you trying to do in the code. You don't have to use void function, you need to use the int function. Just put my code at the start of your code.
int dir(double spd)
{
if (spd > 0){
dir = 1;
}
else if (spd < 0){
dir = 0;
}
else{
dir = 2;
}
return dir;
}
The return dir is the most important function to get the dir.