There are two ways of reading an encoder that has been assigned to a motor in the motor&sensor setup dialog.
nMotorEncoder is passed the motor port and will always return incrementing values when the motor has been commanded with positive control values. However, this assumes the following.
- The motor has not been reversed by swapping the polarity of the motor connection, ie. make sure red and black wires are not swapped.
- If using an old red quad encoder, the A and B connections are made correctly, this may need some trial and error as it’s never obvious which way to connect these.
Using sensorValue to read the encoder does not automatically change the encoder value if the reverse flag has been set in the M&S setup dialog, I would avoid using this function for encoders if possible.
Also understand that in the situation that you have two encoders configures for left and right drive motors, it is very unlikely they will ever have exactly the same count. You should allow some tolerance and adjust the code to say (in english) “if the two encoder almost match then” …
Something like this (untested, I may have l/r reversed)
#pragma config(I2C_Usage, I2C1, i2cSensors)
#pragma config(Sensor, I2C_1, , sensorQuadEncoderOnI2CPort, , AutoAssign )
#pragma config(Sensor, I2C_2, , sensorQuadEncoderOnI2CPort, , AutoAssign )
#pragma config(Motor, port1, leftMotor, tmotorVex393_HBridge, openLoop, encoderPort, I2C_1)
#pragma config(Motor, port10, rightMotor, tmotorVex393_HBridge, openLoop, reversed, encoderPort, I2C_2)
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//
nMotorEncoder[rightMotor] = 0;
nMotorEncoder[leftMotor] = 0;
while(nMotorEncoder[rightMotor] < 600)
// almost the same
if( abs( nMotorEncoder[leftMotor] - nMotorEncoder[rightMotor] ) < 20 )
motor[rightMotor] = 105;
motor[leftMotor] = 105;
// speedup right, slow left
if( (nMotorEncoder[leftMotor] - nMotorEncoder[rightMotor]) > 20 )
motor[rightMotor] = 127;
motor[leftMotor] = 90;
// speedup left, slow right
if( (nMotorEncoder[rightMotor] - nMotorEncoder[leftMotor]) > 20 )
motor[rightMotor] = 90;
motor[leftMotor] = 127;