magnetic angle tracker application using the cip...

16
2017 Microchip Technology Inc. DS00002373A-page 1 AN2373 INTRODUCTION The objective of this application note is to highlight the functionality and advantages of using the Math Accelerator with Proportional-Integral-Derivative (PID) control, a Core Independent Peripheral (CIP), present on various Microchip microcontroller devices, such as the PIC16F16XX family. For more information on other Core Independent Peripherals refer to www.microchip.com/CIP . In this application note, a case study demonstrates the use of the Math Accelerator to compute the inverse tangent function tan -1 x using the Addition/Multiplication mode of the CIP. MATH ACCELERATOR WITH PID Several products in the PIC ® device family have a Math Accelerator module to perform 16-bit multiplication and addition in hardware, along with 35-bit signed results registers. The PID module can be configured either as a PID controller or as a multiply and accumulate module. Multiply and accumulate can be performed in four modes: Unsigned multiply and add, without accumulation Unsigned multiply and accumulate Signed multiply and add, without accumulation Signed multiply and accumulate When the MODE<2:0> bits of the PIDxCON register are equal to ‘000’, ‘001’, ‘010’, or ‘011’, the module is in Add and Multiply mode. The data flow diagram of the Multiply and Add modes is shown in Figure 1. Since the Math Accelerator shares the registers with the PID module, all the names are related to PID control. As shown in Figure 1, PIDxIN and PIDxSET are the two inputs to the adder. The result of the adder and PIDxK1 are the inputs of the multiplier. There is an adder which adds up to itself to do the accumulation of the output. The result of the calculation is stored in PIDxOUT. The Add and Multiply modes perform operations of the following equation form: EQUATION 1: ADD AND MULTIPLY MODE The operand terms have to be loaded into the PID input registers before performing the add or multiply operation. To execute an add computation, simply set C (PIDxK1) to ‘1’. To execute a multiply computation, it is better to set B (PIDxSET) to ‘0’ and use A and C, since the module uses PIDxINL to trigger the computation. Refer to TB3134, “16-Bit Multiplication and Addition by using the Math Accelerator Peripheral on PIC16(L)F161X” (DS9003134) for the initial setup procedure and the operation of the Math Accelerator module. Author: Rashmi Krishnamurthy Microchip Technology Inc. OUTPUT A B + C = Note: A = PIDxIN, B = PIDxSET, and C = PIDxK1 Magnetic Angle Tracker Application Using the CIP Math Accelerator with PID Controller

Upload: others

Post on 29-Jan-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Magnetic Angle Tracker Application Using the CIP …ww1.microchip.com/downloads/en/AppNotes/00002373A.pdf(CIP) on this device such as Math Accelerator with PID, Configurable Logic

AN2373Magnetic Angle Tracker Application Using the CIP Math Accelerator with PID Controller

INTRODUCTION

The objective of this application note is to highlight thefunctionality and advantages of using the MathAccelerator with Proportional-Integral-Derivative (PID)control, a Core Independent Peripheral (CIP), presenton various Microchip microcontroller devices, such asthe PIC16F16XX family.

For more information on other Core IndependentPeripherals refer to www.microchip.com/CIP.

In this application note, a case study demonstrates theuse of the Math Accelerator to compute the inversetangent function tan-1x using the Addition/Multiplicationmode of the CIP.

MATH ACCELERATOR WITH PID

Several products in the PIC® device family have a MathAccelerator module to perform 16-bit multiplication andaddition in hardware, along with 35-bit signed resultsregisters. The PID module can be configured either asa PID controller or as a multiply and accumulatemodule.

Multiply and accumulate can be performed in fourmodes:

• Unsigned multiply and add, without accumulation

• Unsigned multiply and accumulate

• Signed multiply and add, without accumulation

• Signed multiply and accumulate

When the MODE<2:0> bits of the PIDxCON registerare equal to ‘000’, ‘001’, ‘010’, or ‘011’, the module isin Add and Multiply mode.

The data flow diagram of the Multiply and Add modesis shown in Figure 1.

Since the Math Accelerator shares the registers withthe PID module, all the names are related to PIDcontrol. As shown in Figure 1, PIDxIN and PIDxSETare the two inputs to the adder. The result of the adderand PIDxK1 are the inputs of the multiplier. There is anadder which adds up to itself to do the accumulation ofthe output. The result of the calculation is stored inPIDxOUT.

The Add and Multiply modes perform operations of thefollowing equation form:

EQUATION 1: ADD AND MULTIPLY MODE

The operand terms have to be loaded into the PID inputregisters before performing the add or multiplyoperation. To execute an add computation, simply setC (PIDxK1) to ‘1’. To execute a multiply computation, itis better to set B (PIDxSET) to ‘0’ and use A and C,since the module uses PIDxINL to trigger thecomputation.

Refer to TB3134, “16-Bit Multiplication and Addition byusing the Math Accelerator Peripheral onPIC16(L)F161X” (DS9003134) for the initial setupprocedure and the operation of the Math Acceleratormodule.

Author: Rashmi KrishnamurthyMicrochip Technology Inc.

OUTPUT A B+ C=

Note: A = PIDxIN, B = PIDxSET, andC = PIDxK1

2017 Microchip Technology Inc. DS00002373A-page 1

Page 2: Magnetic Angle Tracker Application Using the CIP …ww1.microchip.com/downloads/en/AppNotes/00002373A.pdf(CIP) on this device such as Math Accelerator with PID, Configurable Logic

AN2373

FIGURE 1: DATA FLOW DIAGRAM OF THE MATH ACCELERATOR IN THE ADDITION/MULTIPLICATION MODE

CASE STUDY: MAGNETIC ANGLE TRACKER

