15
Programming on a Chipkit Max32, a little review Maxime Vinzio November 2014 Contents 1 About the platform 2 2 Core Functions 3 2 .1 Basic includes ................................... 3 2 .2 A task manager .................................. 3 3 Sainsmart Screen and Shield 4 3 .1 LCD and Touchscreen .............................. 4 3 .2 SD Slot ...................................... 5 3 .3 Shield ....................................... 6 3 .4 Network Connection ............................... 6 4 Modification of UTFT Library 6 4 .0.1 Pinout ................................... 7 4 .0.2 Memory usage ............................... 7 4 .0.3 Compatibility ............................... 7 4 .1 Utouch Calibration ................................ 7 5 Hardware 8 5 .1 Analog Write ................................... 8 5 .2 External Interrupts ................................ 10 5 .3 Internal Interrupts ................................ 11 6 Code exportation 14 7 Conclusion 14 1

Programming on a Chipkit Max32, a little reviewz3bu.free.fr/articles/Chipkit_max_32.pdfDiscoveringtheChipkitMax32 Section3 E AnEnablepinthatenableswritingtotheregisters,herealwaysathighlevel,

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Programming on a Chipkit Max32, a little reviewz3bu.free.fr/articles/Chipkit_max_32.pdfDiscoveringtheChipkitMax32 Section3 E AnEnablepinthatenableswritingtotheregisters,herealwaysathighlevel,

Programming on a Chipkit Max32, alittle review

Maxime Vinzio

November 2014

Contents1 About the platform 2

2 Core Functions 32 .1 Basic includes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 .2 A task manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

3 Sainsmart Screen and Shield 43 .1 LCD and Touchscreen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 .2 SD Slot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 .3 Shield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 .4 Network Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

4 Modification of UTFT Library 64 .0.1 Pinout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 .0.2 Memory usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 .0.3 Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

4 .1 Utouch Calibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

5 Hardware 85 .1 Analog Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 .2 External Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 .3 Internal Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

6 Code exportation 14

7 Conclusion 14

1

Page 2: Programming on a Chipkit Max32, a little reviewz3bu.free.fr/articles/Chipkit_max_32.pdfDiscoveringtheChipkitMax32 Section3 E AnEnablepinthatenableswritingtotheregisters,herealwaysathighlevel,

Discovering the Chipkit Max 32 Section 2

This document is a feedback of the use of the ChipKit Max32 prototyping board usedwith a saintsmart screen. It presents the platform principles and modifications done in orderto help anyone willing to develop with it. The lack of documentation asks to be a bit sneakyand study the code adapted from the Arduino community. Special ChipKit functionalitiesare well documented, and in case of doubt the PIC32 documentations of Microchip seemcomplete and are useful1. Please see the condensed presentation of the Chipkit MAX32board[2].

1 About the platformThe software has been developed with an external editor from MPIDE. MPIDE is themodified Arduino IDE by Digilent for the ChipKit products. The interface and functional-ities are basics, compilation macros are hidden and unmodifiable. The version I used to wasmpide-0023-linux64-20140316. It was sometimes a bit buggy, but usually an unexplainedbug can be solved by unplugging the ChipKit board and relaunching the software. A smarterchoice would be to use MPLABX, developed for the PIC32 micro-controllers types or createa makefile for the project. Nevertheless, MPIDE is a turnkey software, for other solutionssome manipulations have to be done to use the compiler and the exportation of the projectto another platform risk to be more difficult.

Arduino prototyping systems "like" use the combination of C and C++. C++ is cho-sen as programming language, object oriented languages allowing an easy interfacing for"object" control.

Arduino functions are present in the basic functions. ChipKit also respects the design ofArduino’s systems and allows to use Arduino’s shields. Nevertheless, the operating voltagebeing different (3.3 V for ChipKit instead of 5 V for Arduino), in most of cases Arduino’sshields have to be modified. Here the ChipKit MAX32 –having a "similar" pinout– borrowin some configuration files the name of the Arduino Mega board.

Finally, lot’s of code have been adapted from the Arduino project. But it is really sadto see most of basic functions provided as soft solutions instead of using the hard-designedfunctionalities. For example the PWM signal demonstration is done by software. Besidethe instructive function, this kind of design is resource’s consuming, can not be implementedif other operations must be operated and is always frustrating.

