Using Quadrature Encoders


I just added a piece of code to handle the encoders I am using on my project. Couldn’t find any library or any details actually on this subject for LPC1225 so I had to do it from scratch.

Anyway, for start let’s see how the waveforms looks like. Based on the direction the motor spins the waveforms will look slightly different:

q encoders - A leading B

Motor spin in one direction.

q encoders - B leading A

Motor spin in a different direction.

Now, we’ll need to be able to read this information and for this we’ll use external interrupts triggered on raising and falling edges:

q encoders - interrupts on raising and falling edges

Trigger an interrupt on each edge for each signal.

Will use IRQ2 for this:

void initExtInt (){
    LPC_SYSCON->SYSAHBCLKCTRL |= (1<<6);
    NVIC_EnableIRQ(EINT2_IRQn);
    ENCAINTALL;
    ENCBINTALL;
}

In IRQ2 handler I am doing the checking for directions too that allows us to determine the direction and calculate the pulses to compensate for change in direction:

void PIOINT2_IRQHandler (void){
	if (LPC_GPIO2->MIS & (ENCA)){
		if (((ENCB_STATE) && (!ENCA_STATE)) || ((!ENCB_STATE) && (ENCA_STATE)))
                      qeLeftRear++;
		else 
                      qeLeftRear--;

		LPC_GPIO2->IC |= (ENCA);
	}

	if (LPC_GPIO2->MIS & (ENCB)){
		if (((ENCA_STATE) && (!ENCB_STATE)) || ((!ENCA_STATE) && (ENCB_STATE))) 
                      qeLeftRear--;
		else 
                      qeLeftRear++;

		LPC_GPIO2->IC |= (LBENCB);
	}
}

And the macros used for this:

#define ENCA		(1UL<<4)	// P2.4
#define ENCB	   	(1UL<<5)	// P2.5 

#define ENCA_IN   	LPC_GPIO2->DIR &= ~ENCA
#define ENCB_IN   	LPC_GPIO2->DIR &= ~ENCB

#define ENCAINTALL	{LPC_GPIO2->IS &= ~(ENCA);LPC_GPIO2->IBE |= (ENCA);LPC_GPIO2->IE |= ENCA;}
#define ENCBINTALL	{LPC_GPIO2->IS &= ~(ENCB);LPC_GPIO2->IBE |= (ENCB);LPC_GPIO2->IE |= ENCB;}

Now we have the readings from our encoder in qEncCounter variable to use it the way we want.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s