The case study demonstrates the use of the MathAccelerator to compute the inverse tangent functiontan-1x using the Addition/Multiplication mode of theCIP. PIC16F1619 was chosen for this project becauseof the availability of the Core Independent Peripherals(CIP) on this device such as Math Accelerator with PID,Configurable Logic Cell (CLC), SPI, PWM, ADC, DAC,Peripheral PIN Select (PPS) modules required for theapplication.

Magnetic Angle Sensor

For the case study described in this application note,the angle sensor used is the NVE AAT001-10ETunneling Magneto-Resistance (TMR) angle sensor.

TMR Technology

Tunneling Magneto-Resistive (TMR) effect is aphenomenon that occurs in ferro magnetic materials.

When two ferro-magnets are separated by a thininsulator, a magnetic junction is formed. Each sensorelement consists of a combination of multiple magneticlayers: pinned layers and free layers. Upon theapplication of an external magnetic field, the free layersalign themselves in the direction of the field. Thiscauses a change in the resistance of the material,which in turn changes the output voltages of the anglesensor.

FIGURE 2: INTERNAL BRIDGE CONFIGURATION OF THE ANGLE SENSOR

The AAT001-10E device contains four sensingresistors with the pinned layer 90 degrees apart. Theresistors are connected as two half-bridges, providingsine and cosine outputs. The internal structure of thehalf bridges of the sensor is shown in Figure 2.Variations in the air gap between the magnet and thesensor element will cause slight changes in the outputdepending on the size and strength of the externalmagnet.

Rev. 10-000228A4/7/2015

Adder+

+

PIDxIN

PIDxSET

Multiplier

PIDxK1

Adder+

+ PIDxOUT

PIDxACC

10MODE<0>

0

RCOS1 RCOS2

RSIN1

RSIN2

VCC

COSINE SINE

GND

Rotation of magnet

DS00002373A-page 2 2017 Microchip Technology Inc.

Page 3: Magnetic Angle Tracker Application Using the CIP …ww1.microchip.com/downloads/en/AppNotes/00002373A.pdf(CIP) on this device such as Math Accelerator with PID, Configurable Logic

AN2373

Sensor Output Calibration

The outputs of the AAT001-10E angle sensor are in theform of sine(Y) and cosine(X) waveforms. Thesesignals can be expressed as follows:

EQUATION 2: SINE AND COSINE WAVEFORMS

The angle between the sine(Y) and the cosine (X) sig-nals can be denoted as follows:

EQUATION 3: ANGLE CALCULATION

The direct computation of the angle using the outputsignals of the sensor will result in inaccurate anglevalues and the resulting vector of X and Y signals willhave an elliptical shape as shown in Figure 3, since thesignals include amplitude, offset and orthogonalityerrors.

A calibration routine is implemented to reduce the errorin the signals. After calibration, the resulting vector of Xand Y signals will have a circular shape as shown inFigure 4. The calibration routine is as follows:

1. Turn the field 360 degrees in the clockwisedirection and measure X and Y values.

2. Calculate the amplitude and offset correctionvalues of the clockwise turn.

3. Turn the field 360 degrees in thecounterclockwise direction and measure X andY values.

4. Calculate the amplitude and offset correctionvalues of the counterclockwise turn.

5. Calculate the mean values of the amplitude andthe offset correction.

The purpose of the calibration process is to calculatethe amplitude and offset correction values. Bothclockwise and counterclockwise measurements aretaken to reduce error due to the physical rotation of theexternal magnet. The calibration method used in thiscase study is the MIN-MAX method. This method isbriefly explained in the following section.

MIN-MAX METHOD

Xmax, Xmin, Ymax, Ymin have to be obtained from thefull turn clockwise and counterclockwise rotations ofthe magnetic field around the angle sensor.

The amplitude error and the offset error can becomputed using Equation 4 as follows:

EQUATION 4: AMPLITUDE ERROR CALCULATION

Equation 6 is applied to both the clockwise andcounterclockwise min and max values. ACW and ACCWare clockwise and counterclockwise amplitude errorparameters, OCW and OCCW are clockwise andcounterclockwise offset error parameters.

The mean parameters of correction for both the x andy signals are calculated as follows:

EQUATION 5: MEAN ERROR CALCULATION

The orthogonality error is not computed in thiscalibration routine. The next step is to normalize the Xand Y values by using the mean values determined inthe calibration.

EQUATION 6: FINAL CALIBRATED SENSOR OUTPUT

The sensor output characteristics before calibration areshown in Figure 3.

X ACOS z cos OffsetCOS+=

Y ASIN z sin OffsetSIN+=

ACOS= Amplitude of X (cosine) waveform

ASIN= Amplitude of Y (sine) waveform

z= Angle between the cosine and sine waveform

OffsetCOS= Offset of X (cosine) waveform

OffsetSIN= Offset of Y (sine) waveform

z arc Y X tan=

Ax Xmax Xmin– 2=

Ay Ymax Ymin– 2=

Ox Xmax Xmin+ 2=

Oy Ymax Ymin+ 2=

Amplitude Error Amean ACW ACCW+ 2=

Offset error Omean OCW OCCW+ 2=

CW = Clockwise parameters

CCW = Counterclockwise parameters

mean = Mean parameters

X1 = X - Omean

Y1 = Y = Omean

X2 = X1/Amean

Y2 = Y1/Ymean

X1 and Y1 and the offset corrected values

X2 and Y2 and amplitude corrected values which areused in Equation 3 to calculated the angle.

2017 Microchip Technology Inc. DS00002373A-page 3

Page 4: Magnetic Angle Tracker Application Using the CIP …ww1.microchip.com/downloads/en/AppNotes/00002373A.pdf(CIP) on this device such as Math Accelerator with PID, Configurable Logic

AN2373

