Go Down

### Topic: Using constrain() to limit servo movement (Read 2529 times)previous topic - next topic

#### ZacharyBruno

##### Dec 11, 2012, 04:09 am
After fiddling around with my dysfunctional, bloated Servo limit function, I decided to scrap it entirely and go with something else that was more intuitive. I knew that there must be something that would serve my purposes without using a bunch of if statements and switch statements. As it turns out--that function was constrain(). It's really easy to use if you have specific functions to adjust their respective servos. Here's how I did it:

Code: [Select]
`void Plane::Aileron(byte desiredDir, int increase) {  int deg;  switch(desiredDir) {       case RIGHT:        deg = aileronServo.read()-increase;      deg = constrain(deg, minAileronServoLimit, maxAileronServoLimit);      aileronServo.write(deg);    break;  case LEFT:...`

In this case, I calculate the original servo command, constrain it to my 2 global variables, minAileronServoLimit and maxAileronServoLimit, and then Servo.write() the resulting integer.

#### PeterH

#1
##### Dec 11, 2012, 03:01 pm
You didn't ask a question, so I will: what are RIGHT and LEFT for?

#### ZacharyBruno

#2
##### Dec 11, 2012, 03:36 pm
RIGHT, LEFT, STABLE, and RESET are the byte inputs from the parameter "desiredDirection". They control the direction/behavior of the aileron servos.

Something like Aileron(RIGHT, 5); would increment the aileron servos in the direction to make the plane roll to the right. The function is meant to be used in a loop.

#### PeterH

#3
##### Dec 11, 2012, 04:19 pm
That's a curious way to do it, but if it works for you then fair enough.

#### ZacharyBruno

#4
##### Dec 11, 2012, 04:39 pm
How would you do it?

#### PeterH

#5
##### Dec 11, 2012, 04:58 pm
I can't guess what the 'stable' and 'reset' functions are intended to do. Left and right appear to be relative moves. If I was controlling the aileron positions directly, I'd define separate methods to move the ailerons by a relative amount, to an absolute position, or whatever other type of movement I needed. I wouldn't lump all these different functions together into a single method with flags to say what functionality I was trying to access. Moving left and right are IMO essentially the same thing - moving by an amount which might be positive or negative - so I would expect one function to handle both directions.

Go Up