===== Ball and Beam NXC Code =====
Use the additional library (dist-nx) to get the Infra Red sensor data. ( save it on the same folder of your NXC Code and include it using #include).
{{::dist-nx-lib.rar|}}
{{::nxc_codes.rar|}}
** NXT CODE **
{{:code1.jpg?direct|}}
{{::code2.jpg?direct|}}
{{::code_3.jpg?direct|}}
{{::code5.jpg?direct|}}
{{::code_6.jpg?direct|}}
** TUNING THE CODE **
After introducing the file saving function and the necessary commands to get the data , the system response was slowed down. ( oscillating more than before ). So i made some tuning:
* KP=1 and KD=0.60
* No waiting time inside the if statements
* 50ms waiting before starting the control loop again.
The new result is:
{{::the_last_response.jpg?direct|}}
{{youtube>Jp9xxLjVyi0?medium}}
** Modifying the Code **
One way to make the motor movement smoother is to change the rotation commands "PosRegAddAngle" for power commands "OnFwd" and use the power input as the PID equation ( Power=KP*(delta distance) + KD*(ball velocity). ).
Insted of using :
if (position >21)
{
PosRegAddAngle(OUT_A,-position);
Wait(18);
time=time+40;
}
// Ball is close to set point
if (position<21 & position >0)
{
PosRegAddAngle(OUT_A,0);
time=time+60;
}
if (position <0 & position>-21)
{
PosRegAddAngle(OUT_A,0);
time=time+60;
}
// Ball is far from the set point (negative side)
//Rotating positive angles make the beam go down
if (position < -21)
{
PosRegAddAngle(OUT_A,-position);
Wait(18);
time=time+40;
}
Wait(40);
// After rotating an angle , goes back to 0 degree ( equilibrium position ).
PosRegSetAngle(OUT_A,0);
You can just use:
power = KP*(dist-d_setpoint) + KD*(velocity);
OnFwd(OUT_A,power)
Depending on the direction of the ball , the power variable can change from positive to negative. And the "OnFwd" command with negative power argument runs exactly like the "OnRev".
You will have to change the gains a little bit (from using rotation commands to power commands ) , but it will make the platform to move smoother