I'm working on a project where I need my arduino to detect the value of encoder at the instant the reading of the joystick change to 128. When the joystick is at rest, the reading is 128 which also means, my robot will hold its position/brake. Values above or below 128 correspond to the motor moving forward or backward.
I actually want to record the encoder value exactly at the first instant my arduino reads 128, so that I can apply PID position control so that my robot can brake or hold its position against gravity. The first instant when the joystick reads 128, that is the encoder value that I'd like to set as the Setpoint.
Here's some explanations for implementing PID in Arduino. http://playground.arduino.cc/Code/PIDLibraryConstructor
For instance the joystick readings go from 140, 137, 131, [128], 128, 128, 133, 139, 131, [128], 128 and at the same time, the encoder gives out corresponding values. I need the encoder values at the Joystick value of 128 in the square bracket, [] in the example above.
If I use the code below, it will just run the statements in {} whenever it sees 128, which is not what I want. FYI, the motor sometimes tend to backdrive, and this gives different encoder value also at 128. What I only need is the first encoder value at the first reading of 128 whenever I encounter it.
void loop()
{
int pwmSpeed;
int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);
Input = encoder0Pos;
if (Y_axis == 128)
{
Setpoint = encoder0Pos;
myPID.Compute();
analogWrite(pwm, Output);
}
else if (Y_axis > 128)
{
pwmSpeed = Y_axis;
digitalWrite(dir,HIGH); // set DIR pin HIGH or LOW
analogWrite(pwm, pwmSpeed); //analogWrite(pin, value)
}
else
{
pwmSpeed = abs(Y_axis-255);
digitalWrite(dir, LOW);
analogWrite(pwm, pwmSpeed);
}
}
Thanks.
//New edited code is shown below:
What do you think of the code? Did I do it correctly? I will test it once I get back to the lab.
If 128 is detected, encoder value is stored in Setpoint and then Pid.compute() is executed for as long as 128 is detected. For this duration, Pid.compute() will compute the error = Setpoint - Input and use Pid formula to calculate the Output that can be found in the analogWrite(pwm, Output). Motor will work to maintain its position at Setpoint.
However if other than 128 is encountered, it will just execute the 'else if' and 'else' statement to move the robot forward or backward.
global g_detect128 = false;
void setup()
{
//any code here
}
void loop()
{
int pwmSpeed;
int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);
Input = encoder0Pos;
if (!g_detect128 && Y_axis == 128)
{
Setpoint = encoder0Pos;
g_detect128 = true;
}
if (Y_axis == 128)
{
myPID.Compute();
analogWrite(pwm, Output);
}
else if (Y_axis > 128)
{
pwmSpeed = Y_axis;
digitalWrite(dir,HIGH); // set DIR pin HIGH or LOW
analogWrite(pwm, pwmSpeed); //analogWrite(pin, value)
}
else
{
pwmSpeed = abs(Y_axis-255);
digitalWrite(dir, LOW);
analogWrite(pwm, pwmSpeed);
}
if(Y_axis != 128)
{
g_detect128 = false;
}
}