Couple of issues.
The code you posted seems to be fundamentally flawed, because "
oldstate" always equals "
state".
Essentially,
oldstate = state = rc_dig_in05;
rtick will only increase if the encoder happens to "tick" exactly between those first two lines of the setting of
oldstate and the setting of
state. That can happen sometimes, but it would be pretty random. You want to avoid "windows" like this in your logic where all the ticks happening outside those first two lines are being ignored.
I assume you are polling the encoder, but are maybe polling it from the code slow loop? It should be polled from the fast loop. If you are running autonomously that would mean you need to call your function from User_Autonomous_Code() right before the line:
Code:
if (statusflag.NEW_SPI_DATA) /* 18.5ms loop area */
Make sure
oldstate is a global variable (I imagine it is since it's not declared within your function), or declared static (meaning it sticks around), and it gets initialized to something, e.g.,
Code:
void StartRightEncoder(void)
{
static unsigned char oldstate=0;
state = rc_dig_in05;
if(oldstate != state)
{
rtick++;
}
oldstate = state;
}
There are two ways an encoder can be implemented: polling or interrupt.
You should try both ways to get the experience.
- Polling is just checking the encoder every software loop.
Polling works if the encoder updates are slow enough. To be safe you should calculate how many ticks per second you expect and compare that to how fast your code is polling. Polling the encoder should be performed in the fast loop, so you are less likely to miss a tick. Polling too slow will cause you to miss ticks and go further than you wanted. As a rough rule of thumb you want to poll at least twice as fast as the ticks will come in.
For instance, the slow loop in the vex controller runs at 18.5ms, so it makes 54 loops per second. The vex encoder is 90 ticks per revolution, so if it's more than a quarter revolution per second you'll be dropping counts as it moves. For your case if the robot covers the 9 inches in less than 11 seconds you'd be getting faulty counts. On the other hand the fast loop might give you on the order of a hundred thousand polls per second, so you could safely cover that same distance in 5.4 milliseconds without losing count!
-Interrupts are more reliable for higher speed ticks in that whenever the encoder state changes the PIC hardware immediately notifies your software - sort of like a good poke in the side. No matter what else your code is doing it will stop, add the tick, and go back to what it was doing before.
P.S. You still must calculate how fast you expect the ticks to arrive to be sure the interrupts don't happen too fast to handle. The danger to watch out for here is getting so many interrupts per second that the PIC gets overwhelmed.