Nevertheless, the PIC32 documentation allows to write low-level functions that will bepresented here (find the reference manuals of the pic32 family with the keyword "pic32"[url]).

The MPIDE software can be downloaded here2. On Linux it is easily installable byextracting it in the /aux/ directory. Nevertheless some of the libraries used by this soft-ware (based on java) are not all functioning out-of-the-box or need administrator rights.Especially for the serial management library. It allows the transfer of the compiled binaryand equally the communication with the prototyping platform. To fix this a manipulationis to create a symbolic link from the system serial library (/usr/lib/librxtxSerial.so) to thesoftware lib directory.

1http://www.microchip.com/TechDoc.aspx?type=ReferenceManuals2http://chipkit.net/started/install-chipkit-software/install-mpide-linux/

Page 2 of 15

Page 3: Programming on a Chipkit Max32, a little reviewz3bu.free.fr/articles/Chipkit_max_32.pdfDiscoveringtheChipkitMax32 Section3 E AnEnablepinthatenableswritingtotheregisters,herealwaysathighlevel,

Discovering the Chipkit Max 32 Section 2

2 Core FunctionsA reference of basic functions can be found on Arduino’s website3. For example, it is notrecommended to have a recursive use of the min/max functions, indeed having a look in thewiring.h definition file, we can see that theses functions are defined by macros.

2 .1 Basic includes

In every program are automatically included these standard libraries:

#inc lude <s t d l i b . h>#inc lude <s t r i n g . h>#inc lude <math . h>#inc lude " wi r ing . h"#inc lude "WProgram . h"

#i f d e f __cplusplus#inc lude "HardwareSer ia l . h"#end i f

"Wiring.h" contains mathematical constants, main.cpp and Arduino functions prototypeand macros as min(), max(). . . "WProgram.h" contains registers pointers e.g. T2CONSET: configuration register for the TIMER2.

To facilitate the definitions, or use pic32 specific functions (for example, UARTConfig-ure(uartX, UART_ENABLE_PINS_TX_RX_ONLY);) the library <plib.h> is proposed.This library is mentioned here because it should be avoid, for strange reasons ChipKitredefined the type word. This can conduct to overwriting definitions and failures4.

Some of the definitions findable in this library have been written in the p32_defs.h forclassic hardware use (e.g. for the output compare) (see /pathtompide/hardware/pic32/cores/pic32/p32_defs.h).

2 .2 A task manager

The task manager allows the creation and operation of background tasks. A task is a userdefined function that is executed automatically at specified intervals or at a specified time.Using tasks can simplify the logic of programs that need to perform periodic operations.

The scheduling times for task functions is based on the system millisecond tick counter(the core timer). This is the value returned by the millis() function. This tick counter runscontinuously and gives the number of milliseconds elapsed since the system started running.

Scheduling of tasks for execution is done prior to each execution of the user functionloop(). In order to task scheduling works reliably, the time to execute the user loop() functionshould be short; preferably less than a millisecond, but no more than a few milliseconds ifthe timing accuracy of task scheduling needs to be precise.

Example of functions :createTask ( )destroyTask ( )

3http://arduino.cc/en/Reference/HomePage4http://ChipKit.net/forum/viewtopic.php?f=7&t=2790&sid=05b48c8be96c6af12711a1c7bf650702&start=10

Page 3 of 15

Page 4: Programming on a Chipkit Max32, a little reviewz3bu.free.fr/articles/Chipkit_max_32.pdfDiscoveringtheChipkitMax32 Section3 E AnEnablepinthatenableswritingtotheregisters,herealwaysathighlevel,

Discovering the Chipkit Max 32 Section 3

i n t main ( void ){

i n i t ( ) ;setup ( ) ;whi l e (1 ){

_scheduleTask ( ) ;loop ( ) ;

}re turn 0 ;

}

Figure 1: main.cpp

getTaskId ( )startTaskAt ( )getTaskNextExec ( )setTaskState ( )setTaskPer iod ( )

If a task is too long, the task management may be broken, this can be avoided bydisabling every task at the start of one and re-enabling them afterwards. For example, theUTFT button library (presented further) has a multi-thread incompatible design, if a buttonstays pressed, the whole system stays in a reading loop and waits for the user to release thetouch-screen, the functioning of this library has to be modified to fit to a periodic operating(a periodic interrupt function based on a timer can do it).