The sensor output characteristics after the calibrationroutine is shown in Figure 4. Note that the origin of thecalibrated output voltages has shifted to the origin andthe amplitude error is corrected as well. This procedureprovides the accurate angle value between the two

sensor output voltages. Example 2 in Appendix A:“Code Snippets” provides the Function to Read theAmplified Sensor Voltages and Perform ADCConversion.

FIGURE 3: ANGLE SENSOR OUTPUT CHARACTERISTICS

FIGURE 4: ANGLE SENSOR OUTPUT CHARACTERISTICS

00.5

11.5

22.5

3

1 11 21 31 41 51 61

X,Y

outp

uts

Sample Number

Angle Sensor Output Characteristics

X - cosine

Y- Sine

0

0.5

1

1.5

2

2.5

3

0 1 2 3

Uncalibrated output voltages

-1.5

-1

-0.5

0

0.5

1

1.5

1 11 21 31 41 51 61

X2, Y

2 O

utpu

ts

Sample Number

Calibrated Angle Sensor Output Characteristics

X- Cosine

Y- Sine

-1.5

-1

-0.5

0

0.5

1

1.5

-1.5 -1 -0.5 0 0.5 1 1.5

Calibrated output Volatges

DS00002373A-page 4 2017 Microchip Technology Inc.

Page 5: Magnetic Angle Tracker Application Using the CIP …ww1.microchip.com/downloads/en/AppNotes/00002373A.pdf(CIP) on this device such as Math Accelerator with PID, Configurable Logic

AN2373

INVERSE TANGENT (ARCTAN) FUNCTION

Inverse trigonometric functions are used to find theunknown value of an angle of a right triangle when twoside lengths are known. For each of the standardtrigonometric functions, such as sin, cos, tan, etc., is aninverse of the function, such as arcsin, arccos, andarctan.

The tangent of an angle theta, ө, is the ratio of theopposite side by hypotenuse in a right angle triangle.The inverse tangent tan-1(z) is the inverse function ofthe tangent function. The inverse tangent is themultivalued tan-1(z) function also denoted as arctan (z).The associated trigonometric terms are denoted inFigure 5. The formula for the inverse tangent functionin terms of sin() and cos () is provided in Equation 7.

EQUATION 7: THETA IN TERMS OF INVERSE TANGENT FUNCTION

FIGURE 5: RIGHT ANGLE TRIANGLE

The expansion of the tan-1(z) function according to theMaclaurin series is as follows:

EQUATION 8: MACLAURIN SERIES EXPANSION OF tan-1(z)

With the help of a case study, the implementation of theinverse tangent function to calculate the angle betweenthe analog voltage outputs of a magnetic angle sensoris described. Compared to the software arctangentfunction, the hardware CIP implementation can reducethe number of instruction cycles for the computation upto half. An average calculation using the software atan2function takes 2.5 ms when the system clock is runningat an internal oscillator frequency of 16 MHz.

On the other hand, the average time for the samecalculation performed using the Math Acceleratormodule takes 1.25 ms. Once the angle has beencalculated and a change in the magnetic field occurs,the resulting angle can be quickly recalculated.

Signal Amplification

The output of the angle sensor has a voltage measuredpeak-to-peak of about 200-250 mV. To get better rangeon the 10-bit ADC on the PIC16F1619, the two sensoroutput voltages are amplified using the MCP604 linearquad operational amplifier in the non-inverting amplifierconfiguration shown in Figure 6. For more informationon the analog op amp, refer to the device data sheet,which can be found on the web page,www.microchip.com/mcp604.

The resistor values in the circuit are selected to achievean output gain of four. The AN_COS and AN_SINsignals have a measured voltage peak-to-peak of 800-1000 mV, that is sensed with the microcontroller’s ADCmodule.

AN_COS and AN_SIN are the two amplified signals,provided as analog inputs to the microcontroller‘s ADCmodule.

Ɵ = tan–1 Opposite

Adjacent( ) = tan–1 Opposite/Hypotenuse

Adjacent/Hypotenuse( ) = tan–1 sin Ɵ

cos Ɵ( )

Opposite Hypotenuse

Adjacent

θ

tan1–

z

n 0= z13---z

3 15---z

5 17---z

7 +–+–= =

2017 Microchip Technology Inc. DS00002373A-page 5

Page 6: Magnetic Angle Tracker Application Using the CIP …ww1.microchip.com/downloads/en/AppNotes/00002373A.pdf(CIP) on this device such as Math Accelerator with PID, Configurable Logic

AN2373

FIGURE 6: SIGNAL AMPLIFICATION CIRCUIT USING THE MCP604

Sensor Interface with PIC16F1619

The amplified sensor voltages are measured by theinternal 10-bit (ADC) module present on thePIC16F1619. Figure 7 shows the block diagram of theinterface between the sensor and the PICmicrocontroller.

The critical step in the ADC module configuration ischoosing the correct conversion clock and theacquisition delay time. In this application, the ADCFRC

clock is used as the clock source for the ADC module.This gives an ADC clock period between 1-6 us. A fixedamount of time is required for acquisition of the signalfor the sample and hold capacitor to charge and sensethe analog signals accurately. If the ADC timingconsiderations are not met, it results in missing codesin the ADC count. Please refer to the PIC16F1619 Datasheet for complete information on the ADC conversionclock selection and the acquisition delay requirements.

FIGURE 7: INTERFACE BLOCK DIAGRAM

R1 10K

R3 30K

R2 30K

R4 10K

R5 10K

C1

C3

C2

DAC1OUT

ANCOSIN

AN_COS

AN_SIN

ANSINEIN

3.3V

3.3V

3.3V

Analog to DigitalConverter

PIC16F1619

Angle Calculation Block

Returns angle value in radians

Cosine Analog input

Sine Analog input

DS00002373A-page 6 2017 Microchip Technology Inc.

