Is there a way to find the direction of the potentiate, maybe by taking its position twice then subtracting and seeing if it is negative? If so, how would you put that in an if statement.

# Detecting the direction of a potentiometer

**Codec**#2

A assume you meant direction of movement. Yes you can measure the position twice then subtract to get the speed. One way will be positive and the other will be negative. Just make sure that there is enough time between the two measurements.

**jokeywho**#3

Could you show some example code for that? Semi-new to robotc, not exactly sure how to impliment this.

**Codec**#4

```
float speed = 0;
int previousValue = 0;
long previousReading = -1;
while(true)
{
if(nSysTime - previousReading > 250 || previousReading == -1)
{
if(previousReading != -1) speed = SensorValue[pot] - previousValue;
previousValue = SensorValue[pot];
previousReading = nSysTime;
}
if(speed > 0) {} //moving in one direction
if(speed < 0) {} //moving in the other direction
delay(5);
}
```

This takes a measurement every 250 milliseconds or every 0.25 seconds and calculates the speed. Also when previousReading is -1 (only happens in the beginning) it does update the speed because then it would be incorrect due the previousValue being incorrect.

**jokeywho**#5

So if I were to use this to control a claw, would I just calculate that with a lot of if statements for what the measurement is

if (SensorValue[pot]>100 && <150 {

}

else if…

**Codec**#6

If the potentiometer is on a claw you should use a simple pid controller. For your purposes you can do it with just a p controller…

```
float Kp = 0.1;
int targetPosition = 1000;
while(true)
{
int error = targetPosition - SensorValue[pot];
motor[clawMotor] = Kp * error;
delay(5);
}
```

This will move the claw to the target position, but you have to figure out the right value for `Kp`

first. If you run this code and the motor spin the wrong way than `Kp`

has to be negative. Then if the motor gets to the right position but goes to far and then moves back and forth you need to lower the `Kp`

value. If the motor doesn’t go far enough then you should raise the `Kp`

value. Then that is working you set the `targetPosition`

to a value and the motor will turn to that position.