PIC32MX: Encoder Motor Control

From Mech
Revision as of 11:08, 13 August 2009 by Andrew Long (talk | contribs) (New page: ==Available Pins== The PIC32MX460F512L has 5 available external timer / counter pins denoted TXCK on the pin list, where x is from 1 to 5. Unfortunately, the PIC32MX440F512H has only 1 av...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Available Pins

The PIC32MX460F512L has 5 available external timer / counter pins denoted TXCK on the pin list, where x is from 1 to 5. Unfortunately, the PIC32MX440F512H has only 1 available external counter (T1CK), so this cannot be used for quadrature encoder.

Quadrature Encoder Example

This section details how to set up quadrature encoder with the PIC32MX460F512L and the LS7083.

Sample Code

First include header files with definitions for generic type definitions, compiler, and for specific PIC. Also include the plib header file.

  #include "GenericTypeDefs.h"
  #include "Compiler.h"
  #include "HardwareProfile.h"
  #include <plib.h>

NOTE THAT BECAUSE WE USE THE BOOTLOADER, NO CONFIGURATION IS NECESSARY. THE BOOTLOADER PROJECT ACTUALLY CONTROLS ALL OF OUR CONFIG BITS.

Define the system frequency

  #define SYS_FREQ 				(80000000L)

Define global variables for counting

   signed int bigcount = 0; 	// set encoder value initially to zero, it can go + or -
                               // 32 bit number
   short count0, count1; 		// 16 bit number
   short last0 = 0, last1 = 0; // 16 bit number

Begin main function

  int main(void)
  {

Configure the proper PB frequency and the number of wait states

  SYSTEMConfigPerformance(SYS_FREQ);

Initialize Timer1 and Timer2 as external clocks and periods (PR1, PR2)

  OpenTimer1( T1_ON | T1_PS_1_1 | T1_SOURCE_EXT, 0xFFFF);
  OpenTimer2( T2_ON | T2_PS_1_1 | T2_SOURCE_EXT, 0xFFFF);

main loop

  while (1)
  {
     count0 = ReadTimer1();  // in your routine this must be done at least every 32000
                             // encoder counts to avoid rollover ambiguity
     count1 = ReadTimer2(); 	
     bigcount += count0 - last0; // add on the recent up-counts, since the last time
     
     if (count0 < last0)
     {
        bigcount += 65536; 		// count0 only increments, so if it got lower 
                                       //it must have rolled over
     }
     last0 = count0;
     bigcount -= count1 - last1; // we're not worrying about rollover of the 32 bit bigcount total
     if (count1 < last1)
     {
         bigcount -= 65536;
     }
     
     last1 = count1; 

Put Code to Display Here I put the above code in the Communicate Via USB Code and added the following lines:

  sprintf (USB_Out_Buffer, "Encoder Count = %d!\r\n", bigcount);
  if(mUSBUSARTIsTxTrfReady())
  {
  putrsUSBUSART(USB_Out_Buffer);
  }

end the main function

  return 0;
  }