Controling Stepper with fuzzy logic and PID controller


I work on some project that contains 64 step stepper motor (cheap),fan, arduino MEGA 1280 and ultasonic.

The purpose is to levitate the ball in a tube with a fan, and control the hight of the ball by opening and closing of the hatch on the tube.

The ultrasonic sensor has been used as feedback for close loop control system.

My problem is PID conroller and fuzzy logic.

For calculations I took ball speed and ball hight and I built rules.

But the ball would not restrain.

I think I need to build PID controller for stepper speed but I dont know how.

Please help me.
my code so far.

//fuzzy definitions
if (error>20) ball_pos=VHIGH;
if (error<=20 && error>2) ball_pos=LHIGH;
if (error<=2 && error>=-2) ball_pos=SPOINT;
if (error<-2 && error>-20) ball_pos=LLOW;
if (error<-20) ball_pos=VLOW;

 if (ball_speed>3) ball_sp=UPFAST;
 if (ball_speed<=3 && ball_speed>1) ball_sp=UPSLOW;
 if (ball_speed<=1 && ball_speed>=-1) ball_sp=STOP;
 if (ball_speed<-1 && ball_speed>-3) ball_sp=DOWNSLOW;
 if (ball_speed<-3) ball_sp=DOWNFAST;

//fuzzy rules
if( (ball_pos==VLOW && ball_sp==UPSLOW) //???      
    || (ball_pos==LLOW && ball_sp==UPSLOW) 
    || (ball_pos==SPOINT && ball_sp==STOP) 
    || (ball_pos==LHIGH && ball_sp==DOWNSLOW) 
    || (ball_pos==VHIGH && ball_sp==DOWNSLOW))  myStepper.step(0);
if ((ball_pos==LLOW && ball_sp==UPFAST)    //????? ????? 
    || (ball_pos==SPOINT && ball_sp==UPFAST)
    || (ball_pos==SPOINT && ball_sp==UPSLOW)
    || (ball_pos==LHIGH && ball_sp==UPFAST)
    || (ball_pos==LHIGH && ball_sp==UPSLOW)
    ||  (ball_pos==VHIGH && ball_sp==UPFAST) 
    ||  (ball_pos==VHIGH && ball_sp==UPSLOW)) {
 if ((ball_pos==VLOW && ball_sp==UPFAST) //????? ?????
    || (ball_pos==LHIGH && ball_sp==STOP) 
    ||  (ball_pos==VHIGH && ball_sp==STOP)) {

 if((ball_pos==VLOW && ball_sp==DOWNSLOW) //????? ?????
    || (ball_pos==VLOW && ball_sp==DOWNFAST) 
    || (ball_pos==LLOW && ball_sp==DOWNSLOW)
    || (ball_pos==LLOW && ball_sp==DOWNFAST) 
    || (ball_pos==SPOINT && ball_sp==DOWNSLOW)  
    || (ball_pos==SPOINT && ball_sp==DOWNFAST)
    || (ball_pos==LHIGH && ball_sp==DOWNFAST)) {
 if  ((ball_pos==VLOW && ball_sp==STOP)  //????? ?????
    ||  (ball_pos==LLOW && ball_sp==STOP)
       ||  (ball_pos==VHIGH && ball_sp==DOWNFAST)) {
         myStepper.step(4 );

Is this a straight or tapered tube? YOu will have a lot of difficulty keeping the ball height stable in a straight tube. The only way I would know to control the height with a damper would be to drill holes up the tube so that air can leak out, and adjust the damper against the leaking air. Otherwise, enough air to lift the ball will blow the ball to the top of the tube.

If you have access to MatLab you can build your fuzzy system there and use MakeProto’s Fuzzy Inference Translator to produce code for you.

You’ll still have to create the fuzzy system and link it up in Arduino code, but they provide the “meat”.

Good luck: