C++ documentation C documentation

Subtract a given value from the encoder counter.

This allows us to stop the internal counter from overflowing if the encoder continues to rotate in the same direction. This normally means updating another variable and then subtracting a value from the encoder. See the example below.

Syntax

Where *Encoder* is the name you have given to the device in Project Designer.

Parameters

Type | Name | Description |

'ticks'
| The number of ticks to reduce the current tick count by. |

Returns

None

Note

This will only effect the internal counter and so getTicks() will continue to return the original value until the next time read() is called.

Example

Assumptions:

- our encoder is called myEncoder in Project Designer

- 1000 ticks represent a distance travelled of 1cm.

We start by having a variable called 'distanceCM', which needs to be signed as the wheel can go forward and in reverse. So let's use an 'int32_t'.

Next: every time we have got at least 1000 ticks we will update our variable with 1 more centimetre and reduce the encoder counter by 1000. This means that the remaining value in the encoder will be between -999 and +999 represents the fraction of a centimetre.

So here is the code:-

int32_t distanceCM; // Distance in cm - automatically initialised to 0

// This routine is called repeatedly - its your main loop

TICK_CONTROL appControl(LOOP_COUNT loopCount, TICK_COUNT loopStart){

// Read the encoder and store the value

myEncoder.read();

// Get the current number of ticks

TICK_COUNT ticks = myEncoder.getTicks();

// Adjust for any whole cm

if( ticks >= 1000 ){

myEncoder.subtract(1000);

// Update my local variable as well

ticks -= 1000;

distanceCM++;

}else if( ticks <= -1000){

myEncoder.subtract(-1000);

// Update my local variable as weill

ticks += 1000;

distanceCM--;

}

// Print distance travelled to standard out

double total = ticks;

total /= 1000;

total += (double)distanceCM;

cout << "Distance = " << total << '\n';

}