This system should not be used for a precise period sampling, we will prefer timerinterrupts control for data sensoring.

3 Sainsmart Screen and ShieldSince the MCU is working in 3.3 V, the designed shield for the 5 V Arduino Mega has tobe modified.

3 .1 LCD and Touchscreen

The screen is a 3.2 inches TFT LCD SainSmart 320x240 RGB based on the SSD1289, Inte-grated Power device, 262k color, Gate and Source Driver With RAM. The touch-screen is aresistive technology and a controller convert the analog signal (ADS7843). Standing alonethey work in 3.3 V. The pinout is shown on figure 2.

The screen is controllable with the pins:

Page 4 of 15

Page 5: Programming on a Chipkit Max32, a little reviewz3bu.free.fr/articles/Chipkit_max_32.pdfDiscoveringtheChipkitMax32 Section3 E AnEnablepinthatenableswritingtotheregisters,herealwaysathighlevel,

Discovering the Chipkit Max 32 Section 3

E An Enable pin that enables writing to the registers, here always at high level,directly wired on the shield.

CS The ChipSelect PinRS A register select pin that controls where in the LCD’s memory you’re writing

data to. You can select either the data register, which holds what goes on thescreen, or an instruction register, which is where the LCD’s controller looksfor instructions on what to do next.

WR that selects reading mode or writing modeRST Reset Pin.DB0-15 16 bits data bus, bidirectional to read or to write.

The touch-screen is controllable with the pins:

DOUT Serial Data Output. Data is shifted on the falling edge of DCLK. This outputis high impedance when CS is HIGH.

BUSY Busy Output. This output is high impedance when CS is HIGH. Not compul-sory.

DIN Serial Data Input. If CS is LOW, data is latched on rising edge of DCLK.CS Chip Select Input. Controls conversion timing and enables the serial input/out-

put register.DCLK External Clock Input. This clock runs the SAR conversion process and syn-

chronizes serial data I/O.

Figure 2: Sainsmart TFT LCD Pin Out

This device is working with the UTFT Library (see section 4 ) and should work as wellwith the library TFT from Chipkit (it uses directly the PMP functionality but the writingof a touchscreen driver may be necessary)5.

3 .2 SD Slot

The Sainsmart screen comes with a SD slot usable as extended memory pluggable to the5 V Arduino. The shield is known as having an incorrect routing for the SD card, afterverification it’s not the case. A SD card can be directly connected to the 3.3 V of the system.

5hrefhttps://github.com/majenkotech/TFThttps://github.com/majenkotech/TFT

Page 5 of 15

Page 6: Programming on a Chipkit Max32, a little reviewz3bu.free.fr/articles/Chipkit_max_32.pdfDiscoveringtheChipkitMax32 Section3 E AnEnablepinthatenableswritingtotheregisters,herealwaysathighlevel,

Discovering the Chipkit Max 32 Section 4

Figure 3: SD connection to Arduino

The resistances on the Sainsmart device have to be removed (3). Note that no voltagedivider is installed on the MISO signal wire, simply being already a 3.3 V signal recognizableby the usual 5 V Arduino threshold.

The SD card works fine with the SD library. The SD library being a wrapper of theSDfat, it creates a class variable SD that we have to use over the "hidden" SDfat parameters.It allows to open only one file at the time.

3 .3 Shield

The shield has been first modified by removing the voltage dividers. Furthermore the routinghas to be changed, indeed some ports configurable as output can not work as it. The USB-on-the-go functions used pins that can only be used as digital inputs when USB is notenabled even if the writing register of these ports exist. See page 174 in the summariseddatasheet[6]. Furthermore some other hardware functionalities as the Output Compare (seefurther) or external interrupts can be reserved for other operations, and the pins usable arelimited.

The variable resistor on the shield seems to engender problems (current too high ?) ifbadly positioned. Try to set it if the screen does not work.

3 .4 Network Connection

Not implemented but pins reserved for a further development.

4 Modification of UTFT LibraryThe Universal TFT library is designed for Arduino and chipKit. It aggregates the commondrivers for Arduino’s like devices. Nevertheless, it is gluttonous in memory. Thus the codehas been adapted and optimized. This free software is downloadable here 6.

6http://www.henningkarlsen.com/electronics/library.php?id=51

Page 6 of 15