Page 7: Magnetic Angle Tracker Application Using the CIP …ww1.microchip.com/downloads/en/AppNotes/00002373A.pdf(CIP) on this device such as Math Accelerator with PID, Configurable Logic

AN2373

Angle Calculation

The expansion of the arctangent function has multiplesolutions. In the math.h library file in ‘C’ language, thearctangent function is represented as atan2 function.This function has two arguments, x and y where x andy are the instantaneous sine and cosine signal values,respectively, as expressed in Equation 9 below. Theflowchart for Equation 9 is shown in Figure 9.

EQUATION 9: EXPANSION OF ATAN2 FUNCTION

The first step in angle calculation is to compute thearctan value using the Maclaurin expansion of tan-1x asprovided in Equation 8.

From the expansion, the critical computation term isidentified as z2. The value of the z2 term is calculatedby the Math Accelerator module in the PIC16F1619. Itshould be noted that the Math Accelerator module used50% less instruction cycles than software computation.

Once the z2 term is computed, the remaining terms ofthe polynomial given by Equation 8 are calculated, toobtain the solution of the angle value in radians.

The angle in degrees can be computed as follows:

EQUATION 10: CONVERT ANGLE RADIANS TO DEGREES

The following figure is the flowchart representation ofthe steps in calculating the angle in radians.

FIGURE 8: FLOWCHART REPRESENTATION OF THE STEPS IN CALCULATING THE ANGLE IN RADIANS

Refer to Appendix A: “Code Snippets” to the codesnippets for calculating the angle.

2atan y x

arcyx-- tan

arcyx-- +tan

arcyx-- –tan

2---

2---–

undefined

=

x > 0

y x < 0

y x < 0

y x = 0

y x = 0

y x = 0

Angle (in degrees) Angle (in radians) 180 =

START

Store the variables,constants

Calculate (z)*(z)using the MATH

Accelerator

Evaluate the polynomial given by Equation .

Return the value of the angle in

radians

STOP

2017 Microchip Technology Inc. DS00002373A-page 7

Page 8: Magnetic Angle Tracker Application Using the CIP …ww1.microchip.com/downloads/en/AppNotes/00002373A.pdf(CIP) on this device such as Math Accelerator with PID, Configurable Logic

AN2373

FIGURE 9: FLOWCHART OF THE INVERSE TANGENT FUNCTION EXPANSION WITH DIFFERENT CONDITIONS

START

Is x==0

Is y==0 Return 0

Return pi/2

Return -pi/2

Is y==0

Is x>0 Return 0Return pi

Is abs(x)>abs(y)

Calculate the angle for (y/x)

and return value in rad.

Calculate the angle for (x/y) andreturn value in rad.

STOP

Is y>0YES YES

NOYES

NO

NO

YES

YESNONO

YES

NO

DS00002373A-page 8 2017 Microchip Technology Inc.

Page 9: Magnetic Angle Tracker Application Using the CIP …ww1.microchip.com/downloads/en/AppNotes/00002373A.pdf(CIP) on this device such as Math Accelerator with PID, Configurable Logic

AN2373

Figure 10 shows the distribution of the computed anglevalues (in degrees) for the calibrated sensor output inFigure 4.

FIGURE 10: DISTRIBUTION OF THE COMPUTED ANGLE VALUES (IN DEGREES) FOR THE CALIBRATED AAT001-10E ANGLE SENSOR

Serial LEDs and Indication

WS2812B Serial LEDs are used to indicate angle onthe demo board. The LEDs are cascaded together toform a 24 LED ring, indicating the angles from 0 to 360degrees.

One digital CLC output I/O is used to control all the 24LEDs. Each LED requires 24 bits to set the intensity ofeach color in the order of 8 bits for Green, 8 bits for Redand 8 bits for Blue. Any remaining data is then passedonto the next LED through the DOUT pin of the LED.

Refer to the application note AN1606, “Using theConfigurable Logic Cell (CLC) to Interface aPIC16F1509 and WS2811 LED Driver” (DS00001606),which describes how to combine SPI and a PMWthrough the CLC to create the required waveform. Theapplication note describes the operation of the WS2811LEDs but the similar concept applies for WS2812B aswell. The method used in this application is very similarto the one described in the application note with theexception of using only one CLC instead of two.Reference to the CLC setup using MCC diagram isshown in Figure 11.

The LEDs require critical timing and duty cycle settings.It is important to set up with correct clock rate on theSPI and correct timing and duty cycle for TMR2/PWMx.

EQUATION 11: SERIAL LED TIMING AND COMMUNICATION SETUP

Appendix C: “Magnetic Angle Tracker DemoBoard” contains a picture of the Magnetic AngleTracker demo board described in this document.

-200

-150

-100

-50

0

50

100

150

200

40 60 80 100 120 140

Angl

e va

lue

in d

egre

es

Sample number

Angle value (deg)

PWM Period 625ns TMR2 =

PWM Freq 1.6MHz=

PWM Duty Cycle 50%=

SPI Mode 1=

SPI Clock 800kHz=The output of the CLC is connected to the DIN (DataIn) of the first LED in the series.

2017 Microchip Technology Inc. DS00002373A-page 9

Page 10: Magnetic Angle Tracker Application Using the CIP …ww1.microchip.com/downloads/en/AppNotes/00002373A.pdf(CIP) on this device such as Math Accelerator with PID, Configurable Logic

AN2373

FIGURE 11: CLC SETUP DIAGRAM USING MCC FOR THE WS2812B SERIAL LEDS

CONCLUSION

The Math Accelerator module does 16-bit addition andmultiplication in hardware. It saves the user timecompared with software calculation, as demonstratedin the case study presented in this application note.The number of instructions was reduced up to halfusing the hardware Math Accelerator module. Designof the magnetic angle tracker demo board waspresented with some code snippets to get started withthe module. Therefore, there is a huge efficiencyimprovement by using the Math Accelerator.

