dsPIC30F Quadrature Encoder Interface (QEI) – Basic Example

This video shows a basic example of using the Quadrature Encoder Interface (QEI) on Microchip’s dsPIC30F4011 microcontroller. I expect that the same approach will work with other microcontrollers in the dsPIC30F family.

In this example, I place two TCRT5000 reflective infrared sensors in front of a spinning black and white checkered disc to generate a pair of quadrature encoded signals. These signals are connected to pins QEA and QEB (the QEI input pins) on the dsPIC. The program shown in the example enables QEI so that the rotation of the disc is recorded in the POSCNT (position count) register. The value of POSCNT is printed via UART every 200 ms, so that it can be monitored on the PC screen.

This is the complete code:

// Quadrature Encoder Interface (QEI) example for dsPIC30F4011
// Written by Ted Burke, Last updated 12-4-2017

#include <xc.h>
#include <libpic30.h>
#include <stdio.h>
// Configuration settings
_FOSC(CSW_FSCM_OFF & FRC_PLL16); // Fosc=16x7.5MHz, i.e. 30 MIPS
_FWDT(WDT_OFF);                  // Watchdog timer off
_FBORPOR(MCLR_DIS);              // Disable reset pin
void main()
    // Use RD0 to blink an LED so that we can see program in running
    _TRISD0 = 0;
    // Setup UART so that we can monitor POSCNT value
    U1BRG = 48;            // 38400 baud @ 30 MIPS
    U1MODEbits.UARTEN = 1; // Enable UART
    // To use pins 6 and 7 as QEA and QEB (quadrature encoding inputs)
    // analog input must be disabled on both pins by setting the bits
    // for AN4 and AN5 in the ADPCFG register.
    _PCFG4 = 1;
    _PCFG5 = 1;
    // Enable the QEI module (x4 mode with POSCNT reset by MAXCNT match)
    _QEIM = 0b111;

        // Print current value of position counter register
        printf("POSCNT = %d\n", POSCNT);
        _LATD0 = 1;         // LED on
        __delay32(3000000); // 100 ms
        _LATD0 = 0;         // LED off
        __delay32(3000000); // 100 ms
This entry was posted in Uncategorized. Bookmark the permalink.

2 Responses to dsPIC30F Quadrature Encoder Interface (QEI) – Basic Example

  1. Gaël says:

    Hello and a big thanks for this video, the only one I’ve found :)I’ve tried to make qudrqture encoder with arduino but it only works on small motor speed. so with the pic 24 140 Mhz with QEI I hope it will work 🙂

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 )

Connecting to %s