Page 7: Programming on a Chipkit Max32, a little reviewz3bu.free.fr/articles/Chipkit_max_32.pdfDiscoveringtheChipkitMax32 Section3 E AnEnablepinthatenableswritingtotheregisters,herealwaysathighlevel,

Discovering the Chipkit Max 32 Section 5

4 .0.1 Pinout

Only theRS,CS,WR andRES (and SER for serials screens) are dynamically configurable.The UTFT library defines its pinout depending on the board used for example for theChipkit Max32 the definition files is in hardware/pic32/HW_PIC32MX795F512L.h. Indeedto get a faster usage of the inputs/outputs the set/reset registers are used hence a as fast aspossible operation of the LCD module. See the code 4 showing the principle of masking.

It would have been possible to do it dynamically using the Parallel Master Port hardwarefunctionality of the Chipkit. It is a parallel 8-bit/16-bit input/output module specificallydesigned to communicate with a wide variety of parallel devices, such as communicationsperipherals, LCDs, external memory devices and microcontrollers.

//PORT B con f i gu r a t i on as outputTRISB&=~0x0700 ;// Clear and wr i t i ngLATBCLR = 0x0700 ;LATBSET = (BYTE<<5 & 0x0700 ) ;

Figure 4: Example given here the 5th to the 3rd bit of the BYTE are written on outputs 10to 8 of the Chipkit port B

4 .0.2 Memory usage

By default the library compiles all the drivers existing in the project. Thus the binary outputcontains useless bits of code, the project needing only one specific driver. By disabling theunused drivers in the file memorysaver.h file, a dozen of kB are saved.

Unused fonts can be equally commented in the file "DefaultFonts.c" of the UTFT libraryand in the file "fonts.c" of the button library. As weel the code can be commented in somefunctions for the serial screens handling.

4 .0.3 Compatibility

A tricky modification has to be done too, in order too allow the use of vec-tors of the STL in c++. The developer defined its own macro "swap" in thefile: "hardware/pic32/HW_PIC32_defines.h" and the "setxy.h" files contained in the"tft_drivers/ssd1963/{480,800,800alt}/setxy.h" directories for the UTFT library. It hasbeen renamed to allow the good definition of the one used in the <vector> library. TheUTouch library has to be patched equally, the code macro is present even if unused.

4 .1 Utouch Calibration

A calibration tool can be used, after loading the compiled sketch UTouch/examples/chip-Kit/UTouch_Calibration/UTouch_Calibration.pde and using a stylus, three calibrationvalues are generated and have to be declared as macro in the UtouchCd.h file.

Page 7 of 15

Page 8: Programming on a Chipkit Max32, a little reviewz3bu.free.fr/articles/Chipkit_max_32.pdfDiscoveringtheChipkitMax32 Section3 E AnEnablepinthatenableswritingtotheregisters,herealwaysathighlevel,

Discovering the Chipkit Max 32 Section 5

5 HardwareThe output/input pins have a working voltage range for analog input fromn 0 V to 3.3 Vand can provide ±18 mA DC Current per pin. These characteristics have to be kept inmind while designing sensors and control devices.

5 .1 Analog Write

The analog outputs are based on Pulse-Width Modulation. Only pin 3, 5, 6, 9 and 10 canproduce an purely hardware PWM. In case of more PWM outputs needed, a countingfunction based on a timer can help doing it.

The function analogWrite() already implemented has for argument the duty cycle com-prised between 0 to 255. For a 30 V generator voltage control for example, this gives atheoretical precision of 117 mV, beyond the aim of the project is to have a 10 mV precision.Furthermore, the frequency of the PWM signal is approximately 490 Hz. You do not needto call pinMode() to set the pin as an output before calling analogWrite().

This function is based on the timer 2 and the output compare modules, it is possibleto change the hardware configurations to aptly control PWM devices. We can reconfigurethe timer 2 (timer 3 can be used as well), anyway, for a better precision should not be usedthe original analogWrite() function.

The Output Compare module is used to generate a single pulse or series of pulses inresponse to selected time base events. For all modes of operation, the Output Comparemodule compares the values stored in the OCxR and/or the OCxRS registers to the valuein the selected timer. When a match occurs, the Output Compare module generates anevent based on the selected mode of operation.