REFERENCES

1. TB3134, “16-Bit Multiplication and Addition byusing the Math Accelerator Peripheral onPIC16(L)F161X” (DS9003134).

2. AN1606, “Using the Configurable Logic Cell(CLC) to Interface a PIC16F1509 and WS2811LED Driver” (DS00001606).

3. AAT00x TMR Angle Sensors Data Sheetavailable on http://www.nve.com/Downloads/AAT00X.pdf.

4. TLE5009, “GMR-Based Angular SensorApplication Note Calibration”.

DS00002373A-page 10 2017 Microchip Technology Inc.

Page 11: Magnetic Angle Tracker Application Using the CIP …ww1.microchip.com/downloads/en/AppNotes/00002373A.pdf(CIP) on this device such as Math Accelerator with PID, Configurable Logic

AN2373

APPENDIX A: CODE SNIPPETS

EXAMPLE 1: MAIN() FUNCTION

EXAMPLE 2: FUNCTION TO READ THE AMPLIFIED SENSOR VOLTAGES AND PERFORM ADC CONVERSION

Software License AgreementThe software supplied herewith by Microchip Technology Incorporated (the “Company”) is intended and supplied to you, theCompany’s customer, for use solely and exclusively with products manufactured by the Company.The software is owned by the Company and/or its supplier, and is protected under applicable copyright laws. All rights are reserved.Any use in violation of the foregoing restrictions may subject the user to criminal sanctions under applicable laws, as well as to civilliability for the breach of the terms and conditions of this license.THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATU-TORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICU-LAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FORSPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.

