Controlled Servo Sweep with Bluetooth

So like the title suggests, I want to control a servo motor using bluetooth module. I have mastered that aspect. But however, I want to go a step further.
So normally in a Blueooth sweep command, when I press th Up button on BT phone application, the servo moves from 0 degrees to 180 and conversely when I press the down button, the servo returns from 180 degrees to 0. But now I want to control the sweep action. So when I press Up button for instance, the servo goes from 0 deg. to 20 and stops. When i press up again, it goes from 20 to 40 and stops. Similary when I press down it goes back from 40 to 20 and stops. Basically, I want to control the servo to move in steps of 20 degrees to a maximum of 180 degrees and vice versa back to 0 degrees in steps of 20.

This is my code so far:


include <Servo.h>

char val;
int ledpin =13;
Servo servoMain;
int pos = 0;

void setup()
{
pinMode(ledpin, OUTPUT);
servoMain.attach(10);
Serial.begin(9600);

}

void loop()
{
if( Serial.available() )
{
;
}
val = Serial.read();

if(val == 0x32)
for (pos = 0; pos <= 180; pos += 20)
{
digitalWrite(ledpin, LOW);
servoMain.write(pos);
delay(200);
Serial.println("ledpin off");
}

if (val == 0x38)
for (pos = 180; pos >= 0; pos -= 20)
{
digitalWrite(ledpin, HIGH);
servoMain.write(pos);
delay(200);
Serial.println("ledpin on");
}
}


The val is defined command for the up and down buttons on the phone application.

You don't need the "for" any more. Just make pos = pos + 20 in the one "if" or pos - 20 in the other. Before you use the new pos in the servo.write() check to see if pos is now > 180 in which case pos =180, or < 0 in the other leg in which case make it 0.

I'm sorry, I really dont comprehend :confused: . Could you please put it down in layman terms.

Something like this:

if(val == 0x32) //going up
{
pos = pos +20;
    if (pos > 180) pos = 180; // otherwise if it was 180 already it would now be 200
                                        // this limits it to 180
servoMain.write(pos);
}

Wow, you been a big help. It works perfectly now. I did the exact opposite of your code for the decrement and it works flawlessy now. I really can't thank you enough. :slight_smile:

easy-8:
It works perfectly now

Great