The Output Compare sets the pin when the timer resets. The timer then counts up from0. The Output Compare resets the pin when the the value in the timer matches the valuein the output compare register. The counter continues to count up until the count valuematches the value in the period register. The timer then resets and it all starts over again (seefigure 5). Also at the end of a period the contents of the duty cycle buffer register(OCxRS)is loaded into the duty cycle register(OCxR). The frequency of the resulting PWM signal isdetermined by the clock speed of the timer, and the value in the period register (figure 6).

The parameters can be determined with the following equations :

PWMPeriod = (Period+ 1)× TPB × (TIMERPrescaleV alue) (1)

With:

Period the timer counter periodTPB the peripheral bus period

PWM Resolution (bits) = log(2)

(FPB

FPWM × TIMERPrescaler

)(2)

So if we want a precision of 10 mV, the PWM must have a definition of 3000 values,if we set a pre-scaler of 8 for the timer, giving it a output signal frequency of 10 MHz wecalculate with 2 a PWM frequency of 3333 Hz. We determine the timer period with 1:2999 clock period.

Page 8 of 15

Page 9: Programming on a Chipkit Max32, a little reviewz3bu.free.fr/articles/Chipkit_max_32.pdfDiscoveringtheChipkitMax32 Section3 E AnEnablepinthatenableswritingtotheregisters,herealwaysathighlevel,

Discovering the Chipkit Max 32 Section 5

[!htp]

OCxR(1)

Comparator

OutputLogic

QSR

OCM<2:0>

Output Enable

OCx(1)

Set Flag bitOCxIF(1)

OCxRS(1)

Mode Select

3

Note 1: Where ‘x’ is shown, reference is made to the registers associated with the respective output compare channels,1 through 5.

2: The OCFA pin controls the OC1-OC4 channels. The OCFB pin controls the OC5 channel.3: Each output compare channel can use one of two selectable 16-bit time bases or a single 32-bit timer base.

0 1 OCTSEL 0 1

1616

OCFA or OCFB(2)

TMR Register Inputsfrom Time Bases(3)

Period Match Signalsfrom Time Bases(3)

LogicOutputEnable

Figure 5: Output Compare

[!htp]

Period = (PRy + 1)

Duty Cycle = (OCxRS)

Timery is cleared and the new duty cycle value is loaded from OCxRS into OCxR.

Timer value equals the value in the OCxR register; OCx Pin is driven low.

Timer overflow; value from OCxRS is loaded into OCxR; OCx pin is driven high.

21 3

2

3

1

TyIF interrupt flag is asserted.

Figure 6: PWM Output

Page 9 of 15

Page 10: Programming on a Chipkit Max32, a little reviewz3bu.free.fr/articles/Chipkit_max_32.pdfDiscoveringtheChipkitMax32 Section3 E AnEnablepinthatenableswritingtotheregisters,herealwaysathighlevel,

Discovering the Chipkit Max 32 Section 5

Thus, we can increase the resolution, the PWM frequency will be smaller (for consump-tion consideration). We can consider a 1kHz PWM signal, common in electronics. Thenwith the 1:8 prescaler the resolution will be 10000 (theorically), hence setting the timer toa 1:16 prescaler, with a 4999 clock edges period and a resolution of 5000 values.

// con f i gu r e t imer 2

T2CONCLR = T2_ON // Turn the t imer o f fT2CON = T2_PS_1_16 ; // Set p r e s c a l e rTMR2 = 0 ; // Clear the counterPR2 = 4999 ; // Set the per iodT2CONSET = T2_ON; // Turn the t imer on

// con f i gu r e output compare 1

OC1R = 2499 ; // Load i n i t i a l va lue in to duty cy c l e r e g i s t e rOC1RS = duty_cycle ∗4999 ; // When a per iod f i n i s h e s the content s

o f OC1RS i s loaded to OC1ROC1CON = OC_TIMER2_SRC | OC_PWM_FAULT_PIN_DISABLE; // Set Timer2 as source |

enable pwm mode without f a u l t p r o t e c t i onOC1CONSET = OC_ON;

For more complete details, you should refer to the Timer [5] and Output Compare [4]sections of the PIC32 Family Reference Manual that can be downloaded from the Microchipweb site.

5 .2 External Interrupts

A system to be secured can not only rely on the microcontroller. Imagine a fault occurringwhile the system is in an heavy calculation phase or simply unresponsive because of abug/electricity shortage. That is why some security functions has to be doubled by hardwarereading the output of sensors. The system has to know about these faults and must reactquickly to reset and adopt the best procedure.