/* Main application */void main(void) { SYSTEM_Initialize(); // initialize the application settings Init(); // Enable the Global Interrupts INTERRUPT_GlobalInterruptEnable(); // Enable the Peripheral Interrupts INTERRUPT_PeripheralInterruptEnable(); while (1) { // get the two ADC inputs from the sensor // this is the amplified signal from the opamp READ_ADC_Values(); angleRad = ATAN2_New(Y2, X2); angleDeg = angleRad * 57; Toggle_Switch(); // change the light color if SW2 button press //Once the angle is calculated , read the angle value and decide which LED to blink valueRec = Read_Angle_Value(angleDeg); //function to read the angle and assign a switch case value Light_ON(valueRec); //Light the LED string based on the angle detected }}

void READ_ADC_Values() { X = ADC_GetConversion(channel_AN3); // measure the sine and cosine sensor output voltages and store the ADC Y = ADC_GetConversion(channel_AN7); //counts in X and Y X_shift = (float) X / 1024; //convert ADC counts to voltage by multiplying factor 1024 since it is a 10 bit ADC X1 = (X_shift)*3.3 - OFF_CORR_X; //X1 and Y1 are the offset corrected voltage values Y_shift = (float) Y / 1024; //X2 and Y2 are the amplitude corrected voltage values Y1 = (Y_shift)*3.3 - OFF_CORR_Y; X2 = X1 / AMP_CORR_X; Y2 = Y1 / AMP_CORR_Y;}

/*

AMP_CORR_X is the average amplitude error correction value for the sine values (x), taking both the clockwise and the counter clockwise rotation into considerationAMP_CORR_Y is the average amplitude error correction value for the cosine values (y), taking both the clockwise and the counter clockwise rotation into considerationOFFSET_CORR_X is the average offset error in the sine values OFFSET_CORR_Y is the average offset error in the cosine values

*/

2017 Microchip Technology Inc. DS00002373A-page 11

Page 12: Magnetic Angle Tracker Application Using the CIP …ww1.microchip.com/downloads/en/AppNotes/00002373A.pdf(CIP) on this device such as Math Accelerator with PID, Configurable Logic

AN2373

EXAMPLE 3: INVERSE TANGENT COMPUTATION FUNCTION

EXAMPLE 4: FUNCTION TO EXPAND INVERSE TANGENT FOR DIFFERENT CONDITIONS

floatATAN_New(float f) { static const float coeff_a[] = { 33.0586184, 58.6557515, //polynomial coefficient constants 32.3909748, 5.85319521, 0.19523741, -.00243460 }; static const double coeff_b[] = { 33.058618, 69.675291, 49.004348, 12.975578, 1.0 }; unsigned char recip; double val, val_squared, y, x; if ((val = fabs(f)) == 0.0) return 0.0; if (recip = (val > 1.0)) val = 1.0 / val; val_squared = MATHACC_MultiplicationResultGet(val);//perform z squared multiplication using MATH Accelerator y = eval_poly(val_squared, coeff_b, 4); x = eval_poly(val_squared, coeff_a, 5); val *= x / y; if (recip) val = HALF_PI - val; return f < 0.0 ? -val : val;}

floatATAN2_New(float y, float x) {// ATAN2_New function is modified to include the ATAN_New function which uses the Math Accelerator PID module double v; if (x == 0) { if (y == 0) { //errno = EDOM; return 0; } if (y > 0) { return HALF_PI; } else { return -HALF_PI; } } if (y == 0) { if (x > 0) { return 0; } else { return PI; } } if (fabs(x) >= fabs(y)) { v = ATAN_New(y / x);//ATAN_New function which uses the Math Accelerator PID module to perform critical mathematical computation if (x < 0.0) if (y >= 0.0) v += PI; else v -= PI; return v; } v = -ATAN_New(x / y);//return v , which is the computed arctangent value in radians if (y < 0.) v -= HALF_PI; else v += HALF_PI; return v;}

DS00002373A-page 12 2017 Microchip Technology Inc.

Page 13: Magnetic Angle Tracker Application Using the CIP …ww1.microchip.com/downloads/en/AppNotes/00002373A.pdf(CIP) on this device such as Math Accelerator with PID, Configurable Logic

2

01

7 M

icroch

ip T

ech

no

log

y Inc.

DS

00

00

23

73

A-p

ag

e 1

3

AN

2373

AP

Project Title

Magnetic Angle Tracker

VDD1

RA5 2RA4 3RA3/MCLR/VPP 4

RC55 RC46 RC37

RC68

RC79 RB7 10RB6 11RB5 12RB4 13

RC214 RC115 RC016

RA2 17RA1/ICSPCLK 18RA0/ICSPDAT 19

VSS20

PIC16F1619-I/SS

U2ICSPDAT/DACOUTICSPCLK

1uFC6

GND

RC0RC1RC2

RC5RC6 RB7

AN_SIN

AN_COS

MCLRRA2

RA5

LED_DRIVE

RB4

RC4

OUT

GND

MCLRLED_DRIVE

112

34

56

78

910

HDR-2.54 Male 1x10

J1

112

34

56

78

910

HDR-2.54 Male 1x10

J2

RA2

RA5

RB4

RC4

ICSPCLK

RB7

RC0RC1RC2

RC5RC6

GND

VDD1

COS2

GND3 GND 4SIN 5VDD 6VDDCOSGND GND

SINVDD

EP7

AAT01-10EU5

ANSINEIN

GNDGND

0.1uF

C21GND

+3.3V

+3.3V

+3.3V +3.3V

+3.3V

R603

8

0R0603

R9

UART_TXUART_RX

MTR92 LFS

1

2

10kR10

470R

R12

PTS645SM43SMTR92 LFS

14

23

S210kR11

470R

R13MCLR RC4

0.1uFC7

ICSPDAT/DACOUT

UART_TXUART_RX

AN_COS

+3.3V+3.3V

GND

GND

AN_SIN

PENDIX B: SCHEMATIC DIAGRAM

123456

HDR-2.54 Male 1x6

J3

ICSP

ICSPDAT/DACICSPCLK

MCLR

ANCOSIN

GND

EXT PWR Option

VDD1

VSS3

DO 2DI4RGB

WS2812B

D2

+3.3V

LED_DRIVE

TP12VDD1

VSS3

DO 2DI4RGB

WS2812B

D3

VDD1

VSS3

DO 2DI4RGB

WS2812B

D4

VDD1

VSS3

DO 2DI4RGB

WS2812B

D5

GND

GND

GND GND GND

VDD1

VSS3

DO 2DI4RGB

WS2812B

D6

VDD1

VSS3

DO 2DI4RGB

WS2812B

D8

VDD1

VSS3

DO 2DI4RGB

WS2812B

D9

GND GND GND GND

VDD 1

VSS 3

DO2 DI 4RGB

WS2812B

D17

VDD 1

VSS 3

DO2 DI 4RGB

WS2812B

D16

VDD 1

VSS 3

DO2 DI 4RGB

WS2812B

D15

VDD 1

VSS 3

DO2 DI 4RGB

WS2812B

D14

GNDGNDGNDGNDGNDGNDGNDGND

VDD 1

VSS 3

DO2 DI 4RGB

WS2812B

D13

VDD 1

VSS 3

DO2 DI 4RGB

WS2812B

D12

VDD 1

VSS 3

DO2 DI 4RGB

WS2812B

D11

VDD 1

VSS 3

DO2 DI 4RGB

WS2812B

D10

GND GND GND GND GND GND GND GND

VDD1

VSS3

DO 2DI4RGB

WS2812B

D18

VDD1

VSS3

DO 2DI4RGB

WS2812B

D19

VDD1

VSS3

DO 2DI4RGB

WS2812B

D20

VDD1

VSS3

DO 2DI4RGB

WS2812B

D21

VDD1

VSS3

DO 2DI4RGB

WS2812B

D22

VDD1

VSS3

DO 2DI4RGB

WS2812B

D23

VDD1

VSS3

DO 2DI4RGB

WS2812B

D24

VDD1

VSS3

DO 2DI4RGB

WS2812B

D25

+3.3V

+3.3V

GND

+3.3V

1uFC3

1uFC41k

1%

R2

GRND1

ID 4

VBUS 1

GND 5

D- 2

D+ 3

0

USB2.0 MICRO-BUSB1

0.1uFC2

USB_5VUSB_5V MCP1826S/3.3V

VIN1

GND2

VOUT 3U1

VDD1

VSS3

DO 2DI4RGB

WS2812B

D7

+3.3V

00

R

0.1uFC13

0.1uFC22

0.1uFC14

0.1uFC15

0.1uFC16

0.1uFC17

0.1uFC18

0.1uFC19

0.1uFC20

GND GND GND GND GND GND GND

GND

0.1uFC23

GND

0.1uFC24

GND

0.1uFC25

GND

0.1uFC26

GND

0.1uFC27

GND

0.1uFC28

GND

0.1uFC36

GND

0.1uFC35

GND

0.1uFC33

GND

0.1uFC34

GND

0.1uFC32

GND

0.1uFC31

GND

0.1uFC30

GND

MCP2221

VDD1

GP02

GP13

RST4

UART RX5

UART TX6

GP27 GP3 8SDA 9SCL 10VUSB 11D- 12D+ 13VSS 14VDDGP0GP1RSTUART RXUART TXGP2 GP3

SDASCL

VUSBD-D+

VSS

U4

10kR4

GP0GP1

GP2 GP3

RESET

UART_TXUART_RX

SDASCL

USB to Uart and I2C

0.1uF

C9

PTS645SM43S

4

3

S1

MCP604-A2

+A3

OUTA 1VSS

11

VDD

4U3A

MCP604

+B5

-B6

OUTB 7

+B

-B

OUTB

B

B

B

B

U3B

MCP604

+C10

-C9

OUTC 8

+C

-C

OUTC

C

C

C

C

C

U3C

10k

R3

10k

R7

10k 1%

R5

30k

1%

R1

30k

1%

R6

+3.3V

GND

ANCOSIN

ANSINEIN

AN_SIN

AN_COS

DAC

DNPC1

DNPC11

TP2TP1

TP5

0.1uFC29

GND

0.1uFC37

+3.3V

ICSPDAT/DACOUT

MCP604

+D12

-D13

OUTD 14

+D

-D

OUTD

D

D

D

D

U3D

GND

+3.3V

GND

0.1uFC5

0.1uF

C8

+t500mA1210

TH1

DNPC10

TP LOOP OrangeTP7

TP LOOP OrangeTP11

TP LOOP WhiteTP8

TP LOOP WhiteTP6

TP LOOP WhiteTP9

TP LOOP OrangeTP10

DNPTP3

DNPTP4

+3.3V

0.1uFC12

Page 14: Magnetic Angle Tracker Application Using the CIP …ww1.microchip.com/downloads/en/AppNotes/00002373A.pdf(CIP) on this device such as Math Accelerator with PID, Configurable Logic

AN2373

APPENDIX C: MAGNETIC ANGLE TRACKER DEMO BOARD

DS00002373A-page 14 2017 Microchip Technology Inc.

Page 15: Magnetic Angle Tracker Application Using the CIP …ww1.microchip.com/downloads/en/AppNotes/00002373A.pdf(CIP) on this device such as Math Accelerator with PID, Configurable Logic

Note the following details of the code protection feature on Microchip devices:

• Microchip products meet the specification contained in their particular Microchip Data Sheet.

• Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the intended manner and under normal conditions.

• There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data Sheets. Most likely, the person doing so is engaged in theft of intellectual property.

• Microchip is willing to work with the customer who is concerned about the integrity of their code.

• Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not mean that we are guaranteeing the product as “unbreakable.”

Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of ourproducts. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such actsallow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.

Information contained in this publication regarding deviceapplications and the like is provided only for your convenienceand may be superseded by updates. It is your responsibility toensure that your application meets with your specifications.MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS ORIMPLIED, WRITTEN OR ORAL, STATUTORY OROTHERWISE, RELATED TO THE INFORMATION,INCLUDING BUT NOT LIMITED TO ITS CONDITION,QUALITY, PERFORMANCE, MERCHANTABILITY ORFITNESS FOR PURPOSE. Microchip disclaims all liabilityarising from this information and its use. Use of Microchipdevices in life support and/or safety applications is entirely atthe buyer’s risk, and the buyer agrees to defend, indemnify andhold harmless Microchip from any and all damages, claims,suits, or expenses resulting from such use. No licenses areconveyed, implicitly or otherwise, under any Microchipintellectual property rights unless otherwise stated.

2017 Microchip Technology Inc.

Microchip received ISO/TS-16949:2009 certification for its worldwide headquarters, design and wafer fabrication facilities in Chandler and Tempe, Arizona; Gresham, Oregon and design centers in California and India. The Company’s quality system processes and procedures are for its PIC® MCUs and dsPIC® DSCs, KEELOQ® code hopping devices, Serial EEPROMs, microperipherals, nonvolatile memory and analog products. In addition, Microchip’s quality system for the design and manufacture of development systems is ISO 9001:2000 certified.

QUALITY MANAGEMENT SYSTEM CERTIFIED BY DNV

== ISO/TS 16949 ==

Trademarks

The Microchip name and logo, the Microchip logo, AnyRate, chipKIT, chipKIT logo, dsPIC, FlashFlex, flexPWR, Heldo, JukeBlox, KeeLoq, KeeLoq logo, Kleer, LANCheck, LINK MD, MediaLB, MOST, MOST logo, MPLAB, OptoLyzer, PIC, PICSTART, PIC32 logo, RightTouch, SpyNIC, SST, SST Logo, SuperFlash and UNI/O are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.

ClockWorks, The Embedded Control Solutions Company, ETHERSYNCH, Hyper Speed Control, HyperLight Load, IntelliMOS, mTouch, Precision Edge, and QUIET-WIRE are registered trademarks of Microchip Technology Incorporated in the U.S.A.

Analog-for-the-Digital Age, Any Capacitor, AnyIn, AnyOut, BodyCom, CodeGuard, dsPICDEM, dsPICDEM.net, Dynamic Average Matching, DAM, ECAN, EtherGREEN, In-Circuit Serial Programming, ICSP, Inter-Chip Connectivity, JitterBlocker, KleerNet, KleerNet logo, MiWi, motorBench, MPASM, MPF, MPLAB Certified logo, MPLIB, MPLINK, MultiTRAK, NetDetach, Omniscient Code Generation, PICDEM, PICDEM.net, PICkit, PICtail, PureSilicon, RightTouch logo, REAL ICE, Ripple Blocker, Serial Quad I/O, SQI, SuperSwitcher, SuperSwitcher II, Total Endurance, TSHARC, USBCheck, VariSense, ViewSpan, WiperLock, Wireless DNA, and ZENA are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.

SQTP is a service mark of Microchip Technology Incorporated in the U.S.A.

Silicon Storage Technology is a registered trademark of Microchip Technology Inc. in other countries.

GestIC is a registered trademarks of Microchip Technology Germany II GmbH & Co. KG, a subsidiary of Microchip Technology Inc., in other countries.

All other trademarks mentioned herein are property of their respective companies.

© 2017, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved.

ISBN: 978-1-5224-1670-8

DS00002373A-page 15

Page 16: Magnetic Angle Tracker Application Using the CIP …ww1.microchip.com/downloads/en/AppNotes/00002373A.pdf(CIP) on this device such as Math Accelerator with PID, Configurable Logic

DS00002373A-page 16 2017 Microchip Technology Inc.

AMERICASCorporate Office2355 West Chandler Blvd.Chandler, AZ 85224-6199Tel: 480-792-7200 Fax: 480-792-7277Technical Support: http://www.microchip.com/supportWeb Address: www.microchip.com

AtlantaDuluth, GA Tel: 678-957-9614 Fax: 678-957-1455

Austin, TXTel: 512-257-3370

BostonWestborough, MA Tel: 774-760-0087 Fax: 774-760-0088

ChicagoItasca, IL Tel: 630-285-0071 Fax: 630-285-0075

DallasAddison, TX Tel: 972-818-7423 Fax: 972-818-2924

DetroitNovi, MI Tel: 248-848-4000

Houston, TX Tel: 281-894-5983

IndianapolisNoblesville, IN Tel: 317-773-8323Fax: 317-773-5453Tel: 317-536-2380

Los AngelesMission Viejo, CA Tel: 949-462-9523Fax: 949-462-9608Tel: 951-273-7800

Raleigh, NC Tel: 919-844-7510

New York, NY Tel: 631-435-6000

San Jose, CA Tel: 408-735-9110Tel: 408-436-4270

Canada - TorontoTel: 905-695-1980 Fax: 905-695-2078

ASIA/PACIFICAsia Pacific OfficeSuites 3707-14, 37th FloorTower 6, The GatewayHarbour City, Kowloon

Hong KongTel: 852-2943-5100Fax: 852-2401-3431

Australia - SydneyTel: 61-2-9868-6733Fax: 61-2-9868-6755

China - BeijingTel: 86-10-8569-7000 Fax: 86-10-8528-2104

China - ChengduTel: 86-28-8665-5511Fax: 86-28-8665-7889

China - ChongqingTel: 86-23-8980-9588Fax: 86-23-8980-9500

China - DongguanTel: 86-769-8702-9880

China - GuangzhouTel: 86-20-8755-8029

China - HangzhouTel: 86-571-8792-8115 Fax: 86-571-8792-8116

China - Hong Kong SARTel: 852-2943-5100 Fax: 852-2401-3431

China - NanjingTel: 86-25-8473-2460Fax: 86-25-8473-2470

China - QingdaoTel: 86-532-8502-7355Fax: 86-532-8502-7205

China - ShanghaiTel: 86-21-3326-8000 Fax: 86-21-3326-8021

China - ShenyangTel: 86-24-2334-2829Fax: 86-24-2334-2393

China - ShenzhenTel: 86-755-8864-2200 Fax: 86-755-8203-1760

China - WuhanTel: 86-27-5980-5300Fax: 86-27-5980-5118

China - XianTel: 86-29-8833-7252Fax: 86-29-8833-7256

ASIA/PACIFICChina - XiamenTel: 86-592-2388138 Fax: 86-592-2388130

China - ZhuhaiTel: 86-756-3210040 Fax: 86-756-3210049

India - BangaloreTel: 91-80-3090-4444 Fax: 91-80-3090-4123

India - New DelhiTel: 91-11-4160-8631Fax: 91-11-4160-8632

India - PuneTel: 91-20-3019-1500

Japan - OsakaTel: 81-6-6152-7160 Fax: 81-6-6152-9310

Japan - TokyoTel: 81-3-6880- 3770 Fax: 81-3-6880-3771

Korea - DaeguTel: 82-53-744-4301Fax: 82-53-744-4302

Korea - SeoulTel: 82-2-554-7200Fax: 82-2-558-5932 or 82-2-558-5934

Malaysia - Kuala LumpurTel: 60-3-6201-9857Fax: 60-3-6201-9859

Malaysia - PenangTel: 60-4-227-8870Fax: 60-4-227-4068

Philippines - ManilaTel: 63-2-634-9065Fax: 63-2-634-9069

SingaporeTel: 65-6334-8870Fax: 65-6334-8850

Taiwan - Hsin ChuTel: 886-3-5778-366Fax: 886-3-5770-955

Taiwan - KaohsiungTel: 886-7-213-7830

Taiwan - TaipeiTel: 886-2-2508-8600 Fax: 886-2-2508-0102

Thailand - BangkokTel: 66-2-694-1351Fax: 66-2-694-1350

EUROPEAustria - WelsTel: 43-7242-2244-39Fax: 43-7242-2244-393

Denmark - CopenhagenTel: 45-4450-2828 Fax: 45-4485-2829

Finland - EspooTel: 358-9-4520-820

France - ParisTel: 33-1-69-53-63-20 Fax: 33-1-69-30-90-79

France - Saint CloudTel: 33-1-30-60-70-00

Germany - GarchingTel: 49-8931-9700Germany - HaanTel: 49-2129-3766400

Germany - HeilbronnTel: 49-7131-67-3636

Germany - KarlsruheTel: 49-721-625370

Germany - MunichTel: 49-89-627-144-0 Fax: 49-89-627-144-44

Germany - RosenheimTel: 49-8031-354-560

Israel - Ra’anana Tel: 972-9-744-7705

Italy - Milan Tel: 39-0331-742611 Fax: 39-0331-466781

Italy - PadovaTel: 39-049-7625286

Netherlands - DrunenTel: 31-416-690399 Fax: 31-416-690340

Norway - TrondheimTel: 47-7289-7561

Poland - WarsawTel: 48-22-3325737

Romania - BucharestTel: 40-21-407-87-50

Spain - MadridTel: 34-91-708-08-90Fax: 34-91-708-08-91

Sweden - GothenbergTel: 46-31-704-60-40

Sweden - StockholmTel: 46-8-5090-4654

UK - WokinghamTel: 44-118-921-5800Fax: 44-118-921-5820

Worldwide Sales and Service

11/07/16