This priority management can be managed by external interrupts with the Change No-tification facilities of the PIC32 chip. The chipkit library keeps the familiar Arduino attach-Interrupt() interface, and applies it to the change notification pins.

Example here:void a t ta ch In t e r rup t ( uint8_t , void (∗ ) ( void ) , i n t mode) ;void detach Inte r rupt ( uint8_t ) ;

CN_x is the change notification pin number in the form CN_0 thru CN_21. Functionis the function to call when the interrupt is triggered, mode is one of RISING, FALLINGor CHANGE.

detachInterrupt(CN_x); will remove ALL interrupts from a pin.attachInterrupt(CN_x,function,direction) will add the interrupt to that specific direc-

tion. You can add a function to multiple directions:a t ta ch In t e r rup t (CN\_4, pressed , RISING) ;a t t a ch In t e r rup t (CN\_4, r e l e a s ed ,FALLING) ;

Page 10 of 15

Page 11: Programming on a Chipkit Max32, a little reviewz3bu.free.fr/articles/Chipkit_max_32.pdfDiscoveringtheChipkitMax32 Section3 E AnEnablepinthatenableswritingtotheregisters,herealwaysathighlevel,

Discovering the Chipkit Max 32 Section 5

5 .3 Internal Interrupts

First of all, the interrupts must be initialized on the device, for this the best is to referon the device section on the pic32 reference manual, example of code are present and wellexplained (see to the interrupts presentation [3]). Thus, here is an example for timer 2 onfigure 7.

T2CON = 0x0 ; // Stop t imer and c l e a r c on t r o l r e g i s t e r ,// p r e s c a l e r at 1 : 1 , i n t e r n a l c l o ck sourceTMR2 = 0x0 ; // Clear t imer r e g i s t e rPR2 = 0xFFFF; // Load per iod r e g i s t e r

IPC2SET = 0x0000000C ; // Set p r i o r i t y l e v e l = 3IPC2SET = 0x00000001 ; // Set sub−p r i o r i t y l e v e l = 1// Could have a l s o done t h i s in s i n g l e operat i on by a s s i gn i ng// IPC2SET = 0x0000000DIFS0CLR = 0x00000100 ; // Clear t imer i n t e r r up t s t a tu s f l a gIEC0SET = 0x00000100 ; // Enable t imer i n t e r r up t sT2CONSET = 0x8000 ; // Star t t imer

Figure 7: Example of timer 2 interrupt initialisation

The function launched by the vector table after the interrupt can be defined in multipleway. No common interface with the Arduino exists it is really hardware specific. The clas-sical pic32 way is to use the __ISR macro putting an interrupts attribute on the function.The ISR functions must be placed in a C namespace.

extern "C"{

void __ISR(_TIMER_2_VECTOR, i p l 3 ) myISRfunction ( void ){

//Do s t u f f .// . . .IFS0CLR = 0x00000010 ; // Clear i n t e r r up t f l ag , must be at the

end}

}

Figure 8: PIC32 classical interrupts function definition

The __ISR macro needs at least one information the vector emplacement of the inter-rupt, and the IPL, the Interrupt Priority Level. It is not really needed, it will work correctlywithout, but will be slightly slower and larger. Without the IPL parameter, the current IPLwill be read from the Cause register instead of being hardcoded.

See annexe 1 to get the nest vector table of interrupt or see page 132 of the summarizeddatasheet [6].

0 _CORE_TIMER_VECTOR

Page 11 of 15

Page 12: Programming on a Chipkit Max32, a little reviewz3bu.free.fr/articles/Chipkit_max_32.pdfDiscoveringtheChipkitMax32 Section3 E AnEnablepinthatenableswritingtotheregisters,herealwaysathighlevel,

Discovering the Chipkit Max 32 Section 5

1 _CORE_SOFTWARE_0_VECTOR2 _CORE_SOFTWARE_1_VECTOR3 _EXTERNAL_0_VECTOR4 _TIMER_1_VECTOR5 _INPUT_CAPTURE_1_VECTOR6 _OUTPUT_COMPARE_1_VECTOR7 _EXTERNAL_1_VECTOR8 _TIMER_2_VECTOR9 _INPUT_CAPTURE_2_VECTOR10 _OUTPUT_COMPARE_2_VECTOR11 _EXTERNAL_2_VECTOR12 _TIMER_3_VECTOR13 _INPUT_CAPTURE_3_VECTOR14 _OUTPUT_COMPARE_3_VECTOR15 _EXTERNAL_3_VECTOR16 _TIMER_4_VECTOR17 _INPUT_CAPTURE_4_VECTOR18 _OUTPUT_COMPARE_4_VECTOR19 _EXTERNAL_4_VECTOR20 _TIMER_5_VECTOR21 _INPUT_CAPTURE_5_VECTOR22 _OUTPUT_COMPARE_5_VECTOR23 _SPI_1_VECTOR24 _I2C_3_VECTOR _UART_1A_VECTOR _UART_1_VECTOR

_SPI_1A_VECTOR _I2C_1A_VECTOR _SPI_3_VECTOR25 _I2C_1_VECTOR26 _CHANGE_NOTICE_VECTOR27 _ADC_VECTOR28 _PMP_VECTOR29 _COMPARATOR_1_VECTOR30 _COMPARATOR_2_VECTOR31 _UART_2A_VECTOR _I2C_2A_VECTOR _SPI_2_VECTOR

_SPI_2A_VECTOR _I2C_4_VECTOR _UART_3_VECTOR32 _UART_2_VECTOR _SPI_3A_VECTOR _I2C_3A_VECTOR

_UART_3A_VECTOR _SPI_4_VECTOR _I2C_5_VECTOR33 _I2C_2_VECTOR34 _FAIL_SAFE_MONITOR_VECTOR35 _RTCC_VECTOR36 _DMA_0_VECTOR37 _DMA_1_VECTOR38 _DMA_2_VECTOR39 _DMA_3_VECTOR40 _DMA_4_VECTOR41 _DMA_5_VECTOR

Page 12 of 15

Page 13: Programming on a Chipkit Max32, a little reviewz3bu.free.fr/articles/Chipkit_max_32.pdfDiscoveringtheChipkitMax32 Section3 E AnEnablepinthatenableswritingtotheregisters,herealwaysathighlevel,

Discovering the Chipkit Max 32 Section 6

42 _DMA_6_VECTOR43 _DMA_7_VECTOR44 _FCE_VECTOR45 _USB_1_VECTOR46 _CAN_1_VECTOR47 _CAN_2_VECTOR48 _ETH_VECTOR49 _UART_4_VECTOR _UART_1B_VECTOR50 _UART_6_VECTOR _UART_2B_VECTOR51 _UART_5_VECTOR _UART_3B_VECTOR

Table 1: Chipkit vector table

High level functions are accessible by the peripheral library functions <plib.h> to con-figure the interrupts. Lot’s of examples are findable on forums. They are usually misused,they confuse the internal interrupt table system. This library will stay unused.

Finally, functions defined for the Chipkit platform are usable for the interrupts settingand management. A research in the wiring.h show their defines, their functions are prettyobvious, nevertheless their code is in WSystem.c in the chipKIT core7.

uint32_t ge t In tF lag ( i n t i r q ) ;void c l e a r I n tF l a g ( i n t i r q ) ;uint32_t se t IntEnab le ( i n t i r q ) ;uint32_t c l ea r In tEnab l e ( i n t i r q ) ;void r e s t o r e In tEnab l e ( i n t i rq , uint32_t s t ) ;void s e t I n tP r i o r i t y ( i n t vec , i n t i p l , i n t sp l ) ;void g e t I n tP r i o r i t y ( i n t vec , i n t ∗ pip l , i n t ∗ psp l ) ;i s rFunc s e t In tVec to r ( i n t vec , i s rFunc func ) ;i s rFunc get IntVector ( i n t vec ) ;i s rFunc c l e a r In tVec t o r ( i n t vec ) ;

Are equally defined global control functions.

uint32_t __attribute__ ( ( nomips16 ) ) enab l e In t e r rup t s ( void ) ;uint32_t __attribute__ ( ( nomips16 ) ) d i s a b l e I n t e r r up t s ( void ) ;void __attribute__ ( ( nomips16 ) ) r e s t o r e I n t e r r u p t s ( uint32_t s t ) ;

No need to enable multi-vector interrupts. All that is already taken care of. The ISRfunction must be attached (as a normal function) with setIntVector(), the priority settedwith setIntPriority(), and the function enabled with setIntEnable(). Then in the interruptfunction can be checked getIntFlag() to test the IF flag, and then be called clearIntFlag()to clear it.

Using that way, no need to place any ISR functions in a C namespace, no need to flagthem as interrupts (see figure 9). They are just normal run-of-the-mill functions.

The last way presented to defined interrupts will be privileged while writing code.7mpide/hardware/pic32/cores/pic32/

Page 13 of 15

Page 14: Programming on a Chipkit Max32, a little reviewz3bu.free.fr/articles/Chipkit_max_32.pdfDiscoveringtheChipkitMax32 Section3 E AnEnablepinthatenableswritingtotheregisters,herealwaysathighlevel,

Discovering the Chipkit Max 32 Section 7

void myISRFunction ( void ){

i n t f l a g=get IntF lag ( ve c in t ) ;// r ou t i n e s in func t i on o f f l a gc l e a r I n tF l a g ( ve c in t ) ;

} ;

Figure 9: ISR function definition

6 Code exportationThe code has been written to minimise the adaptation if the platform has to be changedeven if the hardware implementations deeply depend on the platform. First the code has tobe separated in hardware and purely software functions to facilitate the exportation.

Basic rules are to use standard c/c++ libraries. And especially for embedded platformuse the <stdint.h>. It is a header file in the C standard library allowing programmers towrite more portable code by providing a set of type definitions that specify exact-width inte-ger types, together with the defined minimum and maximum allowable values for each type,using macros. This header is particularly useful for embedded programming which ofteninvolves considerable manipulation of hardware specific I/O registers requiring integer dataof fixed widths[1]. For example, we can consider the type word, that has been customisedby microchip for the PIC32, making it unusable for some applications. Hence if only a 8bit word is needed, int8_t from the stdint.h library will be used. Types have for namingconvention intN_t or uintN_t with N the size of the binary word.

Since Chipkit has its own file to define its wiring: the library WProgram.h which isequivalent to Arduino.h for the classic Atmel AVR and ARM boards the include must bechanged depending on the platform. The #ifdef compiler flag is encouraged to be usedallowing to activate or deactivate whole parts of specific code (see code example 10).

#i f de f ined (__AVR__)#inc lude "Arduino . h"

#e l i f d e f i ned (__PIC32MX__)#inc lude "WProgram . h"

#e l i f d e f i ned (__arm__)#inc lude "Arduino . h"

#end i f

Figure 10: Example of the compiler flag # if defined()

7 ConclusionThe documentation is somehow hard to find for the higher level functions of the Chipkit,the previous wiki disappeared, and the presentations and tutorial on the Chipkit websiteare incomplete hence a deep work of code analyse and forum research had to be done. The

Page 14 of 15

Page 15: Programming on a Chipkit Max32, a little reviewz3bu.free.fr/articles/Chipkit_max_32.pdfDiscoveringtheChipkitMax32 Section3 E AnEnablepinthatenableswritingtotheregisters,herealwaysathighlevel,

Discovering the Chipkit Max 32 References

double nature of the Chipkit is sometime confusing; for example, we can list four ways(PIC32 reference/chipkit/assembly/plib.h) to implement interrupts. This chapter shoulddo a sufficient review to develop the needed hardware functions.

The UTFT buttons library needs to be modified too in to a faster function usable as aninterrupt.

Finally, if the code has to be exported, all the hardware control has to be rewritten. Wecan skip the use of the disguised task manager, if a task is longer than expected, the othertasks fail and the main loop can not be executed. A dangerous behaviour that confine usto use the interrupts function of the software. A state machine will be developed for thesystem management.

An other disappointment is about the into directory splitting of the project, the compilerdoes not seem to handle it, further tests have to be conducted.

References[1] Wikibook’s community. C programming/c reference/stdint.h. Wikibook, 2012. [URL].

[2] Microchip. ChipKIT Max32 Board Reference Manual. Microchip, 2011. [PDF].

[3] Microchip. Microchip PIC32 Manual Interrupts. Microchip, 2011. [PDF].

[4] Microchip. Microchip PIC32 Manual Output Compare. Microchip, 2011. [PDF].

[5] Microchip. Microchip PIC32 Manual Timer. Microchip, 2011. [PDF].

[6] Microchp. PIC32MX5XX/6XX/7XX Summerized Datasheet. Microchip, 2013. [PDF].

Page 15 of 15