Home

mikroPascal PRO for PIC32 User Manual

image

Contents

1. SPI T6963C line 0 0 239 127 SPI T6963C WHITE SPI T6963C line 0 127 239 0 SPI T6963C WHITE SENDIF Draw circles SIFDEF LINE DEMO SPI T6963C circle 120 64 10 SPI T6963C WHITE SPI T6963C circle 120 64 30 SPI T6963C WHITE SPI T6963C circle 120 64 50 SPI T6963C WHITE SPI T6963C circle 120 64 70 SPI T6963C WHITE SPI T6963C circle 120 64 90 SPI T6963C WHITE SPI T6963C circle 120 64 110 SPI T6963C WHITE SPI T6963C circle 120 64 130 SPI T6963C WHITE SENDIF p Draw filled circles FJ SIFDEF FILL DEMO SPI T6963C circle fill 120 64 60 SPI T6963C WHIT SPI T6963C circle fill 120 64 55 SPI T6963C BLAC SPI T6963C circle fill 120 64 50 SPI T6963C WHIT SPI T6963C circle fill 120 64 45 SPI T6963C BLAC SPI T6963C circle fill 120 64 40 SPI T6963C WHIT SPI T6963C circle fill 120 64 35 SPI T6963C BLAC SPI T6963C circle fill 120 64 30 SPI T6963C WHIT SPI T6963C circle fill 120 64 25 SPI T6963C BLAC SPI T6963C circle fill 120 64 20 SPI T6963C WHIT SPI T6963C circle fill 120 64 15 SPI T6963C BLAC SPI T6963C circle fill 120 64 10 SPI T6963C WHIT SPI T6963C circle fill 120 64 5 SPI T6963C BLACK SENDIF Delay ms 1000 SPI T6963C sprite 76 4 einstein bmp 88 119 Delay ms 1000 SPI T6963C setGrPanel 1 117 107 97 87 Thy i2 12 12 12 12 SPI T6963C WHITE SPI T6963C BLAC SPI T6963
2. Main procedure begin Delay ms 1000 Init Main ri y4 while TRUE begin Read Time Transform Time Display Time end end do Perform initialization Endless loop Read time from RTC PCF8583 Format date and time Prepare and display on LCD MikroElektronika 382 mikroPascal PRO for PIC32 Software SPI Library The mikroPascal PRO for PIC32 provides routines for implementing Software SPI communication These routines are hardware independent and can be used with any MCU The Software SPI Library provides easy communication with other devices via SPI A D converters D A converters MAX7219 LTC1290 etc Library configuration SPI to Master mode Clock value 20 kHz Data sampled at the middle of interval Clock idle state low Data sampled at the middle of interval Data transmitted at low to high edge The library configures SPI to the master mode clock 20kHz data sampled at the middle of interval clock idle state low and data transmitted at low to high edge Important The Software SPI library implements time based activities so interrupts need to be disabled when using it External dependencies of Software SPI Library The following variables must be defined in all projects using Software SPI Description Library var SoftSpi SDI sbit sfr g Data In line var SoftSpi SDI sbit at RF2 bit external ae var SoftSpi SD
3. End LCD module connections var text array 16 of char RR byte begin ADPCFG OxFFFF text mikroElektronika Led Init Lcd Cmd LCD CLEAR Lcd Cmd LCD CURSOR OFF for i 1 to 17 do Led Ohr L 2 textlr 1 end MikroElektronika 116 mikroPascal PRO for PIC32 After successful compilation and MCU programming press F9 to start the mikrolCD After the mikrolCD initialization a blue active line should appear e E E Watch Values I3 k BUBE a 9 text mikroElektronika El Eh Eh eo oe er a E A 50 a Add Remove gt Properties tq Add All Remove All e i He nensi c Select variable from list Lcd Cmd LCD CLEAR rat P Lcd Cmd LCD CURSOR OFF Search for variable by assembly name lest y s Lf lito 17 pee a 2 v Peripherals Freeze hegn i i Lcd Chr i1 i text i 1 Name Value Address E end PORTB 0 OQ E end TRIB nc text dE 0x0800 PC 0x0002B0 0 00 us We will debug the program line by line Pressing F8 we are executing code line by line However it is not recommended that user does not use Step Into F7 and Step Over F8 over Delays routines and routines containing delays Instead use Run to cursor F4 and Breakpoints functions All changes are read from MCU and loaded into Watch Window Note that TRISB changed its value from 255 to 0 void main o E Watch Va
4. Shift display left without changing display data RAM Shift display right without changing display data RAM 465 MikroElektronika mikoPascal PRO for PIC32 Library Example Default Pin Configuration Use SPI Lcd Init for default pin settings see the first figure below Copy Code To Clipboard program Spi Lcd var text var counter Port var SPExpanderRST SPExpanderCS SPE SPE End Port array 16 byte xpanderRST Direction xpanderCS Direction sbit at sbit at of char Expander module connections LATD8 bit LATD9 bit procedure Move Delay begin Delay ms 500 end begin Lext ve CHECON ADIPCFG lf If Port Initialize S mikroElektronika x32 OxFFFF sbit at TRISD8 bit sbit at 1 Expander module connections RISD9 bit Function used for text moving You can change the moving speed here Configure AN pins as digital Expander Library uses SPI2 module PI module used with PortExpander SPI2 Init Advanced SPI MASTER SPI 8 BIT 4 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE LOW SPI ACTIVE 2 IDLE Spi Lcd Config 0 Initialize LCD over SPI interface Spi Lcd Cmd LCD CLEAR Clear display Spi Lcd Cmd LCD CURSOR OFF Turn cursor off Spi Lcd Out 1 6 mikroE Print text to LCD lst row 6th c
5. SPIL Init initialize SPI1 module CANSPIInrt 1 3 59 29 1 CANSPT Init Flags initialize CANSPI Notes CANSPI mode NORMAL will be set on exit MikroElektronika 244 mikroPascal PRO for PIC32 CANSPISetBaudRate Prototype procedure CANSPISetBaudRate SJW BRP PHSE EG2 PROPSEG CANSPI CONFIG FLAGS char Nothing Description Sets the CANSPI module baud rate Due to complexity of the CAN protocol you can not simply force a bps value Instead use this function when the CANSPI module is in Config mode SAM SEG2PHTS and WAKFIL bits are set according to CANSPI CONFIG FLAGS value Refer to datasheet for details Parameters SJW as defined in MCU s datasheet CAN Module BRP as defined in MCU s datasheet CAN Module PHSEG1 as defined in MCU s datasheet CAN Module PHSEG2 as defined in MCU s datasheet CAN Module PROPSEG as defined in MCU s datasheet CAN Module CANSPI CONFIG FLAGS is formed from predefined constants See CANSPI CONFIG FLAGS constants Nothing Requires The CANSPI module must be in Config mode otherwise the function will be ignored See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page set required baud rate and sampling rules var CANSPI CONFIG FLAGS byte
6. CPO GET Prototype function CPO GET const register TCPORI Function returns the value of the coprocessor register or part of the register based upon the argument entered Parameter must be a constant from the enumerated built in constants list which can be found at the bottom of this page Returns Value of the coprocessor register or part of the register var register value dword register value i CPO GET CPO0 CONFIG CPO SET Prototype procedure CPO SET const register TCPOREG value dword Function sets the value of the coprocessor register or part of the register based upon the register argument Parameters Function sets the value of the coprocessor register or part of the register based upon the register argument CPO SET CPO CONFIG 0x1A2C0000 Enablelnterrupts procedure EnableInterrupts Description Function enables interrupts Parameters None Returns Nothing o Example EnableInterrupts Notes None MikroElektronika 158 mikroPascal PRO for PIC32 Disablelnterrupts eum Noting Example Pebiemeerrpes Moes None oo CPO CONFIG3 CPO DEBUG CPO TRACECONTROL CPO TRACECONTROL2 CPO USERTRACEDATA CPO TRACEBPC CPO DEBUG2 CPO DEPC CPO0 ERROREPC CPO DESAVE 159 MikroElektronika mikoPascal PRO for PIC32 CPO SRSCTL PSS CP0 SRSMAP SSV1 CP0_SRSMAP_SSV6 CPO CAUSE RIPL CPO CAUSE IP6 CPO CAUSE DC CP0_PRI
7. File name Easy_GSM_GPRS Files of type Image Files bmp jpg png My Nistor C Open as read only There you should select the desired image to be added In our example Easy GSM GPRS jpg image will be added Selected picture is automatically added to the drop down list of the Image field in Active Comment Editor Active Comments Editor Select Active Comment activeComment Active Comment Actions New Rename Properties SI Attributes www mikroe com iJ Events OnLeftClick Alt i OnRightClick OnDblClick OnMouseOver Add Image To Project Add File To Project MikroElektronika mikroPascal PRO for PIC32 Now when image has been selected we can assign an event to it For example OnMouseOver will be used for Previewlmage action and OnLeftClick Alt will be assigned to OpenUrl action www mikroe com Easy_GSM_GPRS jpg None OnRightCliik None OnDblClick None OnMouseOver X PreviewImage Now we can save our changes to Active Comment by clicking the Save button Note Setting file attributes is same as for image so it won t be explained separately Once we have finished creating our active comment we can notice that it has been added to source file on current caret position with ac prefix telling IDE that itis active comment I V ae activeConment 30 Now let s try it If you LeftClick Alt on it URL in default Web browser will be opened
8. Play 784 procedure Melody begin Tonel Tonel ronel ronel Tonel Tone3 end P n procedure begin Sound Play 880 end procedure begin Sound Play 1046 end procedure begin Sound Play 1318 end procedure Melody2 0 0 0 0 0 0 Tone2 Tone2 B Tone2 Tone2 Tone2 n Tone3 n ToneA ToneC ToneE var counter byte begin for counter 0 0 0 0 0 0 250 250 250 E n n n downto 1 do Frequency Frequency Frequency Plays the n Tonel n 659Hz duration 250ms 698Hz duration 250ms 784Hz duration 250ms melody Yellow house Tones used in Melody2 function Plays Melody2 MikroElektronika 392 mikroPascal PRO for PIC32 begin ToneA r oneC ToneE end end begin CHECON 0x32 ADIPCFG OxFFFF TRISB OxF8 Sound Init PORTD 3 Sound Play 880 1000 while TRUE do begin if Button PORTB 7 1 1 then begin Tonel while RB7 bit lt gt 0 do nop end if Button PORTB 6 1 1 then begin Tone2 while RB6 bit 0 do nop end if Button PORTB 5 1 1 then begin Tone3 while RB5 bit 0 do nop end if Button PORTB 4 1 1 then begin Melody2 while RB4 bit 0 do nop end if Button PORTB 3 1 1 then begin Melody while RB3 bit
9. Example crearse rote 7 77 Clear RE OOOO etes oe Oooo 149 MikroElektronika mikoPascal PRO for PIC32 TestBit Prototype function TestBit register rbit byte byte Description Function tests if the bit roit of register is set If set function returns 1 otherwise returns 0 Parameter rbit needs to be a variable or literal with value 0 7 See Predefined globals and constants for more information on register identifiers This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Parameters register desired register rbit desired bit Returns If the bit is set returns 1 otherwise returns 0 Nothing flag TestBit PORTE E2 is set otherwise 0 Prototype procedure Delay us Time In us dword Description Creates a software delay in duration of Time In us microseconds This is an inline routine the code is generated in the place of the call so the call doesn t count against the nested call limit Parameters Time In us delay time in microseconds Valid values constant values range of applicable constants depends on the oscillator frequency eum Noting Example Delay us 10 Ten microseconds pause Notes None SSCS Delay_ms Prototype procedure Delay ms Time In ms dword Description Creates a software delay in duration of Time In ms milliseconds This is an inline routine
10. Interface globals J BR RK RK RK KK KR KR RK OK KK kc k kc k KK ck k KK eK eK constants declarations const types declarations type variables declarations var Name Name2 ltype absolute 0x123 external volatile register Sfr procedures prototypes procedure procedure name var const ParamName type var const ParamName2 ParamName3 type functions prototypes function function name var const ParamName type var const ParamName2 ParamName3 type type J BK RK RK KK RR kk kk kk kck kc kckck kc kckck kc kckck kckckck kc kckck ck kckck ck kok kk ko kk Implementation J BK RK RK HK kk kk Rk kk Ckck kc kckck kc kckck kc kckckckckckck kc kckckckckckck ck kok kk kokk implementation constants declarations const types declarations type variables declarations var Name Name2 ltype absolute 0x123 external volatile register Sfr labels declarations label procedures declarations procedure procedure name var const ParamName type var const ParamName2 ParamName3 type ilevel 0x123 overload forward local declarations begin end MikroElektronika 188 mikroPascal PRO for PIC32 functions declarations function function name var const ParamName type var const ParamName2 ParamName3 type type ilevel 0x123 overload forwar
11. MMC SD card must be initialized See Mmc Init var error word dataBuffer array 16 of byte rror Mme Read Csd dataBuffer MikroElektronika 330 mikroPascal PRO for PIC32 Mmc Fat Init Prototype function Mmc Fat Init word Initializes MMC SD card reads MMC SD FAT 16 boot sector and extracts necessary data needed by the library 0 if MMC SD card was detected and successfully initialized 1 if FAT16 boot sector was not found 255 if MMC SD card was not detected Requires Global variables Mmc Chip Select Chip Select line Mmc Chip Select Direction Direction of the Chip Select pin must be defined before using this function The appropriate hardware SPI module must be previously initialized See the SPIx Init SPIx Init Advanced routines IDLE MMC SD card has to be formatted to FAT16 file system MMC module connections var Mmc Chip Select sbit at LATFO bit var Mmc Chip Select Direction sbit at TRISFO bit MMC module connections Initialize the SPI module SPI1 Init Advanced SPI MASTER SPI 8 BIT SPI PRESCALE SEC 1 SPI PRESCALE PRI 64 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 IDLE Initialize MMC SD card and MMC FAT16 library globals Mme Fat Init Reinitialize the SPI module at higher speed change primary prescaler SPI1 Init Advanced SPI MASTER SPI 8 BIT SPI PRESCALE SEC 1 SPI PRESCALE
12. MikroElektronika 9532 mikroPascal PRO for PIC32 TFT_Set_Brush Prototype procedure TFT Set Brush brush enabled byte brush color word gradient enabled gradient orientation byte gradient color from gradient color to word Description Sets color and gradient which will be used to fill circles or rectangles Parameters brush enabled enable brush fill Enable brush fill o Disable brush fill brush color set brush fill color 533 MikroElektronika mikoPascal PRO for PIC32 Description gradient enabled enable gradient Enable gradient lo Disable gradient gradient orientation sets gradient orientation Left to right gradient orientation Top to bottom gradient orientation gradient color from sets the starting gradient color MikroElektronika 534 mikroPascal PRO for PIC32 Description gradient color to sets the ending gradient color TFT module needs to be initialized See the TFT Init routine Enable gradient from black to white color left right orientation TFT Set Brush 0 0 1 LEFT TO RIGHT CL BLACK CL WHITE TFT Line Prototype procedure TFT Line xl yl x2 y2 integer Description Draws a line from x1 y1 to x2 y2 Parameters x1 X coordinate of the line start y1 y coordinate of the line end x2 X coordinate of the line start y2 y coordinate of the line end TFT module needs to be i
13. Refer to the device data sheet for baud rates allowed for specific Fosc UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Switching between the UART modules in the UART library is done by the UART Set Active function UART modules have to be previously initialized Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 554 mikroPascal PRO for PIC32 UARTx Data Ready ITE The function tests if data in receive buffer is ready for reading 1 if data is ready for reading 0 if there is no data in the receive register Requires Routine requires at least one UART module Used UART module must be initialized before using this routine See UARTx Init and UARTx Init Advanced routines var receive word read data if ready if UART1 Data Ready then receive UART1 Read UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library UARTx Tx Idle Use the function to test if the transmit shift register is empty or not
14. ShortToStr Prototype procedure ShortToStr input short var output array 4 of char Description Converts input short signed byte number to a string The output string is right justified and remaining positions on the left if any are filled with blanks Parameters input signed short number to be converted ae i destination string Destination string should be at least 5 characters in length var t short txt array 4 of char 24 ByteToStr t txt txt is 24 one blank here 913 MikroElektronika mikoPascal PRO for PIC32 WordToStr Prototype procedure WordToStr input word var output array 5 of char Description Converts input word to a string The output string is right justified and the remaining positions on the left if any are filled with blanks Parameters input word to be converted a destination string var t word txt array 5 of char i 437 WordToStr t txt txt is 437 two blanks here IntToStr Prototype procedure IntToStr input integer var output array 6 of char Description Converts input integer number to a string The output string is right justified and the remaining positions on the left if any are filled with blanks Parameters input signed integer number to be converted output destination string var input integer txt array 6 of char Jd andes begin input 4220 IntToStririnput txt
15. When using this library with PIC32 family MCUs be aware of their voltage incompatibility with certain number of Lcd modules So additional external power supply for these modules may be required Library uses the SPI module for communication The user must initialize the appropriate SPI module before using the SPI Lcd8 Library For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by using the SPI Set Active routine See the SPI Library functions This Library is designed to work with the mikroElektronika s Serial Lcd Glcd Adapter Board pinout see schematic at the bottom of this page for details Library Dependency Tree m Port Expander SPI Lcd8 pE gt Lcd Constants External dependencies of SPI Lcd Library The implementation of SPI Lcd Library routines is based on Port Expander Library routines External dependencies are the same as Port Expander Library external dependencies Library Routines SPI Lcd8 Config SPI Lcd8 Out SPI Lcd8 Out Cp SPI Lcd8 Chr SPI Lcd8 Chr Cp SPI Lcd8 Cmd MikroElektronika 468 mikroPascal PRO for PIC32 SPI Lcd8 Config Prototype pProcedure SPI Lcd8 Config DeviceAddress byte Description Initializes the Lcd module via SPI interface Parameters DeviceAddress SPI expander hardware address see schematic at the bottom of this page Nothing Requires Global variables SPExpanderCs Chip Select line
16. returns the linefeed character Nus he OOO O MikroElektronika 148 mikroPascal PRO for PIC32 Ord Prototype function Ord const character char byte Description Function returns ASCII code of the character This is an inline routine the code is generated in the place of the call Parameters character input character IReums ASCH code oftie charac OOOO Example C Ord A returns 65 oes None SetBit Prototype procedure SetBit var register word rbit byte Description Function sets the bit roit of register Parameter rbit needs to be a variable or literal with value 0 15 For more information on register identifiers see Predefined Globals and Constants This is an inline routine the code is generated in the place of the call Parameters register desired register rbit desired bit eum Noting example setsit Ponts 7 77 Set RBB OOOO Moes None SSCS ClearBit Prototype procedure ClearBit var register byte rbit byte Description Function clears the bit rbit of register Parameter rbit needs to be a variable or literal with value 0 7 See Predefined globals and constants for more information on register identifiers This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Parameters register desired register rbit desired bit eum Nong
17. txt mikroElektronika txt sub mike res strstr txt_sub txt strcspn Prototype function strcspn var sl s2 string word Description The function searches the string s1 for any of the characters in the string s2 The function returns the index of the first character located in s1 that matches any character in s2 If the first character in s1 matches a character in s2 a value of 0 is returned If there are no matching characters in s1 the length of the string is returned not including the terminating null character txt mikroElektronika txt sub mikr res strcspn txt sub txt Prototype function strpbrk var sl s2 string word Description The function searches si for the first occurrence of any character from the string s2 The null terminator is not included in the search The function returns an index of the matching character in s1 If s1 contains no characters from s2 the function returns OxFFFF txt mikroElektronika txt sub mikr res strpbrk txt sub txt strrchr Description The function searches the string s for the last occurrence of the character ch The null character terminating s is not included in the search The function returns an index of the last ch found in s if no matching character was found the function returns 0xFFFrF txt mikroElektronika res strrchr txt k returns the index of th
18. CANSPISetOperationMode CANSPI MODE CONFIG OxFF set CONFIGURATION mode CANSPI module must be in config mode for baud rate settings CANSPI CONFIG FLAGS CANSPI CONFIG SAMPLE THRICE and CANSPI CONFIG PHSEG2 PRG ON and CANSPI CONFIG STD MSG and CANSPI CONFIG DBL BUFFER ON and CANSPI CONFIG VALID XTD MSG and CANSPI CONFIG LINE FILTER OFF 1 CANSPI CONFIG FLAGS 245 MikroElektronika mikoPascal PRO for PIC32 CANSPISetMask Prototype procedure CANSPISetMask CANSPI MASK byte val longint CANSPI CONFIG FLAGS byte Description Configures mask for advanced filtering of messages The parameter value is bit adjusted to the appropriate mask registers Parameters CANSPI MASK CAN module mask number Valid values CANSPT MASK constants See CANSPI_ MASK constants val mask register value This value is bit adjusted to appropriate buffer mask registers CANSPI CONFIG FLAGS selects type of message to filter Valid values CANSPI CONFIG ALL VALID MSG CANSPI CONFIG MATCH MSG TYPE amp CANSPI CONFIG STD MSG CANSPI CONFIG MATCH MSG TYPE amp CANSPI CONFIG XTD MSG See CANSPI_CONFIG_FLAGS constants Requires The CANSPI module must be in Config mode otherwise the function will be ignored See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra
19. In the First Unit we will define and declare routine called pi r squared calculates pi multiplied by the radius squared unit First Unit procedure pi r squared rr real Declaration of the pi r squared routine implementation procedure pi r squared rr real Definition of the pi r squared routine var res real begin res rr 3 14 end end In the Second Unit we will make a call to the routines defined externally r squaredandpi_ r squared First of all we must declare their prototypes followed with a external modifier Then we can proceed to the routine call unit Second Unit procedure CircleArea function r squared r real real external Declaration of the r squared routine defined in Main Unit followed with a external modifier procedure pi r squared rr real external Declaration of the pi r squared routine defined in First Unit followed with a external modifier implementation procedure CircleArea Definition of the CircleArea routine var res real begin res r squared 5 xr squared routine call pi r squared res pi r squared routine call end end Variables and PIC32 Every declared variable consumes part of RAM memory Data type of variable determines not only the allowed range of values but also the space a variable occupies in RAM memory Bear in mind that operations using different types of variables take different time to be completed mikroPascal PRO fo
20. Initialize SPI1 module SPI2 Init CANSPIInitialize 1 3 3 3 1 Can Init Flags initialize external CANSPI module CANSPISetOperationMode CANSPI MODE CONFIG OxFF set CONFIGURATION mode CANSPISetMask CANSPI MASK B1 1 CANSPI CONFIG XTD MSG set all maskl bits to ones CANSPISetMask CANSPI MASK B2 1 CANSPI CONFIG XTD MSG set all mask2 bits to ones CANSPISetFilter CANSPI FILTER B2 F3 ID 1st CANSPI CONFIG XTD MSG Il Bet id of filter B2 F3 to lst node ID CANSPISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode while TRUE do endless loop begin Msg Rcvd CANSPIRead Rx ID RxTx Data Rx Data Len Can Rcv Flags receive message if Rx ID ID 1st and Msg Rcvd then if message received check id begin PORTB RxTx Data 0 id correct output data at PORTB Inc RxTx Data 0 increment received data CANSPIWrite ID 2nd RxTx Data 1 Can Send Flags send incremented data back end end end 255 MikroElektronika mikoPascal PRO for PIC32 HW Connection o o la Shielded twisted pair 5 1 8 2250020063 PIC32MX460F512L DODUDUUUUU ovcca oVCC3 o VCC3 OSCELATOR Example of interfacing CAN transceiver MCP2510 with MCU via SPI interface 296 mikroPascal PRO for PIC32 Compact Flash Library The Compact Flash Library provides routines for accessing data on Compact Flash
21. Library Dependency Tree L SPI SPI Ethernet String 403 MikroElektronika mikoPascal PRO for PIC32 External dependencies of SPI Ethernet Library The following variables must be defined in all projects using SPI Ethernet Library var SPI Ethernet CS sbit sfr external ENC28J60 chip select pin var SPI Ethernet RST sbit sfr external ENC28J60 reset pin var SPI Ethernet CS Direction sbit sfr external var SPI Ethernet RST Direction external sbit Direction of the ENC28J60 reset pin Sfr The following routines must be defined in all project using SPI Ethernet Library function SPI Ethernet UserTCP var remoteHost array 4 of byte remotePort word SEULS TCP request handler word reqLength word var flags TEthPktFlags word function SPI_Ethernet_UserUDP var remoteHost array 4 of byte remotePort word ies UDP request handler word reqLength word var flags TEthPktFlags word Deco Example var SPI Ethernet CS LATF1 bit sbit at var SPI Ethernet RST at LATFO bit sbit Direction of the ENC28J60 var SPI Ethernet CS Direction chip select pin sbit at TRISFl bit var Direction bits SPI Ethernet RST sbit at TRISF0 Depos tempe OO Refer to the library example at the bottom of this page for code implementation Refer to the library example at the bottom of this page for code implementation MikroEl
22. Variables Sorted By Address Click on column header to sort table by Address Name Unique Assembler Name or Size MikroElektronika 64 mikroPascal PRO for PIC32 SFR Locations Displays list of used SFR locations 387 88558858258589089889T USE EN N CEE AEE EEEE M EEE E ECR ICICIE E CEACIEEIEJE AGI ACT EACI LAE JEDER EIEACIES PII IMES 2 411 ROM Memory Usage Displays ROM memory space usage in a pie like form Statistics BO7S bytes 0 6 521214 bytes 99 4 524289 bytes Project Name C Dewelopment Systemsll V32MY VEILED COG 2x16 lLd mep32 Tene 1 31 2011 1 03 40 PM vewvemioe com mikoPascal PRO for PIC32 ROM Memory Constants Displays ROM memory constants and their addresses ROM Memory Constants Project Name C Development SystemslLVA2Mx VEILED COG 2xi6 iLed ancp32 Tene 1 31 2011 1 03 40 PM Sewers com Functions Sorts and displays functions in various ways Functions Sorted By Address Click on column header to sort table by Address Name Urigue Assembler Name or Size Lcd nit Lcd Out 32 488 32 16 16 204 28 36 28 424 56 1220 324 Project Name C Development SystemslL VIZMK v6l CD COG 2x16 iLed mep32 Tene 1 31 2011 1 03 40 PM seem mibroe com mikroPascal PRO for PIC32 Functions Sorted By Name Chart Sorts and displays functions by their name in the ascending order 1 000 1 100 1200 1300 Double click on
23. var myMacAddr array 6 of byte my MAC address myIpAddr array 4 of byte my IP addr myMacAddr 0 0x00 myMacAddr 1 0x14 myMacAddr 2 0xA5 myMacAddr 3 0x76 myMacAddr 4 myMacAddr 5 d f 0x19 Ox3F myIpAddr 0 192 mylIpAddr 1 168 myIpAddr 2 1 myIpAddr 3 60 SPIl Init SPI Ethernet Init myMacAddr myIpAddr SPI Ethernet FULLDUPLEX MikroElektronika A06 mikroPascal PRO for PIC32 SPI Ethernet Enable Prototype procedure SPI Ethernet Enable enFlt byte Description This is MAC module routine This routine enables appropriate network traffic on the ENC28760 module by the means of it s receive filters unicast multicast broadcast crc Specific type of network traffic will be enabled if a corresponding bit of this routine s input parameter is set Therefore more than one type of network traffic can be enabled at the same time For this purpose predefined library constants see the table below can be ORed to form appropriate input value Advanced filtering available in the ENC28J60 module such as Pattern Match Magic Packet and Hash Table can not be enabled by this routine Additionaly all filters except CRC enabled with this routine will work in OR mode which means that packet will be received if any of the enabled filters accepts it This routine will change receive filter configuration on the fly It will not in
24. 0 do nop end end end Ls LH P Configure AN pins as digital I O Configure RB7 RB3 as input endless loop If PORTB 7 is pressed play Tonel Wait for button to be released If PORTB 6 is pressed play Tonel Wait for button to be released If PORTB 5 is pressed play Tonel Wait for button to be released If PORTB 4 is pressed play Tonel Wait for button to be released If PORTB 3 is pressed play Tonel Wait for button to be released MikroElektronika mikoPascal PRO for PIC32 HW Connection OSCILLATOR ap imd L PIEZO 2 SPEAKER Example of Sound Library MikroElektronika 394 mikroPascal PRO for PIC32 SPI Library The SPI module is available with all PIC32 MCUs mikroPascal PRO for PIC32 provides a library for initializing the Slave mode and initializing and comfortable work with the Master mode The PIC32 can easily communicate with other devices via SPI A D converters D A converters MAX7219 LTC1290 etc Important SPI library routines require you to specify the module you want to use To select the desired SPI module simply change the letter x in the routine prototype for a number from 1 to 3 Number of SPI modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Switching between the SPI modules in th
25. 31 MikroElektronika mikoPascal PRO for PIC32 Lcd Library mikroPascal PRO for PIC32 provides a library for communication with Lcds with HD44780 compliant controllers through the 4 bit interface An example of Lcd connections is given on the schematic at the bottom of this page For creating a set of custom Lcd characters use Lcd Custom Character Tool Library Dependency Tree Lcd Lcd Constants Keypad Key Click The following variables must be defined are fmaipejedesangceatiey somete amie var LCD_EN Direction sbit Enable direction pin LCD EN Direction external pin Di bit var LCD D7 Direction Data 7 direction pin LCD D7 Direc external i IOR RIN SB3 bit var LCD D6 Direction Data 6 direction pin LCD D6 Direction external pin SB2 bit var LCD D5 Direction Data 5 direction pin LCD D5 Direc external Hess SBl bit var LCD Direction i LCD D4 Direc external Data 4 direction pin SBO bit Library Routines var LCD RS Direction Sbit sfr LCD RS Direction i e Register Select direction pin pd external DO bit Lcd Init Lcd Out Lcd Out Cp Lcd Chr Lcd Chr Cp Lcd Cmd MikroElektronika 318 mikroPascal PRO for PIC32 Lcd Init Requires Global variables LC Data bit 7 LC Data bit 6 LC Data bit 5 LC Data bit 4 LC Register Select data instruction signal pin L
26. Command Data signal S f external LATFO bit var T6963C ctrlrst sbit sfr Lr6963C ctrl Reset signal ir ner external F4 bit var T6963C ctrlwr Direction Direction of the Write pin Lr6963C ctrlwr Direction sbit sfr external is epin at TRISF2_bit var T6963C ctrlrd Direction lrd Direction shit sfr external Direction of the Read pin Fl bit var T6963C ctrlcd Direction Direction of the Command lcd Direction sbit sfr external Data pin FO var T6963C ctrlrst Direction Direction of the Reset pin var T696 rst Direction sbit sfr external PER sbit at 1 F4 bit 499 MikroElektronika mikoPascal PRO for PIC32 Library Routines T6963C init T6963C writeData T6963C writeCommand T6963C_setPtr T6963C waitReady T6963C fill T6963C dot T6963C write char T6963C write text T6963C line T6963C rectangle T6963C Rectangle round edges T6963C Rectangle round edges fill T6963C box T6963C circle T6963C Circle fill T6963C image T6963C Partiallmage T6963C sprite T6963C set cursor T6963C displayGrPanel T6963C displayTxtPanel T6963C_setGrPanel T6963C setTxtPanel T6963C panelFill T6963C grFill T6963C txtFill T6963C cursor height T6963C graphics T6963C text T6963C cursor T6963C cursor blink MikroElektronika 500 mikroPascal PRO for PIC32 T6963C init Proto
27. J s 5j assign value 10 to variable j is at the address 0x003A ptrl Qi ptrl is pointer to byte pointing to i ptr2 Qj ptr2 is a pointer pointing to j x 2 pbrl ptr2 result is equal to the sum of the values pointed to x 5 end Pointer Subtraction Similar to addition you can use Dec to subtract an integral value from a pointer If a pointer is declared to point to type subtracting an integral value n from the the pointer decrements the pointer value byn sizeof type as long as the pointer remains within the legal range first element to one beyond the last element If type has a size of 10 bytes then subtracting 5 from a pointer to type pushes back the pointer 50 bytes in memory For example var a array 10 of byte array a containing 10 elements of type byte ptr i byte pointer to byte begin ptr Ga 6 ptr is pointer to byte pointing to a 6 ptr ptr 3 ptr 3 is a pointer pointing to a 3 ptr lt 6 a 3 now equals 6 Dec ptr ptr now points to the previous element of array a a 2 end Also you may subtract two pointers The difference will be equal to the distance between two pointed addresses and is calculated regarding to the type which the pointer points to For example var i j x byte variables ptrl byte pointers to byte pir2 i byte begin i 10 assign value 10 to variable i is at the address 0x0039 j 5 assign va
28. U2RXIF bit end 0 begin CHECON AD1PCFG 0x32 OxFF TRISB TRISD PORTB PORTD eoOoOoococ Ne Ne Ne Ne UART2 Init 1920 Delay ms 100 FF 0 hy ensure interrupt not pending initialize UART2 module RS485Slave Init 160 Intialize MCU as slave address 160 dat 0 OxAA dat 1 OxF0 dat 2 OxOF dat 4 0 ensure that message received flag is 0 dat 5 0 ensure that error flag is 0 dat 6 0 U2IPO bit 1 set interrupt UZ2IPl bit 1 4 priority U2IP2 bit 1 toT URXISELI U2STA bit 0 Ox Interrupt flag bit is set when a character is received U2RXIF bit 0 ensure interrupt not pending MVEC bit 1 Interrupt controller configured for multi vectored mode asm ei R0 Enable all interrupts end U2RXIE bit 1 enable intterupt while TRUE do begin if dat 5 0 then if an error detected signal it by begin PORTD OxAA setting portd to OxAA dat 5 0 end if dat 4 lt gt 0 then upon completed valid message receiv begin dat 4 0 data 4 is set to OxFF j dat 3 for i 1 to dat 3 do show data on PORTB PORTB dat i 1 dat 0 dat 0 1 increment received dat 0 Delay ms 1 RS485Slave Send dat 1 and send it back to master end end end MikroElektronika 374 mikroPascal PRO for PIC32 HW Connection Shielded pair no longer than 300m
29. UART1 Write Line outstr end else begin file was not found signal it UART1 Write 0x55 Delay ms 1000 UART1 Write 0x55 end end VA Tries to create a swap file fi sectors see Help for details procedure M Create Swap File var i word begin for i 0 to 511 do Buffer i i Size Cf Fat Get Swap File 5000 function for details if size 0 then begin LongIntToStr size err txt UART1 Write Line err txt for i 0 to 4999 do begin WikbsOR test Cf Write Sector size Buffer hour 0x20 minute whose size will be at least 100 see help on this 219 MikroElektronika mikoPascal PRO for PIC32 Inc size UART1 Write end end end Main Uncomment the function s to test the desired operation s begin err txt FAT16 not found file contents XX CF FATIG library by Anton Rieckert file contents LINE LEN 2 13 file contents LINE LEN 1 10 file contents LINE LEN 0 filename MIKROO0xTXT I Sdefine COMPLETE EXAMPLE comment this line to make simpler smaller example CHECON 0x32 ADIPCFG OxFFFF disable A D inputs Initialize UART1 module UART1 Init 56000 Delay ms 10 UART1 Write Line MCU Started MCU present report Init the FAT library use Cf Fat QuickFormat instead of init routine if a format is needed
30. day buffer to store day of modification attribute to Upon function execution day of modification attribute is returned through this parameter hours bufferto store hours of modification attribute to Upon function execution hours of modification attribute is returned through this parameter mins buffer to store minutes of modification attribute to Upon function execution minutes of modification attribute is returned through this parameter Nothing Requires CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign var year word month day hours mins byte Cf Fat Get File Date Modified year month day hours mins 269 MikroElektronika mikoPascal PRO for PIC32 Cf_Fat_Get_File_Size Returns Size oftne curentiy assigned fie in byes Requires CF card and CF library must be initialized for file operations See Cf_Fat_Init File must be previously assigned See Cf_Fat_Assign var my file size dword my file size Cf Fat Get File Size Cf Fat Get Swap File Prototype function Cf Fat Get Swap File sectors cnt dword var filename string 11 file attr byte dword Description This function is used to create a swap file of predefined name and size on the CF media If a file with specified name already exists on the media search for consecutive sectors will ignore sectors occupied by t
31. frames are padded to 60 bytes CRC maximum packet size is set to 1518 Back to Back Inter Packet Gap 0x15 in full duplex mode 0x12 in half duplex mode Non Back to Back Inter Packet Gap 0x0012 in full duplex mode 0x0C12 in half duplex mode Collision window is set to 63 in half duplex mode to accomodate some ENC28J60 revisions silicon bugs CLKOUT output is disabled to reduce EMI generation half duplex loopback disabled LED configuration default LEDA link status LEDB link activity 405 MikroElektronika mikoPascal PRO for PIC32 Parameters mac RAM buffer containing valid MAC address ip RAM buffer containing valid IP address full Duplex ethernet duplex mode switch Valid values 0 half duplex mode and 1 full duplex mode Requires Global variables SPI Ethernet CS Chip Select line SPI Ethernet CS Direction Direction of the Chip Select pin SPI Ethernet RST Resetline SPI Ethernet RST Direction Direction of the Reset pin must be defined before using this function The SPI module needs to be initialized See the SPIx Init and SPIx Init Advanced routines SPI Ethernet module connections var SPI Ethernet RST sbit at RFO bit var SPI Ethernet CS sbit at RFI bit var SPI Ethernet RST Direction sbit at TRISFO bit var SPI Ethernet CS Direction sbit at TRISF1 bit const SPI Ethernet HALFDUPLEX 0 const SPI Ethernet FU LLDUPLEX Ts
32. mikroPascal PRO for PIC32 Cf_Fat_Rewrite Prototype procedure Cf Fat Rewrite Description Opens currently assigned file for writing If the file is not empty its content will be erased Nothing Requires CF card and CF library must be initialized for file operations See Cf Fat Init The file must be previously assigned See Cf Fat Assign open file for writing Cf Fat Rewrite Cf Fat Append Prototype procedure Cf Fat Append Opens currently assigned file for appending Upon this function execution file pointers will be positioned P after the last byte in the file so any subsequent file writing operation will start from there Nothing Requires CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign open file for appending Cf Fat Append Notes noe CS Cf Fat Delete Requires CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign delete current fil Cf Fat Delete Notes noe OTS 261 MikroElektronika mikoPascal PRO for PIC32 Cf_Fat_Write Prototype procedure Cf Fat Write var fdata array 512 of byte data_len word Description Writes requested number of bytes to currently assigned file opened for writing Parameters fdata data to be written data_len number of RE RS to be written Retums Noth
33. mikroPascal PRO for PIC32 SPI Glcd Rectangle Round Edges Prototype Description Parameters Requires SPI Glcd Prototype Description Parameters procedure SPI Glcd Rectangle Round Edges x upper left byte y upper left byte x bottom right byte y bottom right byte radius byte color byte Draws a rounded edge rectangle on Glcd x upper left x coordinate of the upper left rectangle corner Valid values 0 127 y upper left y coordinate of the upper left rectangle corner Valid values 0 63 x bottom right x coordinate of the lower right rectangle corner Valid values 0 127 y bottom right y coordinate of the lower right rectangle corner Valid values 0 63 round radius radius of the rounded edge color color parameter Valid values 0 2 Nothing Glcd needs to be initialized see SPI Glcd Init routine Draws a rounded edge rectangle between dots 5 5 and 40 40 with radius SPI Glcd Rectangle Round Edges 5 5 40 40 12 1 Rectangle Round Edges Fill procedure SPI Glcd Rectangle Round Edges Fill x upper left byte y upper left 3 byte x bottom right byte y bottom right byte radius byte color byte Draws a filled rounded edge rectangle on Glcd with color x upper left x coordinate of the upper left rectangle corner Valid values 0 127 y upper left y coordinate of the upper left rectangle corner Valid values 0 63 x bottom right x coordinate
34. mikroPascal PRO for PIC32 memcpy Prototype procedure memcpy pl p2 byte nn word Description The function copies nn words from the memory area starting at the address p2 to the memory area starting at p1 If these memory buffers overlap the memcpy function cannot guarantee that words are copied before being overwritten If these buffers do overlap use the memmove function For parameters p1 and p2 you can use either a numerical value literal variable constant indicating memory address or a dereferenced value of an object for example mystring or PORTB txt mikroElektronika txt_sub mikr memcpy txt 4 Qtxt sub 4 string txt will be populated with the first 4 characters of the txt sub string beginning from the 4th character memmove Prototype procedure memmove pl p2 byte nn word Description The function copies nn words from the memory area starting at the address p2 to the memory area starting at p1 If these memory buffers overlap the Memmove function ensures that the words in p2 are copied to p1 before being overwritten For parameters p1 and p2 you can use either a numerical value literal variable constant indicating memory address or a dereferenced value of an object for example mystring or PORTB mikroElektronika txt sub c Wukr memmove txt 7 Qtxt sub 4 string txt will be populated with first 4 characters of the tz
35. mimm 1 upon success lease time was renewed 0 otherwise renewal request timed out while true do begin if SPI Ethernet doDHCPLeaseTime 0 then begin SPI Ethernet renewDHCP 5 it s time to renew the IP address lease with 5 secs for a reply end 419 MikroElektronika mikoPascal PRO for PIC32 Library Example This code shows how to use the Ethernet mini library the board will reply to ARP amp ICMP echo requests the board will reply to UDP requests on any port returns the request in upper char with a header made of remote host IP amp port number the board will reply to HTTP requests on port 80 GET method with pathnames will return the HTML main page s will return board status as text string tO t7 will toggle RDO to RD7 bit and return HTML main page all other requests return also HTML main page Copy Code To Clipboard program HTTP Demo ook ee ke ee EEK HERR ERER TERRE EEK EERE RAM variables J mE ehternet NIC pinout var SPI Ethernet Rst sbit at LATFO bit for writing to output pin always use latch SPI Ethernet CS sbit at LATF1 bit for writing to output pin always use latch SPI Ethernet Rst Direction sbit at TRISFO bit SPI Ethernet CS Direction sbit at TRISF1 bit end ethernet NIC definitions var myMacAddr array 6 of byte my MAC address myIpAddr array 4 of byte my IP address gwlIpAddr array
36. res 0 25 iptr 6 00 pow Prototype function pow x real y Description Function returns the value of x raised to the power y i e xY If x is negative the function will automatically cast y into unsigned long pow 10 5 res 9 999984e 4 sin wee function sin arg real real Function returns the sine of in radians The return value is from 1 to 1 Example sin PI 2 res 1 000000 sinh Prototype function sinh x real real Description Function returns the hyperbolic sine of x defined mathematically as e e 7 2 If the value of x is too large if overflow occurs the function fails sinh PI 2 res 2 301296 sqrt a function sqrt x real real Function returns the non negative square root of x res sqrt 10000 res 100 0000 tan Prototype function tan real real Description Function returns the tangent of x in radians The return value spans the allowed range of floating point aes the mikroPascal PRO for PIC32 tan PI 4 res 0 999998 tanh Prototype function tanh x real real Function returns the hyperbolic tangent of x defined mathematically as sinh x cosh x tanh PI 4 ves 0 655793 599 MikroElektronika mikoPascal PRO for PIC32 Trigonometry Library The mikroPascal PRO for PIC32 implements fundamental trigonometry functions These functions are implemented as look up tables Trigonom
37. var data byte SPI Glcd Write Data Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Glcd side x axis position and page should be set first See the functions SPI Glcd Set Side SPI Glcd Set X and SPI Glcd Set Page var data byte SPI Glcd Write Data data 449 MikroElektronika mikoPascal PRO for PIC32 SPI Glcd Fill Prototype procedure SPI Glcd Fill pattern byte Description Fills Glcd memory with byte pattern To clear the Glcd screen use SPI Gicd Fill 0 To fill the screen completely use SPI Gicd Fill OxFF byte to fill Glcd memory with Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Clear screen SPI Glcd Fill 0 SPI Glcd Dot Prototype procedure SPI Glcd Dot x pos y pos color byte Draws a dot on Glcd at coordinates x pos y pos Parameters x pos x position Valid values 0 127 y pos y position Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the dot state 0 clears dot 1 puts a dot and 2 inverts dot state Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Invert the dot in the upper left corner SPI Glcd Dot 0 0 2 Notes For x and y axis layout explanation see schematic at the bottom of this page MikroElektronika 450 mikroPascal PRO for PIC32 SPI Glcd Line Protot
38. 1 Make sure that the window containing the file that you want to print is the active window 2 Select File gt Print from the drop down menu or press Ctrl P 3 In the Print Preview Window set a desired layout of the document and click the OK button The file will be printed on the selected printer Saving file 1 Make sure that the window containing the file that you want to save is the active window 2 Select File gt Save from the drop down menu or press Ctrl S or click the Save File Icon d from the File Toolbar MikroElektronika 608 mikroPascal PRO for PIC32 Saving file under a different name 1 Make sure that the window containing the file that you want to save is the active window 2 Select File Save As from the drop down menu The New File Name dialog will be displayed 3 In the dialog browse to the folder where you want to save the file 4 In the File Name field modify the name of the file you want to save 5 Click the Save button Closing file 1 Make sure that the tab containing the file that you want to close is the active tab 2 Select File Close from the drop down menu or right click the tab of the file that you want to close and select Close option from the context menu 3 If the file has been changed since it was last saved you will be prompted to save your changes Search Paths You can specify your own custom search paths select Project Edit Search Paths option from th
39. 435 MikroElektronika mikoPascal PRO for PIC32 SPI_Ethernet_24j600_putBytes Prototype procedure SPI Ethernet 243600 putBytes ptr byte n word Description This is MAC module routine It stores requested number of bytes into ENC247600 RAM starting from current ENC24J600 write pointer EWRPT location Parameters ptr RAM buffer containing bytes to be written into ENC247600 RAM n number of bytes to be written Nothing Requires Ethernet module has to be initialized See SPI Ethernet 24 600 Init var buffer array 17 of byte buffer mikroElektronika SPI Ethernet 24 600 putBytes buffer 16 put an RAM array into ENC24J600 buffer SPI Ethernet 24j600 putConstBytes Prototype procedure SPI Ethernet 245600 putConstBytes const ptr byte n word Description This is MAC module routine It stores requested number of const bytes into ENC24J600 RAM starting from current ENC243600 write pointer zWRPT location Parameters ptr const buffer containing bytes to be written into ENC247600 RAM n number of bytes to be written Nothing Ethernet module has to be initialized See SPI Ethernet 24j600 Init const buffer array 17 of byte buffer mikroElektronika SPI Ethernet 243600 putConstBytes buffer 16 put a const array into ENC24J600 buffer MikroElektronika 436 mikroPascal PRO for PIC32 SPI Ethe
40. Append LF Send as Number ormat ASCII C HEX C DEC Clear HID Read Write Test Interrupt Assistant mikroPascal PRO for PIC32 includes the Interrupt Assistant that assist user in configuring interrupts Output is the code for the configured interrupt routine You can launch it from the drop down menu Tools Interrupt Assistant Interrupt Assistant x void interrupt i w ilevel v 4 ics SOFT OK MikroElektronika 90 mikroPascal PRO for PIC32 Lcd Custom Character mikroPascal PRO for PIC32 includes the Lcd Custom Character Output is mikroPascal PRO for PIC32 compatible code You can launch it from the drop down menu Tools Lcd Custom Character MikroElektronika LCD Custom Char Generator Save Load Fillall Clearall Invert ose const char character 0 4 4 31 4 4 0 0 void CustomChar char pos row char pos char char i Lcd Cmd 64 for i 0 i lt 7 i Lcd Chr CP character i Lcd Cmd LCD RETURN HOME Lcd Chr pos row pos char 0 91 MikroElektronika mikoPascal PRO for PIC32 Seven Segment Editor The Seven Segment Editor is a convenient visual panel which returns decimal hex value for any viable combination you would like to display on seven segment display Click on the parts of seven segment image to get the requested value in the edit boxes You can launch it from the drop down menu Tools Seven Segment Editor or by
41. E Library Manager a Essere E sound oO ser C sPr Ethernet O sPr Glcd O sPr Led O sPr Lede O sPr T6963c E sprintF C Sprinti C sprint v T6963c E Time C TouchPanel v Trigonometry E tw CO uaRT E E ED ED E 6 8 ED EE ED ED ED E ED ED Help Examples Uninstall package BinaryToGray Kal GrayToBinary Related topics mikroPascal PRO for PIC Libraries Creating New Library MikroElektronika 62 mikroPascal PRO for PIC32 Routine List Routine list diplays list of routines and enables filtering routines by name Routine list window can be accessed by pressing Ctrl L You can jump to a desired routine by double clicking on it or pressing the Enter button Also you can sort routines by size or by address Routine List EJ Sort By Name Sort By Line Line 74 Line 50 C9iMove Delay Line 54 ishift Text Left Line 64 Sishift Text Right Statistics After successful compilation you can review statistics of your code Click the Statistics Icon Bu Memory Usage Windows Provides overview of RAM and ROM usage in the various forms 63 MikroElektronika mikoPascal PRO for PIC32 Variables Displays variables sorted by addresses Project Name C Development Systems V32MX v LCO COG 2x16 cd mcp32 Time 1 31 2011 1 03 40 PM sere iit com Used RAM Locations Displays used RAM memory locations and their names
42. Easy_GSM_GPRS mpas 7 Header Files Binaries Project Level Defines S C7 Image Files Easy GSM GPRS jpg EEPROM Files S C7 Active Comments Files activeComment xml Output Files gt Other Files MikroElektronika 96 mikroPascal PRO for PIC32 You can see the contents of the created XML file by expanding Active Comment Editor Active Comments Editor Enter comment name lt activeComment gt activeComment lt Attributes gt Url nnr mikroe comc Url lt Image gt lt Image gt lt File gt lt File gt Properties lt Attributes gt Active Comment Actions New Rename Attributes lt Events gt wn mikroe com lt OnLeftClick gt lt OnLeftClick gt Image j lt 0nRightClick gt lt 0nRightClick gt File lt OnDb1Click gt lt OnDb1Click gt Ld Events lt OnMouseOver gt lt OnMouseOver gt OnLeftClick Alt lt Events gt OnRightClick aes o OnDblClick activeCommen OnMouseOver Add Image To Project Add File To Project As we mentioned above you can add image or file which are already included in project If the the desired image or file aren t added you can do it directly from here by clicking the Add Image To Project or Add File To Project button 97 MikroElektronika mikoPascal PRO for PIC32 Next file dialog will be opened Look in Images B My Recent Documents My Documents My Computer
43. Ethernet module has to be initialized See SPI Ethernet Ini t SPI Ethernet Disable SPI Ethernet CRC SPI Ethernet UNICAST disable CRC checking and Unicast traffic Advanced filtering available in the ENC28360 module such as Pattern Match Magic Packet and Hash Table can not be disabled by this routine This routine will change receive filter configuration on the fly It will not in any way mess with enabling disabling receive transmit logic or any other part of the ENC28760 module The ENC28760 module should be properly cofigured by the means of SPI Ethernet Init routine MikroElektronika 408 mikroPascal PRO for PIC32 SPI Ethernet doPacket Prototype function SPI Ethernet doPacket byte Description This is MAC module routine It processes next received packet if such exists Packets are processed in the following manner ARP amp ICMP requests are replied automatically upon TCP request the SPI Ethernet UserTCP function is called for further processing upon UDP request the SPI Ethernet UserUDP function is called for further processing Parameters None 0 upon successful packet processing zero packets received or received packet processed successfully 1 upon reception error or receive buffer corruption ENC28J60 controller needs to be restarted 2 received packet was not sent to us not our IP nor IP broadcast address 3 received IP packet was not IPv
44. Expander Write PortAB Expander Set DirectionPortA Expander Set DirectionPortB Expander Set DirectionPortAB Expander Set PullUpsPortA Expander Set PullUpsPortB Expander Set PullUpsPortAB 34 MikroElektronika mikoPascal PRO for PIC32 Expander Init Prototype procedure Expander Init ModuleAddress byte Description Initializes Port Expander using SPI communication Port Expander module settings hardware addressing enabled automatic address pointer incrementing disabled byte mode BANK O0 register adressing slew rate enabled ModuleAddress Port Expander hardware address see schematic at the bottom of this page Requires Global variables SPExpanderCs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before using this function SPI module needs to be initialized See SPIx Init and SPIx Init Advanced routines Port Expander module connections var SPExpanderRST sbit at LATFO bit SPExpanderCS sbit at LATF1 bit SPExpanderRST Direction sbit at TRISFO bit SPExpanderCS Direction sbit at TRISF1 bit End of Port Expander module connections If Port Expander Library uses SPI module SPII Init Initialize SPI module used with PortExpander Expander Init 0 Initialize Port Expander MikroElektronika 348 mikroPascal PRO fo
45. SENDIF UART Write Line Test End end else begin UART Write Line err txt Note Mme Fat Init tries to initialize a card more than once PA d If card is not present initialization may last longer depending on clock speed end end MikroElektronika 344 mikroPascal PRO for PIC32 HW Connection Pin diagram of MMC memory card OneWire Library The OneWire library provides routines for communication via the Dallas OneWire protocol for example with DS18x20 digital thermometer OneWire is a Master Slave protocol and all communication cabling required is a single wire OneWire enabled devices should have open collector drivers with single pull up resistor on the shared data line Slave devices on the OneWire bus can even get their power supply from data line For detailed schematic see device datasheet Some basic characteristics of this protocol are single master system low cost low transfer rates up to 16 kbps fairly long distances up to 300 meters small data transfer packages Each OneWire device also has a unique 64 bit registration number 8 bit device type 48 bit serial number and 8 bit CRC so multiple slaves can co exist on the same bus Important Oscillator frequency Fosc needs to be at least 4MHz in order to use the routines with Dallas digital thermometers This library implements time based activities so interrupts need to be disabled when using OneWir
46. SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before using this function The SPI module needs to be initialized See SPIx Init and SPIx Init Advanced routines Port Expander module connections var SPExpanderRST sbit at LATFO bit var SPExpanderCS sbit at LATFI bit var SPExpanderRST Direction sbit at TRISFO bit var SPExpanderCS Direction sbit at TRISF1 bit End Port Expander module connections If Port Expander Library uses SPI1 module SPIT Inst Initialize SPI module used with PortExpander SPI Lcd8 Config 0 intialize Lcd in 8bit mode via SPI 469 MikroElektronika mikoPascal PRO for PIC32 SPI Lcd8 Out ae procedure SPI Lcd8 Out row column byte var text string Prints text on Lcd starting from specified position Both string variables and literals can be passed as a text Parameters row starting position row number column starting position column number text text to be written Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routine Write text Hello on Lcd starting from row 1 column 3 SPI Leas Out ly 3 Hellol jy SPI Lcd8 Out Cp Prints text on Lcd at current cursor position Both string variables and literals can be passed as a text text text to be written Lcd needs to be initialized for SPI communicatio
47. SPI T6963C set cursor cposx 0 0 0 15 even if not visible SPI T6963C txtCols then 0 cposy Delay ms 100 end end HW Connection Toshiba T6963C Graphic LCD 240x128 Contrast Adjustment SPI T6963C Glcd HW connection 128 128 GmikroE 240x128 bmp GmikroE 240x128 bmp GmikroE 240x128 bmp GmikroE 240x128 bmp SPI T6963C grHeight SPI T6963C CHARACTE R EIGHT then 49 mikoPascal PRO for PIC32 T6963C Graphic Lcd Library The mikroPascal PRO for PIC32 provides a library for working with Gleds based on TOSHIBA T6963C controller The Toshiba T6963C is a very popular Lcd controller for the use in small graphics modules It is capable of controlling displays with a resolution up to 240x128 Because of its low power and small outline it is most suitable for mobile applications such as PDAs MP3 players or mobile measurement equipment Although small this contoller has a capability of displaying and merging text and graphics and it manages all the interfacing signals to the displays Row and Column drivers For creating a custom set of Glcd images use Glcd Bitmap Editor Tool Important When using this library with PIC32 fa
48. STOP BYTE then erc send v cre send 1 NOTE DATALEN lt 4 0 gt can not take the START BYTE 4 0 or STOP BYTE lt 4 0 gt values MikroElektronika 376 mikroPascal PRO for PIC32 Software I C Library The mikroPascal PRO for PIC32 provides routines for implementing Software IC communication These routines are hardware independent and can be used with any MCU The Software lC library enables you to use MCU as Master in IC communication Multi master mode is not supported Important This library implements time based activities so interrupts need to be disabled when using Software l C All PC Library functions are blocking call functions they are waiting for C clock line to become logical one The pins used for the Software I C communication should be connected to the pull up resistors Turning off the LEDs connected to these pins may also be required Every Software l C library routine has its own counterpart in Hardware FC library except 12C Repeated Start Soft I2C Start is used instead of I2C Repeated Start Working clock frequency of the Software C is 20kHz External dependencies of Software C Library The following variable must be defined Des ribtion in all projects using RS 485 Library P 2 var soft 12C Scl sbit sfr SoftI C Clock line var Soft I2C Scl sbit at RF3 bit external gt var Soft I2C Sda sbit sfr r Do Soft C Data line var Soft I2C Sda sbit
49. TRISB6 bit TRISB7 bit ff Z7 ee ae Loop variable Function used for text moving You can change the moving speed here Configure AN pins as digital I O Initialize LCD Clear display Cursor off Write text in first row Write text in second row Clear display Write text in first row Write text in second row MikroElektronika 322 mikroPascal PRO for PIC32 Moving text for i 0 to 3 do begin Lcd Cmd LCD SHIFT RIGHT Move Delay end while TRUE begin for i 0 to 7 do begin Lcd Cmd LCD SHIFT LEFT Move Delay end do for i 0 to 7 do begin Lcd Cmd LCD SHIFT RIGHT Move Delay end end end 7 XXXrxrczrrzrcrrsrrscri LCD COG 2X16 Move text to Endless loop Move text to Move text to Led HW connection PIC32MX460F512L 5 the right 4 times the left 7 times the right 7 times OSCILLATOR 323 MikroElektronika mikoPascal PRO for PIC32 Memory Manager Library This library provides routines for accessing microcontroller s internal Flash memory Library Routines Heap Init malloc free LargestFreeMemBlock TotalFreeMemSize Heap Init eum Ng const APT SIZE declare Heap siz set Heap size GetMem PIG procedure GetMem var P dword WantedSize word Fetches memory from the memory heap Parameters WantedS
50. The following variables must be defined in all projects using S1D13700 Graphic Description Lcd library var S1D13700 DATA external S1D13700 WR external S1D13700 RD external S1D13700 AO external var S1D13700 RES external sbit at sbit at sbit at S1D13700 CS external var S 1D13700 DATA Direction byte sfr external var Sbit sfr external var S1D13700 RD Direction sbit sfr external var S1D13700 A0 Direction sbit sfr external var S1D13700 RES Direction sbit sfr external var 1D13700 CS Direction sbit sfr external Direction of the Write pin Direction of the Read pin Direction of the System Address var sS Direction of the Reset pin Direction of the Chip select pin a R a R SC2 bit 3700 RD Direction BLE 3700 A0 Direction SCO bit var S1D13700 RES Direction SC3 bit var 5 1D13700 CS Direction TRISC4 bit MikroElektronika 218 mikroPascal PRO for PIC32 Library Routines 81D13700 Init 81D13700 Write Command 81D13700 Write Parameter 81D13700 Read Parameter 81D13700 Fill 81D13700 GrFill 81D13700 TxtFill 81D13700 Display GrLayer 81D13700 Display TxtLayer 81D13700 Set Cursor 1D13700 Display Cursor 81D13700 Write Char 1D13700 Write Text 81D13700 Dot 81D13700 Line 81D13700 H Line 81D13700 V Line 81D13700 Rectangle 81D13700 Box 81D13700 Rectangle
51. This is DHCP module routine It takes care of IP address lease time by decrementing the global lease time library counter When this time expires it s time to contact DHCP server and renew the lease 0 lease time has not expired yet 1 lease time has expired it s time to renew it Ethernet module has to be initialized See SPI Ethernet 24j600 Init while true do if SPI Ethernet 245 600 doDHCPLeaseTime lt gt 0 then begin it s time to renew the IP address lease SPI Ethernet 24j600 renewDHCP Prototype function SPI Ethernet 245 600 renewDHCP tmax byte byte This is DHCP module routine It sends IP address lease time renewal a a to DHCP server tmax time in seconds to wait for an tmax time in seconds to wait for an reply 0 E 1 upon success lease time was renewed 0 otherwise renewal request timed out Ethernet module has to be initialized See SPI_Ethernet_24j600_lnit while true do begin if SPI Ethernet 243600 doDHCPLeaseTime lt gt 0 then begin SPI Ethernet 24 600 renewDHCP 5 it s time to renew the IP address lease with 5 secs for a reply end 445 MikroElektronika mikoPascal PRO for PIC32 SPI Graphic Lcd Library mikroPascal PRO for PIC32 provides a library for operating Graphic Lcd 128x64 with commonly used Samsung KS108 KS107 controller via SPI interface For creating a custom set of Glcd images use Glcd Bitmap Editor Tool Imp
52. Watch Clock Cycles Time Current Count 2 103 943 273 1105 20 s Delta 80 881 413 4044 07 ms Stopwatch 2 103 943 273 105197 16 ms Reset To Zero 80 MHz MikroElektronika mikoPascal PRO for PIC32 Notes The user can change the clock in the Stopwatch Window which will recalculate values for the latest specified frequency Changing the clock in the Stopwatch Window does not affect actual project settings it only provides a simulation Stopwatch is available only when Software Simulator is selected as a debugger EEPROM Watch Window Note EEPROM Watch Window is available only when mikrolCD is selected as a debugger To show the EEPROM Watch Window select Debug Windows EEPROM from the View drop down menu The EEPROM Watch Window shows current content of the MCU s internal EEPROM memory There are two action buttons concerning the EEPROM Watch Window Read EEPROM Reads data from MCU s internal EEPROM memory and loads it up into the EEPROM window Write EEPROM Writes data from the EEPROM window into MCU s internal EEPROM memory EEPROM Watch Read EEPROM Write EEPROM MikroElektronika 130 mikroPascal PRO for PIC32 Code Watch Window Note Code Watch Window is available only when mikrolCD is selected as a debugger To show the Code Watch Window select Debug Windows Code from the View drop down menu The Code Watch Window shows code hex format writt
53. Write text Hello world on the position 10 inside the page 2 SPI Gleg Write Text Hello world 10 2 1 Notes For x axis and page layout explanation see schematic at the bottom of this page 45 MikroElektronika mikoPascal PRO for PIC32 SPI Glcd Image Prototype procedure SPI Glcd Image const image byte Displays bitmap on Glcd Parameters image image to be displayed Bitmap array can be located in both code and RAM memory due to the mikroPascal PRO for PIC32 pointer to const and pointer to RAM equivalency Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draw image my image on Glcd SPI Glcd Image my image Use the mikroPascal PRO for PIC32 integrated Glcd Bitmap Editor Tools gt Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd SPI Glcd Partiallmage Prototype procedure SPI Glcd Partiallmage x left y top width height picture width picture height word const image byte Displays a partial area of the image on a desired location Parameters x left x coordinate of the desired location upper left coordinate y top y coordinate of the desired location upper left coordinate width desired image width height desired image height picture width width ofthe original image picture height height of the original image image image to be displayed Bitmap array can be located in bo
54. asm ei RO Enable all interrupts end U2RXIE bit 1 enable intterupt RS485Master Send dat 1 160 while TRUE do begin Li 17 Inc cnt if dat 5 lt gt 0 then rr PORTD OxAA Le if dat 4 lt gt 0 then Id begin cnt 0 dat 4 0 i j dat 3 for i 1 to dat 3 do Pi PORTB dat i 1 dat 0 dat 0 1 Delay ms 1 RS485Master Send dat 1 160 end if cnt gt 100000 then begin Ine PORTD cnt 0 RS485Master Send dat 1 160 if PORTD gt 10 then begin RS485Master Send dat 1 50 end end end end Copy Code To Clipboard program RS485 Slave Example var dat array 20 of byte dy byte var rs485 rxtx pin sbit at RF2 bit rs485 rxtx pin direction Interrupt routine procedure interrupt begin RS485Slave Receive dat sbit at TRISF2 bit upon completed valid message receiving data 4 is set to 255 if an error detected signal it by setting portd to OxAA if message received successfully Clear message received flag show data on PORTB send back to master if in 100000 poll cycles the answer ri was not detected signal failure of send messag if sending failed 10 times iy send message on broadcast address buffer for receving sending messages set transcieve pin set transcieve pin direction iv IVT UART 2 ilevel 7 ics ICS SRS 313 MikroElektronika mikoPascal PRO for PIC32
55. l txt us 24920 MikroElektronika 574 mikroPascal PRO for PIC32 LongToStr Prototype procedure LongintToStr input longint var output array 11 of char Description Converts input longint number to a string The output string is right justified and the remaining positions on the left if any are filled with blanks Parameters input signed long integer number to be converted BUM destination string var input longint txt array 11 of char Pb sos begin input 12345678 IntToStr input txt txt is 12345678 LongWordToStr Prototype procedure LongWordToStr input dword var output array 10 of char Description Converts input double word number to a string The output string is right justified and the remaining positions on the left if any are filled with blanks Parameters input unsigned long integer number to be converted BURN destination string var input longint txt array 10 of char bE ees begin input 12345678 IntToStr input txt li txt is 12345678 979 MikroElektronika mikoPascal PRO for PIC32 FloatToStr Prototype procedure FloatToStr fnum real var str array 23 of char byte Description Converts a floating point number to a string The output string is left justified and null terminated after the last digit Parameters fnum floating point number to be converted str destination string var ffl ff2 ff3 re
56. mikoPascal PRO for PIC32 Touch Panel TFT Library The mikroPascal PRO for PIC32 provides a library for working with Touch Panel for TFT Library Dependency Tree Touch Panel 9 apc Jj External dependencies of Touch Panel TFT Library The following variables must be defined in all projects using Touch Panel TFT Library Description var DriveX Left sbit sfr external DriveX Left line var DriveX Left sbit at LATB13 bit DriveX Right sbit sfr external DriveX Right line var DriveX Right sbit at TBI1 bit DriveY Up sbit sfr external DriveY Up line DriveY Down Sbit sfr external DriveY Down line DriveY Down sbit at m 0 bi var DriveX Left Direction sbit sfr Direction of the DriveX Left pin DriveX Left Direction external sbit at TRISB13 bit var DriveX Right Direction sbit sfr Direction of the DriveX_Right pin var DriveX Right Direction external sbit at TRISB11 bit var DriveY Up Direction sbit sfr Direction of the DriveY Up pin var DriveY Up Direction i external sbit at TRISB12 bit var DriveY Down Direction sbit sfr Direction of the DriveY Down pin var DriveY Down Direction external sbit at TRISB10 bit Library Routines TP TFT Init TP TFT Set ADC Threshold TP TFT Press Detect TP TFT Get Coordinates TP TFT Calibrate Min TP TFT Calibrate Max TP TFT Get Calibration Consts TP TFT Set Calib
57. mikroPascal PRO for PIC32 Manual mikroPascal PRO for PIC32 is a full featured C compiler for PIC32 MCUs from Microchip It is designed for developing building and debugging PIC32 based embedded applications This development environment has a wide range of features such as easy to use IDE very compact and efficient code many hardware and software libraries comprehensive documentation software simulator COFF file generation SSA optimization up to 30 code reduction and many more Numerous ready to use and well explained examples will give a good start for your embedded project 7 MikroElektronika SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD waking ib si ple mikoPascal PRO for PIC32 Table of Contents CHAPTER 1 30 INTRODUCTION 30 Introduction to mikroPascal PRO for PIC32 31 Features 31 Where to Start 31 Software License Agreement 32 mikroElektronika Associates License Statement and Limited Warranty 32 IMPORTANT READ CAREFULLY 32 LIMITED WARRANTY 32 HIGH RISK ACTIVITIES 33 GENERAL PROVISIONS 33 Technical Support 34 How to Register 34 Who Gets the License Key 34 How to Get License Key 34 After Receving the License Key 36 CHAPTER 2 38 mikroPascal PRO for PIC32 38 Environment 38 Main Menu Options 39 File 40 File Menu Options 40 Edit 41 Edit Menu Options 41 Find Text 42 Replace Text 42 Find In Files 43 Go To Line 43 Regular expressions option 43 View 44 View Menu Options 44 Project 46
58. txt sub to txt strlen Prototype function strlen var s string word Description The function returns the length in words of the string s The length does not include the null terminating character A mikroElektronika strlen txt calculates the length of the txt string result 16 with a null character If s2 is shorter than the size characters s2 is copied up to and including the null terminating character txt mikroElektronika txt sub mikr Ext 5 strncat txt txt sub 4 routine appends first 4 characters from the string txt sub at the place of first null character in the txt string 589 MikroElektronika mikoPascal PRO for PIC32 strncpy Prototype procedure strncpy var sl s2 string size word Description The function copies at most size characters from the string s2 to the string s1 If s2 contains fewer characters than size s1 is padded out with null characters up to the total length of the size characters txt mikroElektronika txt sub t mikr strnopy txt txt sub 4 copies first 4 characters form the string txt sub DO TERE strspn Prototype function strspn var sl s2 string word Description The function searches the string s1 for characters not found in the s2 string The function returns the index of first character located in s1 that does not match a character in s2 If the first charact
59. v Check Spelling Comment style e 44 Eh single line Advanced Editor Options T Open options dialog Code Folding V Enable code folding V Show Ident Guides Tools J Output mikroPascal PRO for PIC32 Auto Save Auto Save is a function which saves an opened project automatically helping to reduce the risk of data loss in case of a crash or freeze Autosaving is done in time intervals defined by the user Highlighter Highlighting is a convenient feature for spotting brackets which notate begin or end of a routine by making them visually distinct Spelling The Spell Checker underlines unknown objects in the code so they can be easily noticed and corrected before compiling your project Select Tools Options from the drop down menu or click the Show Options Icon i and then select the Spell Checker Tab Comment Style Code Editor has a feature to change the comment style to either single line or multi line Commenting or uncommenting the selected code is done by a simple click of a mouse using the Comment Icon i2 and Uncomment Icon u from the Advanced Edit Toolbar Code Folding Code folding is IDE feature which allows users to selectively hide and display sections of a source file In this way it is easier to manage large regions of code within one window while still viewing only those subsections of the code that are relevant during a particular editing session While typing the c
60. var buf array 4 of word Note Program flow diagrams are indexed according to the sequence of execution procedure func33 if QGeeesesatesea begin Delay ms 1000 hi if nop gs longjmp buf 2 1 Umek2 iile 2 2 2 gt nop P ff end 7 4 P procedure func fi deese begin JJ PORTB 2 3 Er if setjmp buf 2 then 3 lt PORTB 1 Pp Mee else func33 l 2 25e9e gt e l 4 lt end jf Sese gt as begin fi ADPCFG OxFFFF rd ff PORTB 0 TRISB 0 i 7 nop as une 7 ff o qee gt it nop i Sasss Delay ms 1000 PORTB OxFFFF end MikroElektronika 984 mikroPascal PRO for PIC32 Sprint Library mikroPascal PRO for PIC32 includes a library which automatizes string related tasks Library Dependency Tree Functions memchr memcmp memcpy memmove memset strcat strcat2 strchr strcmp strcpy strlen strncat strncat2 strncpy strspn strncmp strstr strcspn strpbrk strrchr Itrim rtrim strappendpre strappendsuf length 585 MikroElektronika mikoPascal PRO for PIC32 memchr Prototype function memchr p byte ch byte n word word Description The function locates the first occurrence of the word ch in the initial n words of memory area starting at the address p The function returns the offset of this occ
61. 158 au 6 gwlIpAddr 1 gwlIpAddr 2 gwIpAddr 3 dnsIpAddr 0 dnsIpAddr 1 dnsIpAddr 2 dnsIpAddr 3 192 168 20 100 2555 2553 255 OF Ethernet confNetwork ipMask gwIpAddr dnsIpAddr set network configuration parameters The above mentioned network parameters should be set by this routine only if DHCP module is not used Otherwise DHCP will override these settings MikroElektronika mikoPascal PRO for PIC32 SPI Ethernet arpResolve Prototype function SPI Ethernet arpResolve var ip array 4 of byte tmax byte word Description This is ARP module routine It sends an ARP request for given IP address and waits for ARP reply If the requested IP address was resolved an ARP cash entry is used for storing the configuration ARP cash can store up to 3 entries For ARP cash structure refer to eth enc28j60LibDef h header file in the compiler s Uses folder Parameters ip IP address to be resolved tmax time in seconds to wait for an reply MAC address behind the IP address the requested IP address was resolved 0 otherwise Ethernet module has to be initialized See SPI Ethernet Init IpAddr array 4 of byte IP address 1025 168 1 i t arpResolve IpAddr 5 get MAC address behind the above IP address wait 5 secs for the response The Ethernet services are not stopped while this routine waits for ARP reply The incoming pac
62. MikroElektronika 264 mikroPascal PRO for PIC32 Cf Fat Assign Prototype function Cf Fat Assign var filename array 12 of char file cre attr byte word Description Assigns file for file operations read write delete All subsequent file operations will be applied over the assigned file Parameters filename name of the file that should be assigned for file operations The file name should be in DOS 8 3 file name extension format The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does not have to take care of that The file name and extension are case insensitive The library will convert them to proper case automatically so the user does not have to take care of that Also in order to keep backward compatibility with the first version of this library file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between the file name and extension i e MIKROELETXT gt MIKROELE TXT In this case the last 3 characters of the string are considered to be file extension file cre attr file creation and attributes flags Each bit corresponds to the appropriate file attribute Read Only zT Device internal use only never found on disk File creation flag If the file does not exist and this flag is set a new file with specified name will be creat
63. Prototype procedure Lcd Out Cp var text string Prints text on Lcd at current cursor position Both string variables and literals can be passed as a text text text to be written The Lcd module needs to be initialized See Lcd Init routine Write text Here at current cursor position Led Out Cp Here Lcd Chr SENS procedure Lcd Chr row column word out char byte Prints character on Lcd at specified position Both variables and literals can be passed as a character Parameters row writing position row number column Writing position column number out char character to be written The Lcd module needs to be initialized See Lcd Init routine ri d ide character i at row 2 column 3 Lcd Chr 3y are MikroElektronika 320 mikroPascal PRO for PIC32 Lcd Chr Cp Description Prints character on Lcd at current cursor position Both variables and literals can be passed as a character Parameters out char character to be written Nothing Requires The Lcd module needs to be initialized See Lcd Init routine Write character e at current cursor position Led Chr Cp e None Lcd Cmd Prototype procedure Lcd Cmd out char byte Description Sends command to Lcd Parameters out char command to be sent Nothing Requires The Lcd module needs to be initialized See Lcd Init table Clear Lcd display Lcd Cmd LCD CLEAR Predefined constants can be
64. SPI T6963C Partiallmage 487 SPI T6963C sprite 488 SPI T6963C set cursor 488 SPI T6963C clearBit 488 SPI T6963C setBit 489 SPI T6963C negBit 489 SPI T6963C displayGrPanel 489 SPI T6963C displayTxtPanel 490 SPI T6963C setGrPanel 490 SPI T6963C setTxtPanel 490 SPI T6963C panelFill 491 SPI T6963C grFill 491 SPI T6963C txtFill 491 SPI T6963C cursor height 492 SPI T6963C graphics 492 SPI T6963C text 492 SPI T6963C cursor 493 SPI T6963C cursor blink 493 Library Example 493 HW Connection 499 T6963C Graphic Lcd Library 500 Library Dependency Tree 500 External dependencies of T6963C Graphic Lcd Library 501 Library Routines 502 T6963C init 503 T6963C writeData 504 T6963C writeCommand 505 T6963C setPtr 505 T6963C waitReady 505 T6963C fill 506 T6963C dot 506 T6963C write char 507 T6963C write text 508 T6963C line 508 T6963C rectangle 509 T6963C rectangle round edges 509 T6963C rectangle round edges fill 510 T6963C box 510 T6963C circle 510 T6963C circle fill 511 T6963C image 511 MikroElektronika 20 mikroPascal PRO for PIC32 T6963C Partiallmage 512 T6963C sprite 512 T6963C set cursor 513 T6963C displayGrPanel 513 T6963C displayTxtPanel 513 T6963C setGrPanel 514 T6963C setTxtPanel 514 T6963C panelFill 514 T6963C grFill 515 T6963C txtFill 515 T6963C cursor height 515 T6963C graphics 516 T6963C text 516 T6963C cursor 516 T6963C cursor blink 517 Library Example 517 HW Connection 524 TFT Library 525 External dependencies
65. TY Help Toolbar provides access to information on using and registering compilers Open Help file EM How To Register Related topics Keyboard shortcuts Integrated Tools MikroElektronika 80 mikroPascal PRO for PIC32 Customizing IDE Layout Docking Windows You can increase the viewing and editing space for code depending on how you arrange the windows in the IDE Step 1 Click the window you want to dock to give it focus Project Manager or B Sources E Lcd mpas Binaries y Project level defines Image Files EEPROM Files 7 Active Comments Files E 7j Output Files ES Lcd hex 25 Lcd asm Other Files Step 2 Drag the tool window from its current location A guide diamond appears The four arrows of the diamond point towards the four edges of the IDE m 81 MikroElektronika mikoPascal PRO for PIC32 Step 3 Move the pointer over the corresponding portion of the guide diamond An outline of the window appears in the designated area E an cu Step 4 To dock the window in the position indicated release the mouse button Tip To move a dockable window without snapping it into place press CTRL while dragging it Saving Layout Once you have a window layout that you like you can save the layout by typing the name for the layout and pressing the Save Layout Icon ik To set the layout select the desired layout from the layout drop down list and click the S
66. The Multi Media Card MMC is a Flash memory card standard MMC cards are currently available in sizes up to and including 32 GB and are used in cellular phones digital audio players digital cameras and PDAs mikroPascal PRO for PIC32 provides a library for accessing data on Multi Media Card via SPI communication This library also supports SD Secure Digital and high capacity SDHC Secure Digital High Capacity memory cards Secure Digital Card Secure Digital SD is a Flash memory card standard based on the older Multi Media Card MMC format SD cards are currently available in sizes of up to and including 2 GB and are used in digital cameras digital camcorders handheld computers media players mobile phones GPS receivers video games and PDAs Secure Digital High Capacity Card SDHC Secure Digital High Capacity SD 2 0 is an extension of the SD standard which increases card s storage capacity up to 32 GB by using sector addressing instead of byte addressing in the previous SD standard SDHC cards share the same physical and electrical form factor as older SD 1 x cards allowing SDHC devices to support both newer SDHC cards and older SD cards The current standard limits the maximum capacity of an SDHC card to 32 GB Important Routines for file handling can be used only with FAT16 file system Library functions create and read files from the root directory only Library functions populate both FAT1 and FAT2 tables when
67. Watch from the View drop down menu The Watch Values Window displays variables and registers of the MCU with their addresses and values Values are updated along with the code execution Recently changed items are coloured red There are two ways to add variable register into the watch list by its real name variable s name in program code Just select wanted variable register from Select variable from list drop down menu and click the d Add button by its name ID assembly variable name Simply type name ID of the variable register you want to display into Search for variable by assemby name box and click the a Add button 121 MikroElektronika mikoPascal PRO for PIC32 Also it is possible to add all variables in the Watch Values Window by clicking de Add All button To remove a variable from the Watch Values Window just select the variable that you want to remove and then click the 96 Remove button or press the Delete key It is possible to remove all variables from the Watch Values Window by clicking k Remove All button You can also expand collapse complex variables i e struct type variables strings etc by clicking the appropriate button or beside variable name Watch Yalues 2E sh Bh Select variable from list WREGl PC 0x00028E 9655 99 ms Double clicking a variable or clicking the amp Properties button opens the Edit Value window in which you can assign a new value to th
68. mikroPascal PRO for PIC32 RS 485 Library RS 485 is a multipoint communication which allows multiple devices to be connected to a single bus mikroPascal PRO for PIC32 provides a set of library routines for comfortable work with RS485 system using Master Slave architecture Master and Slave devices interchange packets of information Each of these packets contains synchronization bytes CRC byte address byte and the data Each Slave has unique address and receives only packets addressed to it The Slave can never initiate communication It is the user s responsibility to ensure that only one device transmits via 485 bus at a time The RS 485 routines require the UART module Pins of UART need to be attached to RS 485 interface transceiver such as LTC485 or similar see schematic at the bottom of this page Library constants START byte value 150 STOP byte value 169 Address 50 is the broadcast address for all Slaves packets containing address 50 will be received by all Slaves except the Slaves with addresses 150 and 169 Important The library uses the UART module for communication The user must initialize the appropriate UART module before using the RS 485 Library For MCUs with multiple UART modules it is possible to initialize them and then switch by using the UART Set Active routine Library Dependency Tree Rs485 uaRT External dependencies of RS 485 Library The following variable
69. mikroPascal PRO for PIC32 TFT_RGBToColor16bit Prototype function TFT RGBToColorl bit rgb red rgb green rgb blue byte word Returns a color value in the following bit order 5 bits red 6 bits green and 5 bits blue color Description Converts 5 6 5 RGB format into true color format Parameters rgb _ red red component of the image rgb green green component of the image rgb blue blue component of the image TFT module needs to be initialized See the TFT_Init routine Example colorl6 TFT Image Jpeg 150 193 65 TFT Color16bitTOoRGB Prototype procedure TFT Colorl6bitToRGB color word rgb red rgb green rgb blue byte Description Converts true color into 5 6 5 RGB format Parameters color true color to be converted rgb red red component of the input color rgb green green component of the input color rgb blue blue component of the input color TFT module needs to be initialized See the TFT Init routine TFT Colorl 6 bitToRGB start color red_ start green start blue start 539 MikroElektronika mikoPascal PRO for PIC32 HW Connection TFT 320x240 display Bee LEE MI0283QT2 TFT HW connection MikroElektronika 540 mikroPascal PRO for PIC32 Touch Panel Library The mikroPascal PRO for PIC32 provides a library for working with Touch Panel Library Dependency Tree Touch Panel ADC External dependen
70. mikroPascal PRO for PIC32 Specifics 135 Predefined Globals and Constants 136 Predefined project level defines 136 Accessing Individual Bits 137 sbit type 138 at keyword 139 bit type 139 Interrupts 140 MikroElektronika mikoPascal PRO for PIC32 Configuring Interrupts 140 Single Vector Mode 140 Multi Vector Mode 140 Interrupt Priorities 141 Interrupts and Register Sets 141 Register Set Selection in Single Vector Mode 141 Interrupts and Register Sets 141 Interrupt Coding Requirements 141 Interrupt Service Routine 141 Function Calls from Interrupt 142 Interrupt Example 143 Linker Directives 144 Directive absolute 144 Directive org 144 Directive orgall 145 Built in Routines 146 Lo 147 Hi 147 Higher 148 Highest 148 LoWord 149 HiWord 149 Inc 150 Dec 150 Chr 150 Ord 151 SetBit 151 ClearBit 151 TestBit 152 Delay_us 152 Delay_ms 152 VDelay_ms 153 VDelay_advanced_ms 153 Delay Cyc 153 Delay Cyc Long 154 Clock kHz 154 Clock MHz 154 Get Fosc kHz 155 Get Fosc Per Cyc 155 Reset 155 ClrWat 156 DisableContextSaving 156 SetFuncCall 157 SetOrg 157 DoGetDateTime 158 GetVersion 158 MikroElektronika 6 mikroPascal PRO for PIC32 KVAO TO KVA1 158 KVA1 TO KVAO 159 KVA TO PA 159 PA TO KVAO 159 PA TO KVA1 159 CPO GET 160 CPO SET 160 Enablelnterrupts 160 Disablelnterrupts 161 Code Optimization 163 Constant folding 163 Constant propagation 163 Copy propagation 163
71. size or by address Routine List E3 Sort By Name Sort By Line Move_Delay Cishift Text Left Cishift Text Right Project Manager Project Manager is IDE feature which allows the users to manage multiple projects Several projects which together make project group may be open at the same time Only one of them may be active at the moment Setting project in active mode is performed by double clicking the desired project in the Project Manager which will result in bolding the project s name Also the name of the currently active project will be diplayed in the Program Manager window title alongside with the number of projects in project group Project Manager 1 1 Lcd mpp32 c Progr X 5 Mey SSS a ct E gs Lcd mpp32 B Sources Z Lcd mpas Binaries y Project level defines 7j Image Files j EEPROM Files E Active Comments Files Output Files 23 Lcd hex 23 Lcd asm E Other Files MikroElektronika 58 mikroPascal PRO for PIC32 Following options are available in the Project Manager icon Description EIC TN EIN E Remove project from the project group Add file to the active project Remove selected file from the project E Build the active project Run mikroElektronika s Flash programmer For details about adding and removing files from project see Add Remove Files from Project Related topics Project Settings Project Menu Options File Menu Opti
72. so interrupts need to be disabled when using it MikroElektronika mikoPascal PRO for PIC32 Library Example This example demonstrates simple data exchange via software UART If MCU is connected to the PC you can test the example from the mikroPascal PRO for PIC32 USART communication terminal launch it from the drop down menu Tools gt USART Terminal or simply click the USART Terminal Icon E3i Copy Code To Clipboard program Soft UART var error byte counter byte read byte Auxiliary variables begin CHECON 0x32 ADIPCFG OxFFFF Configure AN pins as digital I O TRISB 0x00 Set PORTB as output error signalization PORTB 0 No error error Soft UART Init PORTF 2 8 56000 0 Initialize Soft UART at 56000 bps if error 0 then begin PORTB error Signalize Init error while TRUE do nop Stop program end Delay ms 100 for counter z downto A do Send bytes from z downto A begin Soft UART Write counter Delay ms 100 end while TRUE do Endless loop begin byte read Soft UART Read error Read byte then test error flag if error 0 then If error was detected PORTB error JL signal it on PORTB else Soft UART Write byte read If error was not detected return byte read end end MikroElektronika mikroPascal PRO for PIC32 Sound Library The mikroPascal PRO for PIC32 provides a Sound Library to su
73. ums Nothing OOOO Pompe roseueias T6963C txtEi11 0 T6963C cursor height Prototype procedure 7T6963C cursor height n word Parameters n cursor height Valid values 0 Returns Wang T Example T6963c_cursor height OOOO etes Nee OOOO 913 MikroElektronika mikoPascal PRO for PIC32 T6963C_graphics Prototype procedure T6963C graphics n word Enable disable graphic displaying Parameters n graphic enable disable parameter Valid values 0 disable graphic dispaying and 1 enable graphic displaying Toshiba Glcd module needs to be initialized See the T6963C init routine enable graphic displaying T6963C graphics 1 T6963C text Parameters n on off parameter Valid values 0 disable text displaying and 1 enable text displaying ems Ning Cd ume faee rentan d T6963C text l Nes Noe SCS T6963C_cursor RMums Ning OOS SS Toshiba Glcd module needs to be initialized See the T6963C init routine set cursor on T6963C cursor 1 Notes Nowe OOS MikroElektronika 514 mikroPascal PRO for PIC32 T6963C cursor blink Prototype procedure T6963C cursor blink n word Enable disable cursor blinking Parameters n cursor blinking enable disable parameter Valid values 0 disable cursor blinking and 1 enable cursor a Pine Toshiba Glcd module needs to be initialized See the T6963C init routine enable cursor blinking T6963C curso
74. y0 to x1 y1 Parameters x0 X coordinate of the line start y0 y coordinate of the line end x1 X coordinate of the line start y1 y coordinate of the line end pcolor color parameter Valid values S1D13700 BLACK Black color 1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine ame S1D13700 Line 0 239 127 S1D13700 WHITE S1D13700 H Line Prototype procedure 1D13700 H Line x start x end y pos word color byte Nothing Description Draws a horizontal line Parameters x start x coordinate of the line start x end x coordinate of the line end y pos line position on the y axis pcolor color parameter Valid values S 1D13700 BLACK Black color S1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine S1D13700 Line 0 0 239 127 S1D13700 WHITE 281 MikroElektronika mikoPascal PRO for PIC32 S1D13700 V Line Prototype procedure S1D13700 V Line y start y end x pos word color byte Nothing Description Draws a horizontal line Parameters y start y coordinate of the line start y end y coordinate of the line end x pos line position on the x axis pcolor color parameter Valid values 1D13700 BLACK Black color S1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine S1D13700 Line 0 0 239 12
75. 00000000 C I MikroElektronika 172 mikroPascal PRO for PIC32 Actual voltage levels on MCU pins are relevant MODIFY Data is modified to set the RBO bit WRITE PORTB is written with the modified data The output driver for RBO turns on and the Modify value capacitor starts to charge Write modified value Discharged 00000000 C capacitor 0850000 To Oe The second line PORTB B1 1 will be decoded like in this way READ PORTB is read STORE Because the capacitor is still charging the voltage at RBO is still low and reads as a 0 since we are reading from the pins directly not from the PORTB register Store read Value we didn t expect here value but physically still correct one STO CIA TERNAL REGISTER Read from pins Charging 00000000 c capacitor Charging I 00000000 TC Capacitor Actual voltage levels on MCU pins are relevant MODIFY Data is modified to set the bit WRITE PORTB is written with the new data The output driver for RB1 turns on but the Modify value driver for RBO turns back off INTERNAL i REGISTER baneanenemnemeanenemneneneenennenennenennanennanemnenennanennand Write modified value anamanna 0 gt H Charging l capacitor Discharging 00000010 Decne 00000000 173 MikroElektronika mikoPascal PRO for PIC32 To correct the problem in the code insert a delay after each PORTB Bx
76. 0x40 Device internal use only never found on disk File creation flag If file does not exist and this flag is set a new file with specified name will be created 1 if file already exists or file does not exist but a new file is created 0 if file does not exist and no new file is created MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init create file with archive attribut if it does not already exist Mme Fat Assign MIKROO007 TXT 0xA0 Notes Long File Names LFN are not supported 333 MikroElektronika mikoPascal PRO for PIC32 Mmc_Fat_Reset ee procedure Mmc Fat Reset var size dword Procedure resets the file pointer moves it to the start of the file of the assigned file so that the file can be read Parameters size buffer to store file size to After file has been opened for reading its size is returned through this parameter Requires MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init The file must be previously assigned See Mmc_Fat_Assign var size dword Mmc Fat Reset size Mmc_Fat_Read Prototype procedure Mmc Fat Read var bdata byte Description Reads a byte from the currently assigned file opened for reading Upon function execution file pointers will be set to the next character in the file bdata buffer to store read byte to Upon this function execution read byte is returned thro
77. 2 it will double the image TFT module needs to be initialized See the TFT Init routine Example TT tage 0 0 image Dg 0 1 931 MikroElektronika mikoPascal PRO for PIC32 TFT Partial Image Prototype procedure TFT Partial Image left top width height word image const far byte stretch byte Nothing Description Displays a partial area of the image on a desired location Parameters left left coordinate of the image top top coordinate of the image width desired image width height desired image height image image to be displayed Bitmap array is located in code memory stretch stretches image by a given factor if 2 it will double the image TFT module needs to be initialized See the TFT Init routine Draws a 10x15 part of the image starting from the upper left corner on the coordinate 10 12 TFT Partiallmage 10 12 10 15 Gimage 1 TFT Image Jpeg Prototype function TFT Image Jpeg left top word image const far byte byte 0 if image is loaded and displayed successfully 1 if error occured Description Displays a JPEG image on a desired location Parameters left left coordinate of the image top top coordinate of the image image image to be displayed Bitmap array is located in code memory TFT module needs to be initialized See the TFT Init routine Example TFr mage spego 0 image CS MikroElektronika 538
78. 31 30 31 185 MikroElektronika mikoPascal PRO for PIC32 Semicolon Semicolon is a statement terminator Every statement in Pascal must be terminated with a semicolon The exceptions are the last outer most end statement in the program which is terminated with a dot and the last statement before end which doesn t need to be terminated with a semicolon For more information see Statements Colon Colon is used in declarations to separate identifier list from type identifier For example var i j t Byte k word In the program use the colon to indicate a labeled statement start nop goto start For more information refer to Labels Dot Dot indicates an access to a field of a record For example person surname Smith For more information refer to Records Dot is a necessary part of floating point literals Also dot can be used for accessing individual bits of registers in mikroPascal MikroElektronika 186 mikroPascal PRO for PIC32 Program Organization mikroPascal PRO for PIC32 imposes strict program organization Below you can find models for writing legible and organized source files For more information on file inclusion and scope refer to Units and Scope and Visibility Organization of Main Unit Basically the main source file has two sections declaration and program body Declarations should be in their proper place in the code organized in an orderly manner Ot
79. 4 10 minutes and 0x0F Transform months hours hours and OxF0 shr 4 10 hours and Ox0F Transform hours year day and 0xC0 shr 6 Transform year day day and 0x30 shr 4 10 day and 0x0F Transform day month month and 0x10 shr 4 10 month and OxOF Transform month end aed he ee E ES Output values to LCD procedure Display Time begin Lcd Chr 1 6 day 10 t 48 Print tens digit of day variable Lcd Chr 1 7 day mod 10 48 Print oness digit of day variable Lcd Chr 1 9 month 10 48 Lcd Chr 1 10 month mod 10 48 Lcd Chr 1 15 year 49 Print year vaiable 1 start from year 2011 Lcd Chr 2 6 hours 10 t 48 Lcd Chr 2 7 hours mod 10 t 48 Lcd Chr 2 9 minutes 10 48 Lcd Chr 2 10 minutes mod 10 48 Lcd Chr 2 12 seconds 10 48 Lcd Chr 2 13 seconds mod 10 48 end jf Performs project wide init procedure Init Main begin CHECON 0x30 ADIPCFG OxFFFF Initialize AN pins as digital Soft I2C Init Initialize Soft I2C communication Lcd Init Zt Initialize LCD Lcd Cmd LCD CLEAR Clear LCD display Lcd Cmd LCD CURSOR OFF Turn cursor off Lcd Out 1 1 Date Prepare and output static text on LCD Lcd Chr 1 8 Led Chr 1 11 2 Led Out 2 1 Time Led Chr 2 8 o Ji Lod Chr 2 Uys 7 Lcd Out 1 12 201 end qpee
80. 5 exceeds byte range Explicit Typecasting Any expression can be evaluated at specific level by using explicit typecasting Having in mind previous example in order to get same calculation in conditional and assignment expression the following should be done if word b 5 then word level Statements Statements define algorithmic actions within a program Each statement needs to be terminated with a semicolon In the absence of specific jump and selection statements statements are executed sequentially in the order of appearance in the source code The most simple statements are assignments procedure calls and jump statements These can be combined to form loops branches and other structured statements Refer to Assignment Statements Compound Statements Blocks Conditional Statements Iteration Statements Loops Jump Statements asm Statement MikroElektronika 222 mikroPascal PRO for PIC32 Assignment Statements Assignment statements have the following form variable expression The statement evaluates expression and assigns its value to variable All the rules of implicit conversion are applied Variable can be any declared variable or array element and expression can be any expression Do not confuse the assignment with relational operator which tests for equality Also note that although similar the construction is not related to the declaration of constants Compound Statemen
81. Board or similar hardware See connection example at the bottom of this page set the appropriate filter mask and message type value CANSPISetOperationMode CANSPI MODE CONFIG OxFF set CONFIGURATION mode CANSPI1 module must be in config mode for mask settings Set all B1 mask bits to 1 all filtered bits are relevant Note that 1 is just a cheaper way to write OxFFFFFFFF Complement will do the trick and fill it up with ones CANSPISetMask CANSPI MASK B1 e CANSPI CONFIG MATCH MSG TYPE and CANSPI CONFIG XTD MSG MikroElektronika 246 mikroPascal PRO for PIC32 CANSPISetFilter Prototype procedure CANSPISetFilter CAN_FILTE as byte val longint CANSPI CONFIG FLAGS as byte Configures message filter The parameter va1ue is bit adjusted to the appropriate filter registers Parameters CANSPI FILTER CAN module filter number Valid values CANSPI FILTER constants See CANSPI FILTER constants val filter register value This value is bit adjusted to appropriate filter registers CANSPI CONFIG FLAGS selects type of message to filter Valid values CANSPI CONFIG STD MSG and CANSPI CONFIG XTD MSG See CANSPI CONFIG FLAGS constants Requires The CANSPI module must be in Config mode otherwise the function will be ignored See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s
82. Byte 352 Expander Read PortA 352 Expander Read PortB 353 Expander Read PortAB 353 Expander Write PortA 354 Expander Write PortB 354 Expander Write PortAB 355 Expander Set DirectionPortA 355 Expander Set DirectionPortB 356 Expander Set DirectionPortAB 356 Expander Set PullUpsPortA 356 Expander Set PullUpsPortB 357 Expander Set PullUpsPortAB 357 Library Example 358 HW Connection 359 PS 2 Library 360 External dependencies of PS 2 Library 360 Library Routines 360 Ps2 Config 361 Ps2 Key Read 361 Special Function Keys 362 Library Example 363 HW Connection 364 PWM Library 364 Library Routines 364 PWM Init 365 15 MikroElektronika mikoPascal PRO for PIC32 PWM Init Advanced 365 PWM Set Duty 366 PWM Start 366 PWM Stop 366 Library Example 367 HW Connection 368 RS 485 Library 369 Library Dependency Tree 369 External dependencies of RS 485 Library 369 Library Routines 370 RS485Master_Init 370 RS485Master_Receive 371 RS485Master_Send 371 RS485Slave Init 372 RS485Slave Receive 373 RS485Slave Send 373 Library Example 374 HW Connection 377 Message format and CRC calculations 378 Software C Library 379 External dependencies of Software 1 C Library 379 Library Routines 379 Soft_I2C_Init 380 Soft_I2C_Start 380 Soft_I2C_Read 381 Soft I2C Write 381 Soft I2C Stop 381 Soft I2C Break 382 Library Example 383 Software SPI Library 385 External dependencies of Software SPI Library 385 Library Routines 385 Soft SPI Init 386 So
83. Data Direction sbit at sfr external Direction of the PS 2 Data pin TRISBO bit var PS2 Clock Direction sbit var PS2 Clock Direction sbit at ste ertora Direction of the PS 2 Clock pin TRISB1 bit Library Routines Ps2 Config Ps2 Key Read MikroElektronika 398 mikroPascal PRO for PIC32 Ps2 Config ums Noi Requires Global variables PS2 Data Data signal line PS2 Clock Clock signal line PS2 Data Direction Direction of the Data pin PS2 Clock Direction Direction of the Clock pin must be defined before using this function PS2 pinout definition var PS2 Data sbit at RBO bit var PS2 Clock sbit at RBI bit var PS2 Data Direction sbit at TRISBO bit var PS2 Clock Direction sbit at TRISB1 bit End of PS2 pinout definition Init PS 2 Keyboard Ps2 Key Read Prototype function Ps2 Key Read var value byte var special byte var pressed byte word The function retrieves information on key pressed Parameters value holds the value of the key pressed For characters numerals punctuation marks and space value will store the appropriate ASCII code Routine recognizes the function of Shift and Caps Lock and behaves appropriately For special function keys see Special Function Keys Table special is a flag for special function keys F1 Enter Esc etc If key pressed is one of these special Will be set to 1 otherwise O pressed is set to 1 i
84. Description This is MAC module routine It stores requested number of const bytes into xNC28360 RAM starting from current ENC2860 write pointer EWRPT location Parameters ptr const buffer containing bytes to be written into ENC28760 RAM n number of bytes to be written Ethernet module has to be initialized See SPI Ethernet Init const buffer array 17 of byte buffer mikroElektronika SPI Ethernet putConstBytes buffer 16 put a const array into ENC28J60 buffer MikroElektronika 40 mikroPascal PRO for PIC32 SPI Ethernet putString Prototype function SPI Ethernet putString ptr byte word Description This is MAC module routine It stores whole string excluding null termination into ENC28760 RAM starting from current ENC28J60 write pointer EWRPT location Parameters ptr string to be written into ENC28760 RAM Number of bytes written into ENC28760 RAM Requires Ethernet module has to be initialized See SPI Ethernet Init var buffer string 16 buffer mikroElektronika SPI Ethernet putString buffer put a RAM string into ENC28J60 buffer SPI Ethernet putConstString Prototype function SPI Ethernet putConstString const ptr byte word Description This is MAC module routine It stores whole const string excluding null termination into ENC28760 RAM starting from current ENC28760 write pointer EWRP
85. Draws a filled rounded edge rectangle on Glcd with color Parameters x upper left x coordinate of the upper left rectangle corner Valid values 0 127 y upper left y coordinate of the upper left rectangle corner Valid values 0 63 x bottom right x coordinate of the lower right rectangle corner Valid values 0 127 y bottom right y coordinate of the lower right rectangle corner Valid values 0 63 round radius radius of the rounded edge color color parameter Valid values 0 2 The parameter color determines the color of the rectangle border 0 white 1 black and 2 inverts each dot Nothing Requires Glcd needs to be initialized see Glcd Init routine Draws a filled rounded edge rectangle between dots 5 5 and 40 40 with the radius of 12 Glcd Rectangle Round Edges Fill 5 5 Glcd Box Prototype procedure Glcd Box x upper left y upper left x bottom right y bottom right color byte Description Draws a box on Glcd Parameters Parameters x upper left x coordinate of the upper left box corner Valid values 0 127 y upper left y coordinate of the upper left box corner Valid values 0 63 x bottom right x coordinate of the lower right box corner Valid values 0 127 y bottom right y coordinate of the lower right box corner Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the color of the box fill O white 1 black and 2 inverts each d
86. E XOR 481 MikroElektronika mikoPascal PRO for PIC32 SPI T6963C line Prototype procedure SPI T6963C line x0 yO xl yl integer pcolor byte Draws a line from x0 y0 to x1 y1 Parameters x0 x coordinate of the line start y0 y coordinate of the line end x1 x coordinate of the line start yl y coordinate of the line end pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE mre ee o ooo EGLELL Example SPI T6963C line 0 0 239 127 SPI T6963C WHITE eT SPI T6963C rectangle Prototype procedure SPI T6963C rectangle x0 yO xl yl integer pcolor byte Draws a rectangle on Glcd Parameters x0 x coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T69063C rectangle 20 20 219 107 SPI T6963C WHITE MikroElektronika 482 mikroPascal PRO for PIC32 SPI T6963C rectangle round edges Prototype procedure SPI T6963C rectangle round edges x0 qnl yO integer xl integer yl integer radius integer pcolor byte Draws a rounded edge rectangle on Glcd Parameters x0 x coordinate of the up
87. Editor ASCII Chart EEPROM Editor Graphic Lcd Bitmap Editor HID Terminal Interrupt Assistant Lcd Custom Character Seven Segment Editor UDP Terminal USART Terminal Active Comments New Active Comment Renaming Active Comment Deleting Active Comment Export Project Jump To Interrupt Regular Expressions Introduction Simple matches Escape sequences Character classes Metacharacters Metacharacters Line separators Metacharacters Predefined classes Metacharacters Word boundaries 109 MikroElektronika mikroPascal PRO for PIC32 Metacharacters Iterators 109 Metacharacters Alternatives 110 Metacharacters Subexpressions 110 Metacharacters Backreferences 110 Keyboard Shortcuts 111 CHAPTER 3 113 mikroPascal PRO for PIC32 Command Line Options 113 CHAPTER 4 115 mikrolCD In Circuit Debugger 115 Introduction 115 mikroICD Debugger Options 117 Debugger Options 117 mikrolCD Debugger Example 118 mikrolCD Debugger Windows 122 Debug Windows 122 Breakpoints Window 122 Watch Values Window 122 RAM Window 124 Stopwatch Window 124 EEPROM Watch Window 125 Code Watch Window 126 CHAPTER 5 127 Software Simulator Overview 127 Software Simulator 128 Software Simulator Debug Windows 129 Debug Windows 129 Breakpoints Window 129 Watch Values Window 129 RAM Window 131 Stopwatch Window 131 EEPROM Watch Window 132 Code Watch Window 133 Software Simulator Debugger Options 134 Debugger Options 134 CHAPTER 6 135
88. Editor or by clicking the Active Comment Editor Icon A from Tools toolbar Active Comments Editor Enter comment name activeComment Active Comment Actions New Rename Properties Attributes Url Image File J Events OnLeftClick Alt None OnRightClick OnDblClick OnMouseOver Add Image To Project Add File To Project MikroElektronika 96 mikroPascal PRO for PIC32 ASCII Chart The ASCII Chart is a handy tool particularly useful when working with Lcd display You can launch it from the drop down menu Tools gt ASCII chart or by clicking the View ASCII Chart Icon from Tools toolbar meme Ascii Chart NUL SOH STX ETX EOT ENQ ACK BEL BS LF VT FF 0 1 2 3 4 5 6 7 9 10 11 12 DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS 8 19 20 21 22 23 24 25 26 27 28 5 IE Ere 36 37 38 39 40 42 43 4 6 78 2 54 55 56 F 103 104 105 87 MikroElektronika mikoPascal PRO for PIC32 EEPROM Editor The EEPROM Editor is used for manipulating MCU s EEPROM memory You can launch it from the drop down menu Tools EEPROM Editor When you run mikroElektronika programmer software from mikroPascal PRO for PIC32 IDE project name hex file will be loaded automatically while i hex file must be loaded manually MikroElektronika EEPROM Editor Addr 0000 0010 0020 0030 0040 0050 0060 0070 0080 0090 Yyyy
89. Examples int 8 10 matches strings which contain 8 9 or 10 instances of the int routi 0 9 a e matches routi0e routile routine routinne routinnne etc Metacharacters Backreferences Metacharacters 1 through 9 are interpreted as backreferences matches previously matched subexpression Examples N14 matches aaaa and cc 1 matches abab and 123123 d 1 matches 13 in double quotes or 4 in single quotes or 77 without quotes etc MikroElektronika 108 mikroPascal PRO for PIC32 Keyboard Shortcuts Below is a complete list of keyboard shortcuts available in mikroPascal PRO for PIC32 IDE J IDE Shortcuts F ep amo oem Oe Ctrl Shift F11 F F3 Shift F3 Alt F3 Ctrl A Ctrl C Ctrl F Ctrl R Ctrl P Ctrl S Ctrl Shift S Ctrl V Ctrl X Ctrl Y Ctrl Z Ctrl Shift Z Ctrl Shift number Ctrl Alt Select oa mikrolCD Debugger and Software Simulator Shortcuts Jump To Interrupt 109 MikroElektronika mikoPascal PRO for PIC32 Ctri F5 Add to Watch List Ctrl F8 Step Out Shift F5 Open Watch Window Alt D Disassembly View Ctrl Shift A Show Advanced Breakpoints MikroElektronika 110 mikroPa scal PRO for PIC32 HAPTER 3 mikroPascal PRO for PIC32 Command Line Options Usage mPPIC32 exe lt opts gt lt opts gt lt infile gt lt op
90. FIlI 457 SPI Glcd Set Font 458 MikroElektronika 18 mikroPascal PRO for PIC32 SPI Glcd Write Char 459 SPI Glcd Write Text 459 SPI Glcd Image 460 SPI Glcd Partiallmage 460 Library Example 461 HW Connection 463 SPI Lcd Library 464 Library Dependency Tree 464 External dependencies of SPI Lcd Library 464 Library Routines 464 SPI Lcd Config 465 SPI Lcd Out 465 SPI Lcd Out Cp 466 SPI Lcd Chr 466 SPI Lcd Chr Cp 466 SPI Lcd Cmd 467 Available SPI Lcd Commands 467 Library Example 468 Default Pin Configuration 468 SPI Lcd8 8 bit interface Library 470 Library Dependency Tree 470 External dependencies of SPI Lcd Library 470 Library Routines 470 SPI Lcd8 Config 471 SPI Lcd8 Out 472 SPI Lcd8 Out Cp 472 SPI Lcd8 Chr 472 SPI Lcd8 Chr Cp 473 SPI_Lcd8_Cmd 473 Available SPI Lcd8 Commands 474 Library Example 474 SPI T6963C Graphic Lcd Library 477 Library Dependency Tree 477 External dependencies of SPI T6963C Graphic Lcd Library 477 Library Routines 478 SPI T6963C config 479 SPI T6963C writeData 480 SPI T6963C writeCommand 480 SPI T6963C setPtr 481 SPI T6963C waitReady 481 SPI T6963C fill 481 SPI T6963C dot 482 SPI T6963C write char 482 SPI T6963C write text 483 SPI T6963C line 484 SPI T6963C rectangle 484 19 MikroElektronika mikoPascal PRO for PIC32 SPI_T6963C_rectangle_round_edges 485 SPI T6963C rectangle round edges fill 485 SPI T6963C box 486 SPI T6963C circle 486 SPI T6963C circle fill 486 SPI T6963C image 487
91. Fastest way of btaining the license key it takes minutes to get it in your mailbox Recommended j O I work offline Choose this option if you are not connected to Internet You will be quided to Fill in the registration Form which you can e mail when you get online This is a slower way of getting the license key and it is intended for offline computers Request license key now If you choose work online registering method following page will be opened in your default browser F MikroElektronika guo naa DEVELOPMENT TOOLS COMPILERS BOOKS Email officeg mikroe com Home Software Activation In order to get activation key please fill in required fields Upon receiving and verifying your request we will send the license key to the e mail address you specified in the form pment Special Offers Easy Buy Publications Support Projects Download Product Name John Smith Address Invoice If you do not specify 2CO Number or invoice number then the license key request must be processed 2CO Number manually which can take longer time Email jsmitnh example com Re enter email jsmithiexample com Company Product ID Comment Distributor MikroElektronika hd Submit Related Links Products News Forums Distributors About Mikro lektronika Legal Information and Privacy Policy Product Archive Contact Us Copyright 1996 2010 MiroElektronika Al rights reserved Al trade and or services marks men
92. Fi1 d SSCS ipo Build ct Fs Build active project Rebuild All Sources Ak r Rebuild all sources in active project De Build all Projects shift F9 Build all projects Stop Build All Ctr F12 Stop building all projects 2h Build Program Ctr F11_ Build and program active project Related topics Keyboard shortcuts Project Toolbar Creating New Project Project Manager Project Settings 45 MikroElektronika mikoPascal PRO for PIC32 Run Run Menu Options Run Menu is used to debug and test compiled code on a software or harware level Start Debugger F9 54 Stop Debugger Ctrl F2 Run Pause Debugger F6 Step Into F7 Step Over F8 Step Out Ctri F8 Run To Cursor F4 4 Jump To Interrupt F2 Toggle Breakpoint F5 Clear Breakpoints Shift Ctrl F5 Disassembly mode Alt D Ra a v 8 5 Related topics Keyboard shortcuts Debug Toolbar MikroElektronika 46 mikroPascal PRO for PIC32 Tools Tools Menu Options Tools Menu contains a number of applications designed to ease the use of compiler and included library routines mE Programmer Fil Package Manager Active Comment Editor Ctrl Alt C Ascii Chart EEPROM Editor Export Code To HTML GLCD Bitmap Editor Interrupt Assistant Ctrl Alt I LCD Custom Character Seven Segment Editor UDP Terminal USART Terminal Ctri T Option
93. Font const activeFont byte aFontWidth aFontHeight byte aFontOffs byte Sets font that will be used with Glcd Write Char and Glcd Write Text routines Parameters activeFont font to be set Needs to be formatted as an array of char aFontWidth width of the font characters in dots aFontHeignt height of the font characters in dots aFontOffs number that represents difference between the mikroPascal PRO for PIC32 character set and regular ASCII set eg if A is 65 in ASCII character and A is 45 in the mikroPascal PRO for PIC32 character set aFontOffs is 20 Demo fonts supplied with the library have an offset of 32 which means that they start with space The user can use fonts given in the file Lib GLCDFonts file located in the Uses folder or create his own fonts List of supported fonts Font Glcd System3x5 Font Glcd System5x7 Font Glcd 5x7 Font Glcd Character8x7 For the sake of the backward compatibility these fonts are supported also System3x5 equivalent to Font Gl1cd System3x5 FontSystem5x7 v2 equivalent to Font G1cd System5x7 font 5x7 equivalent to Font Glcd 5x7 Character8x7 equivalent to Font Glcd Character8x7 Nothing Glcd needs to be initialized see Glcd Init routine Use the custom 5x7 font myfont which starts with space 32 Glcd Set Font amp myfont 5 7 32 Notes Ne 0L 305 MikroElektronika mikoPascal PRO for PIC32 Glcd_Write_Char Pr
94. Func3 first yellow byte monday word word Yet another function Make sure that parameters match the type definition begin result monday yellow first return something end main program begin MyPtr Funcl MyPtr now points to Funcl Sample MyPtr 1 2 3 Perform function call via pointer call Funcl the return value is 3 MyPtr Func2 MyPtr now points to Func2 Sample MyPtr 1 2 3 Perform function call via pointer call Func2 the return value is 5 MyPtr Func3 MyPtr now points to Func3 Sample MyPtr 1 2 3 Perform function call via pointer call Func3 the return value is 0 end Therefore when declaring a pointer within constant declaration block const qualifier refers to pointed object not to pointer itself MikroElektronika 206 mikroPascal PRO for PIC32 Operator The operator constructs a pointer to its operand The following rules are applied to If x is a variable x returns a pointer to x Note If variable x is of array type the operator will return pointer to it s first basic element except when the left side of the statement in which x is used is an array pointer In this case the operator will return pointer to array not to it s first basic element program example var w word ptr b byte ptr arr array 10 of byte arr array 10 of byte begin ptr b arr operator will return byte
95. Gen Enable readbuff byte writebuff byte Description Initialize the USB module of the MCU Parameters readbuff Read Buffer writebuff Write Buffer Nothing USB needs to be enabled before using this function See HID Enable Enable amp readbuff amp writebuff 565 MikroElektronika mikoPascal PRO for PIC32 Gen_Read Prototype function Gen Read readbuff byte length byte ep byte byte Generic routine that receives the specified data from the specified endpoint Parameters readbuf f Received data length The length of the data that you wish to receive ep Endpoint number you want to receive the data into Returns Returns the number of received bytes otherwise 0 USB needs to be enabled before using this function See HID_Enable peus eee 0 do Gen_Write Prototype function Gen Write writebuff byte length byte ep byte byte Sends the specified data to the specified endpoint Parameters writebuff The data that you want to send length the length of the data that you wish to send ep Endpoint number you want to send the data into Returns Returns the number of transmitted bytes otherwise 0 USB needs to be enabled before using this function See HID_Enable dll while Gen Write writebuff 64 1 MikroElektronika 566 mikroPascal PRO for PIC32 Library Example This example establishes connection with the
96. Glcd Fill OxFF Fill Glcd SPI Glcd Set Font 8Font Glcd Character8x7 8 7 32 Change font someText 8x7 Font SPI Glcd Write Text someText 5 0 2 Write string Delay2s SPI Glcd Set Font Font Glcd System3x5 3 5 32 Change font someText 3X5 CAPITALS ONLY SPI Glcd Write Text someText 60 2 2 Write string Delay2s SPI Glcd Set Font Font Glcd System5x7 5 7 32 Change font SomeText 5x7 Font SPI Glcd Write Text someText 5 4 2 Write string Delay2s SPI Glcd Set Font Font Glcd 5x7 5 7 32 Change font someText 5x7 Font v2 SPI Glcd Write Text someText 50 6 2 Write string Delay2s end end MikroElektronika 460 mikroPascal PRO for PIC32 HW Connection a Left side Rightside 7 X axis 0 x783 xed x 63 UUUUUUuUuUuuuguUUuUUUUUDuuU g Vcca ovcca SPI Glcd HW connection 461 MikroElektronika mikoPascal PRO for PIC32 SPI Lcd Library The mikroPascal PRO for PIC32 provides a library for communication with Lcd with HD44780 compliant controllers in 4 bit mode via SPI interface For creating a custom set of Lcd characters use Lcd Custom Character Tool Important When using this library with PIC32 family MCUs be aware of their voltage incompatibility with certain number of Led modules So additional external
97. HID terminal that is active on the PC Upon connection establishment the HID Device Name will appear in the respective window After that software will wait for data and it will return received data back Examples uses USBdsc mpas descriptor file which is in the same folder and can be created by the HID Terminal Copy Code To Clipboard program HID Read Write Polling var cnt kk char var readbuff array 64 of char var writebuff array 64 of char begin CHECON 0x32 ADIPCFG OxFFFF HID Enable readbuff writebuff while TRUE do begin USB Polling Proc Call this routine periodically kk HID Read if kk lt gt 0 then begin for cnt 0 to 63 do writebuff cnt readbuff cnt HID Write writebuff 64 end end end HW Connection lt oQ o e aj NE y OSCILLATOR PIC32MX460F512L E vec lt Q 8 nnnnnnnn R i 4 Ecs a D USB connection scheme 567 MikroElektronika mikoPascal PRO for PIC32 Miscellaneous Libraries Button Library C Type Library Conversions Library Setjmp Library String Library Time Library Trigon Library Trigonometry Library Button Library The Button Library provides routines for detecting button presses and debouncing eliminating the influence of contact flickering upon pressing a button Library Routines Button Button Prototype function Button var port wor
98. IC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Library Example This code demonstrates working with the I C library Program sends data to EEPROM data is written at the address 2 After that program reads data from the same EEPROM address and displays it on PORTB for visual check See the figure below how to interface the 24C02 to PIC32 Copy Code To Clipboard program I2C Simple var i b char procedure EEPROM 24C02 Init begin I2C2 Init 100000 end fcemneec ecB EBc Writes data to 24C02 EEPROM signle location procedure EEPROM 24C02 WrSingle wAddr byte wData byte begin I2C2 Start issue I2C start signal I2C2 Write 0xA0 send byte via I2C command to 24c02 I2C2 Write wAddr send byte address of EEPROM location I2C2 Write wData send data data to be written I2C2 Stop end Reads data from 24C02 EEPROM single location random function EEPROM 24C02 RdSingle rAddr byte byte begin I2C2 Start issue I2C start signal I2C2 Write 0xA0 send byte via I2C device address W I2C2 Write rAddr send byte data address I2C2 Restart issue I2C signal repeated start I2C2 Write 0xA1 send byte device address R MikroElektronika 312 mikroPascal PRO for PIC32 res
99. MD signal direction End T6963C module connections var panel byte current panel i word general purpose register curs byte cursor visibility Cposx 919 MikroElektronika mikoPascal PRO for PIC32 cposy word cursor x y position txtcols byte number of text coloms txt txtl string 29 txt2 string 21 begin SDEFINE LINE DEMO Uncomment to demonstrate line drawing routines SDEFINE FILL DEMO Uncomment to demonstrate fill routines SDEFINE PARTIAL IMAGE DEMO Uncomment to demonstrate partial image routine txtl EINSTEIN WOULD HAVE LIKED mE txt GLCD LIBRARY DEMO WELCOME txt2 Partial image demo CHECON 0x32 ADIPCFG OxFFFF TRISB8 bit p Set RB8 as input TRISB9 bit 1 Set RB9 as input TRISB10 bit 1 Set RB10 as input TRISB11 bit 1 Set RB11 as input TRISB12 bit 1 Set RB12 as input TRISB13 bit 1 Set RB13 as input T6963C ctrlce Direction 0 T6963C ctrlce 0 Enable T6963C T6963C ctrlfs Direction 0 T6963C ctrlfs 0 Font Select 8x8 T6963C ctrlmd Direction 0 T6963C ctrlmd 0 Column number select panel 0 i 0 curs 0 cposx 0 cposy 0 Initialize T6369C T6963C init 240 128 8 E T6963C graphics 1 T6963C text 1 Text messages T6963C write text txt T6963C write text txtl 0 0 Enable both
100. Microchip s Port Expander MCP23S17 via SPI interface Connections of the PIC32 MCU and MCP23S17 is given on the schematic at the bottom of this page Important The library uses the SPI module for communication User must initialize the appropriate SPI module before using the Port Expander Library For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by using the SPI Set _ Active function See the SPI Library functions Library does not use Port Expander interrupts Library Dependency Tree Port Expander gt sP1 External dependencies of Port Expander Library The following variables must be defined in all projects using Port Expander Description Library var SPExpanderRST sbit sfr A var SPExpanderRST sbit at LATFO Reset line f external bit var SPExpanderCS sbit sfr var SPExpanderCS sbit at LATF1 Chip Select line external bit var SPExpanderRST Direction Direction of the Reset pin var SPExpanderRST Direction sbit Sbit sfr external Ten pin at TRISFO bit var SPExpanderCS Direction var SPExpanderCS Direction sbit at shits wis eetornal Direction of the Chip Select pin TRISF1 bit Library Routines Expander Init Expander Init Advanced Expander Read Byte Expander Write Byte Expander Read PortA Expander Read PortB Expander Read PortAB Expander Write PortA Expander Write PortB
101. MikroElektronika mikoPascal PRO for PIC32 CHAPTER 9 mikroPascal PRO for PIC32 Libraries mikroPascal PRO for PIC32 provides a set of libraries which simplify the initialization and use of PIC32 and their modules Use Library manager to include mikroPascal PRO for PIC32 Libraries in you project MikroElektronika 234 mikroPascal PRO for PIC32 Hardware Libraries ADC Library CANSPI Library Compact Flash Library Epson S1D13700 Graphic Lcd Library Flash Memory Library Graphic Lcd Library PC Library Keypad Library Lcd Library Manchester Code Library Memory Manager Library Multi Media Card Library OneWire Library Port Expander Library PS 2 Library PWM Library RS 485 Library Software l C Library Software SPI Library Software UART Library Sound Library SPI Library SPI Ethernet Library SPI Ethernet ENC24J600 Library SPI Graphic Lcd Library SPI Lcd Library SPI Lcd8 Library SPI T6963C Graphic Lcd Library T6963C Graphic Lcd Library TFT Display Library Touch Panel Library Touch Panel TFT Library UART Library USB Library Miscellaneous Libraries Button Library Conversions Library PrintOut Library Setjmp Library Sprint Library Time Library Trigonometry Library See also Built in Routines 235 MikroElektronika mikoPascal PRO for PIC32 Hardware Libraries ADC Library CA
102. ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written Data to be written to PortA are passed in Data s higher byte Data to be written to PortB are passed in Data s lower byte Nothing Port Expander must be initialized See Expander Init Port Expander s PortA and PortB should be configured as outputs See Expander Set DirectionPortA Expander Set DirectionPortB and Expander Set DirectionPortAB routines Write a byte to Port Expander s PORTA and PORTB Expander Set DirectionPortAB 0 0000 set expander s porta and portb to be output Expander Write PortAB 0 AA55 Expander Set DirectionPortA Prototype Description Parameters procedure Expander Set DirectionPortA ModuleAddress Data byte The function sets Port Expander s PortA direction ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written to the PortA direction register Each bit corresponds to the appropriate pin of the PortA register Set bit designates corresponding pin as input Cleared bit designates corresponding pin as output Nothing Port Expander must be initialized See Expander Init Set Port Expander s PORTA to be output Expander Set DirectionPortA 0 00 MikroElektronika mikoPascal PRO for PIC32 Expander_Set_DirectionPortB Prototype procedure Expander Set DirectionPortB ModuleAddress Dat
103. PIC32 Mmc Fat Get File Date Prototype procedure Mmc Fat Get File Date var year word var month byte var day byte var hours byte var mins byte Description Reads time date attributes of the currently assigned file Parameters year buffer to store year attribute to Upon function execution year attribute is returned through this parameter month buffer to store month attribute to Upon function execution month attribute is returned through this parameter da y buffer to store day attribute to Upon function execution day attribute is returned through this parameter hours buffer to store hours attribute to Upon function execution hours attribute is returned through this parameter nins buffer to store minutes attribute to Upon function execution minutes attribute is returned through this parameter MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init The file must be previously assigned See Mmc Fat Assign var year word month day hours mins byte Date year month day hours mins 337 MikroElektronika mikoPascal PRO for PIC32 Mmc Fat Get File Date Modified Prototype procedure Mmc Fat Get File Date Modified var year word var month byte var day byte var hours byte var mins byte Description Retrieves the last modification date time for the currently selected file Seconds are not being retrieved since they are written in 2
104. PORTB while error on receiving OxAA and number of consecutive unsuccessful retries are displayed on PORTD Hardware configurations in this example are made for the LV 32MX v6 board and PIC32MX460F512L Copy Code To Clipboard program RS485 Master Example var dat array 10 of byte buffer for receving sending messages i j byte ent longint var rs485 rxtx pin sbit at RF2 bit set transcieve pin rs485 rxtx pin direction sbit at TRISF2 bit set transcieve pin direction Interrupt routine procedure interrupt iv IVT UART 2 ilevel 7 ics ICS SRS begin RS485Master Receive dat U2RXIF bit 0 ensure interrupt not pending end begin cnt 0 CHECON 0x32 ADIPCFG OxFFFF PORTB PORTD TRISB TRISD PEU ll eo S S UART2 Init 19200 initialize UART2 module Delay ms 100 RS485Master Init initialize MCU as Master dat 0 OxAA dat 1 OxF0 dat 2 OxOF dat 4 0 ensure that message received flag is 0 dat 5 0 ensure that error flag is 0 dat 6 0 U2IPO bit 1 set interrupt UZ2IPI bit 1 pricorsity U2IP2 bit 1 te 7 URXISEL1 U2STA bit 0 Ox Interrupt flag bit is set when a character is received U2RXIF bit 0 ensure interrupt not pending MikroElektronika 372 mikroPascal PRO for PIC32 Interrupt controller configured for multi vectored mode MVEC bit 1
105. PRI 4 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 33l MikroElektronika mikoPascal PRO for PIC32 Mmc_Fat_QuickFormat Prototype function Mmc Fat QuickFormat var mmc fat label string 11 word Formats to FAT16 and initializes MMC SD card Parameters mmc fat label volume label 11 characters in length If less than 11 characters are provided the label will be padded with spaces If null string is passed volume will not be labeled 0 if MMC SD card was detected successfully formated and initialized 1 if FAT16 format was unseccessful 255 if MMC SD card was not detected The appropriate hardware SPI module must be previously initialized HIGH SPI ACTIVE 2 IDLE This routine can be used instead or in conjunction with Mmc Fat Init routine If MMC SD card already contains a valid boot sector it will remain unchanged except volume label field and only FAT and ROOT tables will be erased Also the new volume label will be set Initialize the SPI module SPI1 Init Advanced SPI MASTER SPI 8 BIT SPI PRESCALE SEC 1 SPI PRESCALE PRI 64 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 IDLE Format and initialize MMC SD card and MMC FAT16 library globals Mme Fat QuickFormat mikroE Reinitialize the SPI module at higher speed change primary prescaler SPI1 Init Advanced SPI MASTER SPI 8 BIT SPI PRESCAL
106. Parameters x0 x coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner pcolor color parameter Valid values T6963C BLACK and T6963C WHITE mme ho o ooo UUU a ie rectangle 20 20 219 107 T6963C WHITE LC Res eT T6963C rectangle round edges Prototype procedure T6963C rectangle round edges x0 y0 xl yl radius integer pcolor byte Draws a rounded erm rectangle on Glcd Parameters x0 x coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner round radius radius of the rounded edge nee color parameter Valid values T6963C BLACK and T6963C WHITE Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C rectangle sound edges 20 20 219 107 12 T6963C WHITE 507 MikroElektronika mikoPascal PRO for PIC32 T6963C rectangle round edges fill pcolor byte Draws a filled rounded edge rectangle on Glcd Parameters x0 x coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner Prototype procedure
107. Project 607 MikroElektronika mikoPascal PRO for PIC32 Source Files Source files containing source code should have the extension mpas The list of source files relevant to the application is stored in project file with extension mppav along with other project information You can compile source files only if they are part of the project Managing Source Files Creating new source file To create a new source file do the following 1 Select File New Unit from the drop down menu or press Ctrl N or click the New File Icon Li from the File Toolbar l 2 Anew tab will be opened This is a new source file Select File gt Save from the drop down menu or press Ctrl S or click the Save File Icon H from the File Toolbar and name it as you want If you use the New Project Wizard an empty source file named after the project with extension mpas will be created automatically The mikroPascal PRO for PIC32 does not require you to have a source file named the same as the project it s just a matter of convenience Opening an existing file 1 Select File Open from the drop down menu or press Ctrl O or click the Open File Icon i E from the File Toolbar In Open Dialog browse to the location of the file that you want to open select it and click the Open button 2 The selected file is displayed in its own tab If the selected file is already open its current Editor tab will become active Printing an open file
108. Round Edges 81D13700 Rectangle Round Edges Fill 81D13700 Circle 81D13700 Circle Fill 81D13700 Image 81D13700 Partiallmage 219 MikroElektronika mikoPascal PRO for PIC32 1D13700_Init Prototype Em S1D13700 Init width word height word Description Initializes S1D13700 Graphic Lcd controller Parameters width width of the Glcd panel height height of the Glcd panel Requires Global variables 1D13700 Data Port Data Bus Port 51D13700 WR Write signal pin 51D13700 RD Read signal pin 51D13700 A0 Command Data signal pin 51D13700 RES Reset signal pin 51D13700 CS Chip Select signal pin 1D13700 Data Port Direction Data Bus Port Direction 51D13700 WR Direction Direction of Write signal pin 1D13700 RD Direction Direction of Read signal pin 51D13700 AO Direction Direction of Command Data signal pin 81D13700 RES Direction Direction of Reset signal pin 81D13700 CS Direction Direction of Chip Select signal pin must be defined before using this function S1D13700 module connections var S1D13700 Data Port byte at PORTD var S1D13700 WR sbit at LATC2 bit var S1D13700 RD sbit at LATCI bit var S1D13700 AO sbit at LATCO bit var S1D13700 RES sbit at LATC3 bit var S1D13700 CS sbit at LATC4 bit var S1D13700 Data Port Direction byte at PORTD var S1D13700 WR Direction sbit at TRISC2 bit var S1D13700 RD Direction sbit at TRISC1 bit
109. SPI module SPI1 Init SPI T6963C config 240 64 8 SPI T6963C writeData procedure SPI T6963C writeData data byte a S O Example SPI_T6963 writevatataata n CS Noes noe 0 SPI T6963C writeCommand Prototype procedure SPI T6963C writeCommand data byte Writes command to T6963C controller via SPI interface data command to be written Toshiba Glcd module needs to be initialized See SPI T6963C E routine ee SPI T6963C writeCommand SPI T6963C CURSOR POINTER SE MikroElektronika 418 mikroPascal PRO for PIC32 SPI_T6963C_setPtr Prototype procedure SPI T6963C setPtr p word c byte Description Sets the memory pointer p for command p Parameters address where command should be written c command to be written Nothing Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine L6963C setPtr SPI T6963C grHomeAddr start SPI T6963C ADDRI TER SET SPI T6963C waitReady SPI T6963C fill Prototype procedure SPI T6963C fill v byte start len word Description Fills controller memory block with given byte Parameters v byte to be written start starting address of the memory block 1en length of the memory block in bytes 479 MikroElektronika mikoPascal PRO for PIC32 SPI_T6963C_dot Prototype procedure SPI T6963C dot x integer color byte y Writes a char in the c
110. See Expander Init Read a byte from Port Expander s register var read data byte read data Expander Read Byte 0 1 Expander Write Byte Prototype procedure Expander Write Byte ModuleAddress RegAddress Data byte Routine writes a byte to Port Expander Parameters ModulecAddress Port Expander hardware address see schematic at the bottom of this page RegAddress Port Expander s internal register address bata data to be written Retums Byte read Port Expander must be initialized See Expander Init Write a byte to the Port Expander s register Expander Write Byte 0 1 0xFF Expander_Read_PortA DOES function Expander Read PortA ModuleAddress byte byte The function reads byte from Port Expander s PortA ModuleAddress Port Expander hardware address see schematic at the bottom of this page Requires Port Expander must be initialized See Expander Init Port Expander s PortA should be configured as input See Expander Set DirectionPortA and Expander Set DirectionPortAB routines Read a byte from Port Expander s PORTA var read data byte Expander Set _DirectionPortA 0 FF set expander s porta to be input read data Expander Read PortA 0 MikroElektronika 390 mikroPascal PRO for PIC32 Expander Read PortB Prototype function Expander Read PortB ModuleAddress byte byte The function reads byte from Port Expander s PortB
111. T6963C 240x128 asm einstein bmp asm mikroe bmp asm T6963C 240x128 lst Other Files 3 DataSheet_70138b pdf MikroElektronika 606 mikroPascal PRO for PIC32 The list of relevant files is stored in the project file extension mpp32 To add a file to the project click the Add File to Project Icon Go press Insert button on your keyboard Each added source file must be self contained i e it must have all necessary definitions after preprocessing To remove file s from the project click the Remove File from Project Icon gt or press Delete button on your keyboard A Project Level Defines Project Level Defines 1a files can also be added to project Project level define files enable you to have defines that are visible in all source files in the project A file must contain one definition per line in the following form ANALOG EBUG TEST J For example lets make a project level define named pld test First of all create a new file with the p1d extension pld test file pld Next open it and write something like this PLD TEST Once you have done this save the file In the Project Manager add pld test ile pid file by right clicking the Project Level Defines node In the source code write the following SIFDEF PLD TEST SENDIF There are a number of predefined project level defines See predefined project level defines Related topics Project Manager Project Settings Edit
112. T6963C WHITE SENDIF Draw a cross SIFDEF LINE DEMO T6963C line 0 0 239 127 T6963C WHIT T6963C line 0 127 239 0 T6963C WHITI SENDIF 91 MikroElektronika mikoPascal PRO for PIC32 Draw circles SIFDEF LINE DEMO T6963C circle 120 64 10 T6963C WHITE T6963C circle 120 64 30 T6963C WHITE M T6963C circle 120 64 50 T6963C WHITI T6963C circle 120 64 70 T6963C WHITI T6963C circle 120 64 90 T6963C WHITE T6963C circle 120 64 110 T6963C WHITE T6963C circle 120 64 130 T6963C WHITE SENDIF e E mo oo M M Draw filled circles SIFDEF FILL DEMO T6963C circle fill 120 64 60 T6963C WHITE T6963C circle fill 120 64 55 T6963C BLACK T6963C circle fil1 120 64 50 T6963C WHITE T6963C circle fill 120 64 45 T6963C BLACK T6963C circle fil1 120 64 40 T6963C WHITE T6963C circle fill 120 64 35 T6963C BLACK T6963C circle fil1 120 64 30 T6963C WHITE T6963C circle fill 120 64 25 T6963C BLACK T6963C circle fil1 120 64 20 T6963C WHITE T6963C circle fill 120 64 15 T6963C BLACK T6963C circle fil1 120 64 10 T6963C WHITE T6963C circle fill 120 64 5 T6963C BLACK SENDIF Delay ms 1000 T6963C sprite 76 4 einstein 88 119 Draw a sprite Delay ms 1000
113. T6963C setGrPanel 1 Select other graphic panel T6963C image mikroE 240x128 bmp T6963C displayGrPanel 1 Delay ms 1000 SIFDEF PARTIAL IMAGE DEMO T6963C grFill 0 T6963C PartialImage 0 0 64 64 240 128 mikroE 240x128 bmp Display partial image Delay ms 1000 T6963C graphics 0 SENDIF T6963C image mikroE 240x128 bmp T6963C graphics 1 T6963C displayGrPanel 0 MikroElektronika 918 mikroPascal PRO for PIC32 Endless loop while TRUE do begin If RB8 is pressed if RB8 bit lt gt 0 then begin Inc panel panel panel and 1 T6963C setPtr T6963C grMemSize T6963C txtMemSize panel T6963C GRAPHIC HOME ADDRESS SET Delay ms 300 end toggle the display between graphic panel 0 and graphic 1 If RB9 is pressed display only graphic panel y else if RB9 bit 0 then begin T6963C graphics 1 T6963C text 0 Delay ms 300 end If RB10 is pressed display only text panel j else if RB10 bit lt gt 0 then begin T6963C_graphics 0 T6963C text 1 Delay ms 300 end pt If RB11 is pressed display text and graphic panels xj else if RB11 bit lt gt 0 then begin T6963C graphics 1 T6963C text 1 Delay ms 300 end If RB12 is pressed change cursor MikroElektronika 919 mikoPascal PRO for PIC32 else if RB12 bit lt
114. This is very convenient for programs that work with time intervals the difference between two UNIX time values is a real time difference measured in seconds What is the epoch Originally it was defined as the beginning of 1970 GMT January 1 1970 Julian day GMT Greenwich Mean Time is a traditional term for the time zone in England The TimeStruct type is a structure type suitable for time and date storage Library Routines Time dateToEpoch Time epochToDate Time dateDiff Time dateToEpoch Prototype function Time dateToEpoch var ts TimeStruct longint var tsl i TimeStruct Epoch longint what is the epoch of the date in ts poch Time dateToEpoch 8tsl 593 MikroElektronika mikoPascal PRO for PIC32 Time_epochToDate Prototype procedure Time epochToDate e longint var ts TimeStruct ts time and date structure for storing conversion output Rems nonn var ts2 TimeStruct epoch longint what date is epoch 1234567890 epoch 1234567890 Time epochToDate epoch ts2 Time_dateDiff Prototype function Time dateDiff var tl t2 TimeStruct longint Description This function compares two dates and returns time difference in seconds as a signed long Result is positive if t1 is before t2 result is null if t 1 is the same as t2 and result is negative if t1 is after t2 Parameters 1 time and date structure the first comparison paramete
115. Tree g _ Compact Flash Compact Flash FAT16 c Type 257 MikroElektronika mikoPascal PRO for PIC32 External dependencies of Compact Flash Library The following variables must be defined in all projects Description using Compact Flash Library var CF Data Port byte I Y Compact Flash Data Port var CF sfr external var CF RDY external var CF WE external var CF OE external var CF CD1 external var CF CEl1 external var CF A2 external var CF Al external var CF A0 external bit sfr e sfr va CF WE direction var CF WE direction sbit at Direction of the Write Enable pin oS external bit va CF OE direction var CF OE direction sbit at pore Sfr var CF CDI direction sbit sfr CF CE1 direction Sbit sfr va CF A2 direction a sfr va CF Al direction vem sfr va CF A0 direction pam sir it sfr Sere STE Ready signal line var C bit sfr du 7 write Enable signal line var CF WE bit r d sid Output Enable signal line var CF OE bit sfr SE be Chip Detect signal line var C bit Sfr s TES xa Chip Enable signal line var C F Data Port byte at PORTD F RDY sbit at RB7 bit sbit at LATB6 bit sbit at LATB5 bit F CD1 sbit at RB4 bit F CE1 sbit at LATB3 bit sbit sfr Address pin 2 var CF A2 sbit at LATB2 bit it sfr z eter Eee Address pin 1 var CF A
116. Valid values 0 2 The parameter color determines a dot state O clears dot 1 puts a dot and 2 inverts dot state Glcd needs to be initialized see Glcd Init routine Invert the dot in the upper left corner Gled Dot 0 0 2 Notes For x and y axis layout explanation see schematic at the bottom of this page Glcd Line Prototype procedure Glcd Line x start y start x end y end integer color byte Draws a line on Glcd Parameters x start x coordinate of the line start Valid values 0 127 y start y coordinate of the line start Valid values 0 63 x end X coordinate of the line end Valid values 0 127 y end y coordinate of the line end Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the line color O white 1 black and 2 inverts each dot Glcd needs to be initialized see Glcd Init routine Draw a ae o dots 0 0 and 20 30 Glcd Line 20 133 MikroElektronika 300 mikroPascal PRO for PIC32 Glcd_V_Line Prototype procedure Gled V Line y start y end x pos color byte Description Draws a vertical line on Glcd Parameters y start y coordinate of the line start Valid values 0 63 y end y coordinate of the line end Valid values 0 63 x pos X coordinate of vertical line Valid values 0 127 color color parameter Valid values 0 2 The parameter color determines the line color 0 white 1 black and 2 i
117. Value numbering 163 Dead code ellimination 163 Stack allocation 163 Local vars optimization 163 Better code generation and local optimization 163 Single Static Assignment Optimization 164 Introduction 164 Proper Coding Recommendations 165 Asm code and SSA optimization 166 Debugging Notes 166 Warning Messages Enhancement 166 CHAPTER 7 168 PIC32 Specifics 168 Types Efficiency 169 Nested Calls Limitations 169 Variable constant and routine alignment 169 Boot Start up Initialization 169 PIC32 Memory Organization 170 PIC32MX Memory Layout 171 Virtual vs Physical Addresses 172 Memory Type Specifiers 173 code 173 data 173 rx 173 sfr 173 Read Modify Write Problem 174 CHAPTER 8 178 mikroPascal PRO for PIC32 Language Reference 178 Lexical Elements Overview 180 Whitespace 180 Newline Character 180 MikroElektronika mikoPascal PRO for PIC32 Whitespace in Strings 180 Comments 181 Nested comments 181 Tokens 182 Token Extraction Example 182 Literals 183 Integer Literals 183 Floating Point Literals 183 Character Literals 184 String Literals 184 Keywords 185 Identifiers 186 Case Sensitivity 186 Uniqueness and Scope 186 Identifier Examples 186 Punctuators 187 Brackets 187 Parentheses 187 Comma 187 Semicolon 188 Colon 188 Dot 188 Program Organization 189 Organization of Main Unit 189 Organization of Other Units 190 Scope and Visibility 191 Scope 191 Visibility 191 Name Spaces 192 Units 193 Uses Clause 193 Main Uni
118. a backslash Examples az matches a z and az matches a z and a z matches a z and a z matches all twenty six small characters from a to z n x0D matches any of 10 11 12 13 d t matches any digit or t 1 a matches any char from a Metacharacters Metacharacters are special characters which are the essence of regular expressions There are different types of metacharacters described below Metacharacters Line separators start of line end of line A start of text z end of text any character in line Examples PORTA matches string PORTA only if it s at the beginning of line PORTAS matches string PORTA only if it s at the end of line PORTAS matches string PORTA only if it s the only string in line PORT r matches strings like PORTA PORTB PORT1 and so on The metacharacter by default is only guaranteed to match beginning of the input string text and the metacharacter only at the end Embedded line separators will not be matched by or You may however wish to treat a string as a multi line buffer such that the will match after any line separator within the string and will match before any line separator Regular expressions works with line separators as recommended at http www unicode org unicode reports tr18 MikroElektronika 106
119. actual Pascal routines Their sources can be found in the delays mpas file located in the uses folder of the compiler Lo Hi Higher Highest LoWord HiWord Inc Dec Chr Ord SetBit ClearBit TestBit Delay_us Delay_ms Vdelay_ms Vdelay_Advanced_ms Delay_Cyc Delay_Cyc_Long Clock_kHz Clock_MHz Get_Fosc_kHz Get_Fosc_Per_Cyc Reset ClrWdt DisableContextSaving SetFuncCall SetOrg GetDateTime GetVersion MikroElektronika 144 mikroPascal PRO for PIC32 KVAO TO KVA1 KVA1 TO KVAO KVA TO PA PA TO KVAO PA TO KVA1 CPO Get CPO Set Enablelnterrupts Disablelnterrupts Prototype function Lo number longint byte Description Function returns the lowest byte of number Function does not interpret bit patterns of number it merely returns 8 bits as found in register This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Retums Lowest 8 bits byte of number bits 7 0 Arguments must be variable of scalar type i e Arithmetic Types and Pointers 0x12345678 tmp Lo d Equals 0x78 Prototype function Hi number longint byte Description Function returns next to the lowest byte of number Function does not interpret bit patterns of number it merely returns 8 bits as found in register This is an inline rou
120. any way mess with enabling disabling receive transmit logic or any other part of the ENC28J60 module The ENC28760 module should be properly cofigured by the means of SPI Ethernet Init routine Parameters enF1t network traffic receive filter flags Each bit corresponds to the appropriate network traffic receive filter 01 MAC Broadcast traffic receive filter flag When set SPI Ethernet MAC broadcast traffic will be enabled BROADCAST X MAC Multicast traffic receive filter flag When set SPI Ethern MAC multicast traffic will be enabled MULTICAST CRC check flag When set packets with invalid eo eee CRC field will be discarded MAC Unicast traffic receive filter flag When set x MAC unicast traffic will be enabled Nothing Ethernet module has to be initialized See SPI Ethernet Init SPI Ethernet Enable SPI Ethernet CRC or SPI Ethernet UNICAST enable CRC checking and Unicast traffic Advanced filtering available in the ENC28J60 module such as Pattern Match Magic Packet and Hash Table can not be enabled by this routine Additionaly all filters except CRC enabled with this routine will work in OR mode which means that packet will be received if any of the enabled filters accepts it This routine will change receive filter configuration on the fly It will not in any way mess with enabling disabling receive transmit logic or any other part of the ENC28760 module The ENC28360 module sh
121. array 30 of char buffer for dynamic response httpCounter word counter of HTTP requests Ree ee ek ek kc ke ke hok KK ERE EEK EKER dee ke ke EK ke e kk k k EK user defined functions i 471 MikroElektronika mikoPascal PRO for PIC32 this function is called by the library the user accesses to the HTTP request by successive calls to SPI Ethernet getByte the user puts data in the transmit buffer by successive calls to SPI Ethernet putByte the function must return the length in bytes of the HTTP reply or 0 if nothing to transmit if you don t need to reply to HTTP requests just define this function with a return 0 as single statement 5 function SPI Ethernet UserTCP var remoteHost array 4 of byte remotePort localPort reqLength word var flags TEthPktFlags word var i word my reply length bitMask dword for bit mask tmp string 11 to copy const array to ram for memcmp begin result 0 should we close tcp socket after response is sent library closes tcp socket by default if canCloseTCP flag is not reset here flags canCloseTCP 0 0 do not close socket otherwise close socket if localPort lt gt 80 then I listen only to web request on port 80 begin result 0 exit end get 10 first bytes only of the request the rest does not matter here for i 0 to 9 do getRequest i SPI Ethernet getByte getRequ
122. array can be located in both code and RAM memory due to the mikroPascal PRO for PIC32 pointer to const and pointer to RAM equivalency Nothing Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Image dimension must match the display dimension Use the integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd SPI T6963C Partiallmage Prototype procedure SPI T6963C Partiallmage x left y top width height picture width picture height word const image byte Description Displays a partial area of the image on a desired location Parameters x left x coordinate of the desired location upper left coordinate y top y coordinate of the desired location upper left coordinate width desired image width height desired image height picture width width of the original image picture height height of the original image image image to be displayed Bitmap array can be located in both code and RAM memory due to the mikroPascal PRO for PIC pointer to const and pointer to RAM equivalency Nothing Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Draws a 10x15 part of the image starting from the upper left corner on the coordinate 10 12 Original image size is 16x32 SPI T6963C Partiallmage 10 12 10 15 16 32 image Use the integrated Glc
123. be volatile warns the compiler not to make assumptions concerning the value of an object while evaluating expressions in which it occurs because the value could be changed at any moment Operators Operators are tokens that trigger some computation when being applied to variables and other objects in an expression There are four types of operators in mikroPascal PRO for PIC32 Arithmetic Operators Bitwise Operators Boolean Operators Relational Operators MikroElektronika 211 mikroPascal PRO for PIC32 Operators Precedence and Associativity There are 4 precedence categories in mikroPascal PRO for PIC32 Operators in the same category have equal precedence with each other Each category has an associativity rule left to right or right to left In the absence of parentheses these rules resolve the grouping of expressions with operators of equal precedence O e e oean 2 n e de E o es s Ho cp 0 00 qe se o 9 d x 00 e 1 Arithmetic Operators Arithmetic operators are used to perform mathematical computations They have numerical operands and return numerical results Since the char operators are technically bytes they can be also used as unsigned operands in arithmetic operations All arithmetic operators associate from left to right Operator Operation operans Ret addition byte short word integer byte short word longint dword real integer longint dword real subt
124. bit GLCD RW Direction Fl bit GLCD EN Direction F4 bit GLCD RST Direction F5 Dit 299 MikroElektronika mikoPascal PRO for PIC32 Library Routines Basic routines Glcd Init Gled Set Side Gled Set X Gled Set Page Gled Read Data Gled Write Data Advanced routines Glcd Fill Gled Dot Glcd Line Gled V Line Glcd H Line Gled Rectangle Gled Rectangle Round Edges Gled Rectangle Round Edges Fill Gled Box Gled Circle Gled Circle Fill Gled Set Font Gled Write Char Gled Write Text Glcd Image Gled Partiallmage Glcd Init Prototype procedure Glcd Init Description Initializes the Glcd module Each of the control lines are both port and pin configurable while data lines must be on a single port pins lt 0 7 gt Requires Global variables DO Data pin 0 D1 Data pin 1 D2 Data pin 2 03 Data pin 3 D4 Data pin 4 D5 Data pin 5 D6 Data pin 6 D7 Data pin 7 CS1 Chip select 1 signal pin CS2 Chip select 2 signal pin RS Register select signal pin RW Read Write Signal pin Spe ed d nd d t ad MikroElektronika 296 mikroPascal PRO for PIC32 VE CE SE ae Requires EN Enable signal pin LCD RST Resetsignal pin 1 DO Direction Direction of the Data pin 0 1 D1 Direction Direction of the Data pin 1 1 D2 Direction Direction of the Data pin 2 1 D3_Direction Di
125. click the added file and choose Set As Preview Image Project Manager 1 1 R5485 Master Example mpp32 a0 ACIE B En RS485 Master Example mpp32 S E Sources R5485 Master Example mpas Binaries Project Level Defines 2 Image Files Ej EEPROM Fies i Save Project Group C7 Active Comments Fi Close Project Ch S C7 Output Files 3 Add Project RS485 Master G i emove Project C3 Other Files a GY Add File To Project Remove File From Project M Build Ctrl F9 d mE Programmer Fil Set As Preview Image Ctri Alt P 13 MikroElektronika mikoPascal PRO for PIC32 Once you have added the image it will appear in the Image Preview Window X bn pa pe SE EE ESE TIY 9 05m 62564244 a SLR Mos Q ge in i 18843912ld DT VIDT 1884912ld i Also you can add multiple images to the Image Files node but only the one that is set will be automatically displayed in the Image Preview Window upon opening the project By changing the Image Preview Window size displayed image will be fit by its height in such a way that its proportions will remain intact Toolbars This section provides an overview of the toolbars available in mikroPascal PRO for PIC32 Help File Toolbar Edit Toolbar Advanced Edit Toolbar Find Toolbar Project Toolbar Build Toolbar Debug Toolbar Styles Toolbar Tools Toolbar View Toolbar Layo
126. coordinate of the circle center y y coordinate of the circle center r radius size color parameter Valid values T6963C BLACK and T6963C WHITE Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C circle fill 120 64 110 T6963C WHITE T6963C image Prototype procedure T6963C image const pic byte Displays bitmap on Glcd Parameters pic image to be displayed Bitmap array can be located in both code and RAM memory due to the mikroPascal PRO for PIC32 pointer to const and pointer to RAM equivalency Toshiba Glcd module needs to be initialized See the T6963C init routine Example T6963C image my image Image dimension must match the display dimension Use the integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd 509 MikroElektronika mikoPascal PRO for PIC32 T6963C_Partiallmage Prototype procedure T6963C Partiallmage x left y_ aa width height picture width picture height word const image byte Displays a partial area of the image on a desired location Parameters x left x coordinate of the desired location upper left coordinate y top y coordinate of the desired location upper left coordinate width desired image width height desired image height picture width width of the original image picture height height of the origin
127. dat2string SUM3 vtext and here are some invalid identifiers temp NO cannot begin with a numeral Shigher NO cannot contain special characters xor NO cannot match reserved word j23 07 94 NO cannot contain special characters dot MikroElektronika 184 mikroPascal PRO for PIC32 Punctuators The mikroPascal PRO for PIC32 punctuators also known as separators are Brackets Parentheses Comma Semicolon Colon Dot Brackets Brackets indicate single and multidimensional array subscripts var alphabet array 1 30 of byte te alphabet 3 c For more information refer to Arrays Parentheses Parentheses are used to group expressions isolate conditional expressions and indicate function calls and function declarations d c a b Override normal precedence if d z then Useful with conditional statements func Function call no arguments function func2 n word Function declaration with parameters For more information refer to Operators Precedence and Associativity Expressions and Functions and Procedures Comma Comma separates the arguments in function calls LCD Out 1 1 txt Furthermore the comma separates identifiers in declarations var i j k byte The comma also separates elements of array in initialization lists const MONTHS array 1 12 of byte 31 28 31 30 31 30 31 31 30
128. data space pointing to a byte in code space Therefore when declaring a pointer within constant declaration block const qualifier refers to pointed object not to pointer itself Notes Pointer to constant space Flash memory is allocated in RAM Constants of a simple type are not allocated in the Flash memory nor in RAM but changed in the compile time and therefore address of a such constant can not be obtained Function Pointers Function pointers are allowed in mikroPascal PRO for PIC32 The example shows how to define and use a function pointer Example Example demonstrates the usage of function pointers It is shown how to declare a procedural type a pointer to function and finally how to call a function via pointer 205 MikroElektronika mikoPascal PRO for PIC32 program Example type TMyFunctionType function paraml param2 byte param3 word word First define the procedural type var MyPtr TMyFunctionType This is a pointer to previously defined type Sample word function Funcl pl p2 byte p3 word word Now define few functions which will be pointed to Make sure that parameters match the type definition begin result pl and p2 or p3 return something end function Func2 abc byte def byte ghi word word Another function of the same kind Make sure that parameters match the type definition begin result abc def ghi return something end function
129. determines the color of the rectangle border O white 1 black and 2 inverts each dot Glcd needs to be initialized see Glcd Init routine Draw a rectangle between dots 5 5 and 40 40 Glcd Rectangle 5 5 40 40 1 Glcd Rectangle Round Edges Prototype procedure Glcd Rectangle Round Edges x upper left byte y upper left i ina x bottom right byte y bottom right byte radius byte color byte Draws a rounded edge rectangle on Glcd Parameters x upper left x coordinate of the upper left rectangle corner Valid values 0 127 y upper left y coordinate of the upper left rectangle corner Valid values 0 63 x bottom right x coordinate of the lower right rectangle corner Valid values 0 127 y bottom right y coordinate of the lower right rectangle corner Valid values 0 63 round radius radius of the rounded edge color color parameter Valid values 0 2 The parameter color determines the color of the rectangle border 0 white 1 black and 2 inverts each dot Glcd needs to be initialized see Glcd Init routine Draw a rounded edge rectangle between dots 5 5 and 40 40 with the radius of 12 Gled Rectangle Round Edges 5 MikroElektronika 302 mikroPascal PRO for PIC32 Glcd Rectangle Round Edges Fill Prototype procedure Glcd Rectangle Round Edges Fill x upper left byte y upper left byte x bottom right byte y bottom right byte radius byte color byte
130. end j Creates new file and writes some data to it procedure M Create New File begin filename 7 A Cf Fat Set File Date 2005 6 21 10 35 0 Cf Fat Assign filename OxA0 Cf Fat Rewrite for loop 1 to 99 do begin UART1 Write file contents 0 loop div 10 48 file contents 1 loop mod 10 48 Cf Fat Write file contents LINE LEN 1 end end procedure M Create Multiple Files begin for loop2 B to Z do begin UART1 Write loop2 df filename 7 loop2 Cf Fat Set File Date 2005 6 21 10 35 0 Cf Fat Assign filename OxA0 Cf Fat Rewrite for loop 1 to 44 do begin file contents 0 file contents 1 loop div 10 48 loop mod 10 48 Set fil Set file date amp time info Will not find file and then create file To clear file and start with new data We want 5 files on the MMC card write data to the assigned file Creates many new files and writes data to them this line can slow down the performance set filename date amp time info find existing file or create a new one To clear file and start with new data write data to the assigned file Cf Fat Write file contents LINE LEN 1 end i i end end E Opens an existing file and rewrites it procedure M Open File _ Rewrite begin filename 7 Cry Cf Fat Assign filename Cf F
131. executing the first instruction within it cele e Executes the current program line then halts If the executed Sten Duer program line calls another routine the debugger will not step into it The whole routine will be executed and the debugger halts at the first instruction following the call Spass Hee Executes all remaining program lines within the subroutine The F8 E debugger halts immediately upon exiting the subroutine Executes the program until reaching the cursor position Ctrl F8 Toggle Breakpoint Toggle breakpoints option sets new breakpoints or removes those F5 already set at the current cursor position T E N T Related topics Run Menu Debug Toolbar 115 MikroElektronika mikoPascal PRO for PIC32 mikrolCD Debugger Example Here is a step by step mikroICD Debugger Example First you have to write a program We will show how the mikrolCD works using this example program Lcd Test LCD module connections var LCD RS sbit at LATDO bit var LCD EN sbit at LATD1 bit var LCD D4 sbit at LATBO bit var LCD D5 sbit at LATB1 bit var LCD D6 sbit at LATB2 bit var LCD D7 sbit at LATB3 bit var LCD RS Direction sbit at TRISDO bit var LCD EN Direction sbit at TRISD1 bit var LCD D4 Direction sbit at TRISBO bit var LCD D5 Direction sbit at TRISB1 bit var LCD D6 Direction sbit at TRISB2 bit var LCD D7 Direction sbit at TRISB3 bit
132. graphics and text display at the same time 0 T6963C ROM MODE XOR 15 T6963C ROM MODE XOR MikroElektronika 916 mikroPascal PRO for PIC32 Cursor sid T6963C cursor height 8 8 pixel height T6963C set cursor 0 0 Move cursor to top left T6963C cursor 0 Cursor off Draw solid boxes M T6963C box 0 0 239 8 T6963C WHITE T6963C box 0 119 239 127 T6963C WHITE Draw rectangles SIFDEF LINE DEMO T6963C rectangle 0 0 239 127 T6963C WHITE T6963C rectangle 20 20 219 107 T6963C WHI T6963C rectangle 40 40 199 87 T6963C WHITI T6963C rectangle 60 60 179 67 T6963C WHITI SENDIF E B H mH M gt Draw rounded edge rectangl SIFDEF LINE DEMO T6963C Rectangle Round Edges 10 10 229 117 12 T6963C WHIT T6963C Rectangle Round Edges 30 30 209 97 12 T6963C WHITI T6963C Rectangle Round Edges 50 50 189 77 12 T6963C WHITI SENDIF me CP me Cop oe Draw filled rounded edge rectangl uu SIFDEF FILL DEMO T6963C Rectangle Round Edges Fill 10 10 229 117 12 T6963C WHITE T6963C Rectangle Round Edges Fill 20 20 219 107 12 T6963C BLACK T6963C Rectangle Round Edges Fill 30 30 209 97 12 T6963C WHITE T6963C Rectangle Round Edges Fill 40 40 199 87 12 T6963C BLACK T6963C Rectangle Round Edges Fill 50 50 189 77 12
133. gt 0 then begin Inc curs pw If RB13 is pressed perform the Partial image TE else SIFD curs 3 then curs 0 case curs of 0 no cursor T6963C cursor 0 1 begin blinking cursor T6963C cursor 1 T6963C cursor blink 1 end 2 begin non blinking cursor T6963C cursor 1 T6963C cursor blink 0 end end Delay ms 300 demonstration EF PARTIAL IMAGE DEMO if RB13 bit I begin T6963C_setGrPanel 0 T6963C setTxtPanel 0 T6963C tx T6963C se T6963C setTxtPanel 0 T6963C graphics 1 T6963C text 1 T6963C displayGrPanel 1 T6963C write text txt2 5 15 T6963C ROM MODE XOR Delay 1sec then Fill 0 GrPanel 1 toc ct T6963C grFill 0 T6963C Partiallmage 0 0 64 64 240 128 mikroE 240x128 bmp Delay ms 1500 T6963C Partiallmage 0 0 128 128 240 128 mikroE 240x128 bmp Delay ms 1500 T6963C Partiallmage 0 0 240 128 240 128 mikroE 240x128 bmp Delay ms 1500 MikroElektronika 920 mikroPascal PRO for PIC32 T6963C txtFill 0 T6963C write text txt 0 0 T6963C write text txtl 0 15 end SENDIF Move cursor even if not visible di Inc cposx if cposx begin Cposx 0 Inc cposy if cposy cposy 0 end T6963C set cursor cposx cposy T6963C ROM MODE XOR T6963C ROM MODE XOR T6963C txtCols then T6963C grHeigh
134. has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page set the CANSPI module into configuration mode wait inside CANSPISetOperationMode until this mode is set CANSPISetOperationMode CANSPI MODE CONFIG OxFF MikroElektronika 242 mikroPascal PRO for PIC32 CANSPIGetOperationMode constants or device datasheet for operation mode codes Requires The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page check whether the CANSPI module is in Normal mode and if it is do something if CANSPIGetOperationMode CANSPI MODE NORMAL then begin end CANSPIInit Prototype procedure CANSPIInit SJW BRP PHS EG2 PROPSEG CANSPI CONFIG FLAGS char Description Initializes the CANSPI module Stand Alone CAN controller in the CANSPI module is set to Disable CAN capture Continue CAN operation in Idle mode Do not abort pending transmissions Fcan clock 4 Tcy Fosc Baud rate is set according to given parameters CAN mode Normal Filter and mask registers IDs are set to zero Filter and mask message frame type is set according to CANSPI_ CONFIG FLAGS value SAM SEG2PHTS WAKFIL and DBEN bits are set according to CANSPI CONFIG FLAGS va
135. if no font is specified then default Font Gicd System5x7 font supplied with the library will be used Write text Hello world on the position 10 inside the page 2 Gled Write Text Hello world 10 2 1 For x axis and page layout explanation see schematic at the bottom of this page MikroElektronika 306 mikroPascal PRO for PIC32 Glcd Image Prototype procedure Glcd Image const image byte Description Displays bitmap on Glcd Parameters image image to be displayed Bitmap array can be located in both code and RAM memory due to the mikroPascal PRO for PIC32 pointer to const and pointer to RAM equivalency Nothing Requires Glcd needs to be initialized see Glcd Init routine Draw image my image on Glcd Glcd Image my image Use the mikroPascal PRO for PIC32 integrated Glcd Bitmap Editor Tools gt Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd Glcd Partiallmage Prototype procedure Glcd Partiallmage x left y top width height picture width picture height word const image byte Description Displays a partial area of the image on a desired location Parameters x left x coordinate of the desired location upper left coordinate y top y coordinate of the desired location upper left coordinate width desired image width height desired image height picture width width of the original image picture height h
136. if Cf Fat Init 0 then begin Delay ms 2000 wait for a while until the card is stabilized period depends on used CF card Test start VARTI Write Line Test Start Create New File SIFDEF COMPLETE EXAMPLE M Create Multiple Files M Open File Rewrite Open File Append Open File Read Delete File M Test File Exist M Create Swap File SENDIF UART1 Write Line Test End end else begin UART1 Write Line err txt If Note Cf Fat Init tries to initialize a card more than once id If card is not present initialization may last longer depending on clock speed end end MikroElektronika 216 mikroPascal PRO for PIC32 HW Connection VCC3 bonbnnnt pananantnnpninmp vec3 BER E FEF CIRG1S5 GND ove res CIRE6 RDO Cire L2 OSCRLATOR Cj oscif gt VCCE3 o B veca VCC3 El 28 98 muuuuuuuuugtiUuuUuUuuUU UU m m vcc g Y zm oio e BPRS SSRN BEE tastes A INRA ALAR Compact Flash Card J jw nett tet ts LJ eel ism r MG Ruo B Biever 10K vcc Pin diagram of CF memory card 211 MikroElektronika mikoPascal PRO for PIC32 Epson 1D13700 Graphic Lcd Library The mikroPascal PRO for PIC32 provides a library for working with Glcds based on E
137. index byte Description Accesses register space of the controller and sets the desired register Parameters index desired register number TFT module needs to be initialized See the TFT_Init routine Access register at the location 0x02 TFT Set_Index 0x02 TFT Write Command Prototype procedure TFT Write Command cmd byte Description Accesses data space and writes a command Parameters cmd command to be written TFT module needs to be initialized See the TFT Init routine Write a command TFT Write Command 0x02 TFT Write Data Prototype procedure TFT Write Data data word Description Writes date into display memory Parameters data data to be written TFT module needs to be initialized See the TFT Init routine Send data TFT Write Data 0x02 MikroElektronika 026 mikroPascal PRO for PIC32 TFT Set Active Prototype procedure TFT Set Active Set Index Ptr TTFT Set Index Ptr Write Command Ptr TIET Write Command Ptr Write Data Ptr TIFT Write Data Ptr Nothing Description This function sets appropriate pointers to a user defined basic routines in order to enable multiple working modes Parameters Set Index Ptr Set Index handler Write Command Ptr Write Command handler Write Data Ptr Write Data handler Example of establishing 16 bit communication between TFT display and PORTD PORTE of MCU procedur
138. instructions Example mpas 29 if yt k then 0x9D000000 0x87A30002 LH R3 2 SP 0x9D000004 0x87A20000 LH R2 O SP 0x9D000008 0x00431021 ADDU R2 R2 R3 0x9D00000C 0x10400002 BEQ R2 RO L SSA Test2 0x9D000010 0x70000000 NOP Proper Coding Recommendations To get the maximum out of the SSA user should regard the following rules during the coding process Routines should not contain too many parameters not more than 4 words Don t change the value of the parameter in the function body it is better to use a new local variable If the function1 parameters are passed as function2 parameters then parameter order should remain the same procedure f2 a integer b integer procedure fl x integer y integer routine call f2 x y x a and y b 1 to 1 and 2 to 2 is far more efficient than f2 y x y a and x b L to 2 and 2 to 1 Large amount of nested loops and complex structures as its members should be avoided When writing a code in assembly keep in mind that there are registers reserved exclusively for routine parameters Using goto and label statements in nested loops should be avoided Obtaining address of the local variable with the global pointer and using it to alter the variable s address should be avoided Notes emc1 files compiled with or without SSA enabled are fully compatible and can be used and mixed without any restrictions except function po
139. letter A Z function returns a lowercase letter Otherwise function returns an unchanged input parameter tolower A E returns a tolower b returns b 971 MikroElektronika mikoPascal PRO for PIC32 Conversions Library mikroPascal PRO for PIC32 Conversions Library provides routines for numerals to strings and BCD decimal conversions Library Dependency Tree Conversions C_String Library Routines You can get text representation of numerical value by passing it to one of the following routines ByteToStr ShortToStr WordToStr IntToStr LongToStr LongWordToStr FloatToStr WordToStrWithZeros IntToStrWithZeros LongWordToStrWithZeros LongIntToStrWithZeros ByteToHex ShortToHex WordToHex IntToHex LongWordToHex LongintToHex StrTolnt StrToWord The following functions convert decimal values to BCD and vice versa Bcd2Dec Dec2Bcd Bcd2Dec16 Dec2Bcd16 MikroElektronika 512 mikroPascal PRO for PIC32 ByteToStr Prototype procedure ByteToStr input byte var output array 3 of char Description Converts input byte to a string The output string is right justified and remaining positions on the left if any are filled with blanks Parameters input byte to be converted output destination string var t byte txt array 3 of char 24 ByteToStr t txt txt is 24 one blank here
140. loop 1 to 99 do We want 5 files on the MMC card begin UART1 Write file contents 0 loop div 10 48 file contents 1 loop mod 10 48 Mmc Fat Write file contents LINE LEN 1 write data to the assigned file end end Jl Creates many new files and writes data to them procedure M Create Multiple Files begin for loop2 B to Z do begin UART1 Write loop2 signal the progress filename 7 loop2 set filename Mmc Fat Set File Date 2011 1 12 11 9 0 Set file date amp time info Mmc Fat Assign filename 0xA0 find existing file or create a new on Mmc Fat Rewrite To clear file and start with new data for loop 1 to 44 do begin file contents 0 byte loop div 10 48 file contents 1 byte loop mod 10 48 Mmc Fat Write file contents LINE LEN 1 write data to the assigned file end end end jd mium miis Opens an existing file and rewrites it procedure M Open File Rewrite begin filename 7 C Set filename for single file tests Mmc_Fat_Assign filename 0 Mmc Fat Rewrite for loop 1 to 55 do begin file contents 0 byte loop div 10 48 file contents 1 byte loop mod 10 48 Mmc Fat Write file contents 42 write data to the assigned file end end 341 MikroElektronika mikoPascal PRO for PIC32 f eec ES Opens an existing file and appends data to it Ri and alters the date time st
141. mail client with message ready for sending Review the information you have entered and add the comment if you deem it necessary Please do not modify the subject line Upon receiving and verifying your request we will send the license key to the e mail address you specified in the form After Receving the License Key The license key comes as a small autoextracting file just start it anywhere on your computer in order to activate your copy of compiler and remove the demo limit You do not need to restart your computer or install any additional components Also there is no need to run the mikroPascal PRO for PIC32 at the time of activation MikroElektronika 34 mikroPascal PRO for PIC32 Important The license key is valid until you format your hard disk In case you need to format the hard disk you should request a new activation key Please keep the activation program in a safe place Every time you upgrade the compiler you should start this program again in order to reactivate the license 35 MikroElektronika mikroPascal PRO for PICS2 mikroPascal PRO for PIC32 Main Menu Options Available Main Menu options are m F E E E S E E E F T IL T a Related topics Keyboard shortcuts Toolbars 3 MikroElektronika mikoPascal PRO for PIC32 File File Menu Options The File menu is the main entry point for manipulation with the source files L New Unit Ctr N Open Ct
142. manual negotiation 431 MikroElektronika mikoPascal PRO for PIC32 Requires Global variables SPI Ethernet 243600 CS Chip Select line SPI Ethernet 243600 CS Direction Direction of the Chip Select pin SPI Ethernet 245600 RST Reset line SPI Ethernet 24j600 RST Direction Direction of the Reset pin must be defined before using this function The SPI module needs to be initialized See the SPIx_Init and SPIx Init Advanced routines SPI Ethernet ENC24J600 module connections var SPI Ethernet 243600 CS sbit at RFI bit var SPI Ethernet 247600 CS Direction sbit at TRISF1 bit var myMacAddr array 6 of byte my MAC address myIpAddr array 4 of byte my IP addr myMacAddr 0x00 myMacAddr 0x14 myMacAddr OxA5 myMacAddr 0x76 myMacAddr 0x19 myMacAddr i x3F myIpAddr 0 1927 myIpAddr 168 1 60 myIpAddr myIpAddr 2 3 SPIL INITE SPI Ethernet 243600 Init myMacAddr myIpAddr SPI Ethernet _ 24j600 MANUAL EGOTIATION and SPI Ethernet 245600 FULLDUPLEX and SPI Ethernet 243600 PD100 MikroElektronika 432 mikroPascal PRO for PIC32 SPI Ethernet 24j600 Enable Prototype procedure SPI Ethernet 243600 Enable enFlt word Description This is MAC module routine This routine enables appropriate network traffic on the ENC24J600 module by the means of it s receive filters unicast multicas
143. memory location var p word A pointer can be assigned to another pointer However note that only the address not the value is copied Once you modify the data located at one pointer the other pointer when dereferenced also yields modified data Pointers and memory spaces Pointers can point to data in any available memory space Pointers can reside in any available memory space except in program code memory space MikroElektronika 204 mikroPascal PRO for PIC32 var ptrl const byte ptrl pointer in data space pointing to a byte in code space var ptr2 const volatile sfr byte rx ptr2 is pointer in rx space pointing to a pointer in code space pointing to volatile byte in sfr space var ptr3 data byte code error pointers can not be placed in code Space Due to backward compatibility pointers to program memory space can also be declared within constant declaration block using keyword const program const ptr constant array will be stored in program memory const b array array 5 of byte 1 2 3 4 5 const ptr byte ptr is pointer to program memory space begin pir b array ptr now points to b array 0 PORTA ptr ptr ptr 3 ptr now points to b array 3 PORTA ptr end This leads to equality of the following declarations var ptrl const byte ptrl pointer in data space pointing to a byte in code space const ptr2 byte ptr2 pointer in
144. mikoPascal PRO for PIC32 RS485Slave Init Prototype procedure RS485Slave Init slave address byte Initializes MCU as a Slave for RS 485 communication Slave address Slave address Requires Global variables R8485 rxtx pin this pin is connected to RE DE input of RS 485 transceiver see schematic at the bottom of this page RE DE signal controls RS 485 transceiver operation mode Valid values 1 for transmitting and 0 for receiving RS485 rxtx pin direction direction of the RS 485 Transmit Receive pin must be defined before using this routine UART HW module needs to be initialized See UARTx Init Initialize MCU as a Slave with address 160 RS485 module pinout var RS485 rxtx pin sbit at RF2 bit transmit receive control set to PORTC B2Z var RS485 rxtx pin direction sbit at TRISF2 bit End of RS485 module pinout UART1 Init 9600 initialize UART1 module RS485Slave Init 160 intialize MCU as a Slave for RS 485 communication with address 160v MikroElektronika 310 mikroPascal PRO for PIC32 RS485Slave Receive Prototype procedure RS485Slave Receive var data buffer array 20 of byte Description Receives messages from Master If Slave address and Message address field don t match then the message will be discarded Messages are multi byte so this routine must be called for each byte received Parameters data buffer 6 byte buffer for storing received data in the foll
145. module routine It is internally called by the library The user accesses to the UDP request by using some of the SPI Ethernet 24j600 get routines The user puts data in the transmit buffer by using some of the SPI Ethernet 24j600 put routines The function must return the length in bytes of the UDP reply or 0 if nothing to transmit If you don t need to reply to the UDP requests just define this function with a return 0 as single statement Parameters remoteHost client s IP address remotePort client s port localPort port to which the request is sent reqLength UDP request data field length flags Structure consisted of two bit fields Copy Code To Clipboard type TEthj600PktFlags record canCloseTCP boolean flag which closes socket not relevant to UDP isBroadcast boolean flag which denotes that the IP package has been received via subnet broadcast address end 0 there should not be a reply to the request Length of UDP reply data field otherwise Ethernet module has to be initialized See SPI Ethernet 24600 Init This function is internally called by the library and should not be called by the user s code The function source code is provided with appropriate example projects The code should be adjusted by the user to achieve desired reply SPI Ethernet 24j600 getlpAddress Prototype function SPI Ethernet 245 600 getIpAddress word This routine should be used when DHCP server is pre
146. ms 100 Wait for keyboard to finish UART1 Write Text Ready Ready UART1 Write 13 Line Feed UART1 Write 10 Carriage return while TRUE do Endless loop begin if Ps2 Key Read keydata special down then If data was read from PS 2 begin if down lt gt 0 and keydata 16 then Backspace begin UART1 Write 0x08 Send Backspace to usart terminal end else if down lt gt 0 and keydata 13 then Enter begin UART1 Write 10 Send carriage return to usart terminal UART1 Write 13 Uncomment this line if usart terminal also expects line feed for new line transition end else if down lt gt 0 and special 0 and keydata lt gt 0 then Common key read begin UART1 Write keydata Send key to usart terminal end end Delay ms 1 Debounce period end end 361 MikroElektronika mikoPascal PRO for PIC32 HW Connection OSCILLATOR PS2 t CONNECTOR NC CLK NC DATA Example of PS2 keyboard connection PWM Library The CCP module is available with a number of PIC32 MCUs mikroPascal PRO for PIC32 provides a library which simplifies using of the PWM HW Module Important PWM module uses either Timer2 or Timer3 module Library Routines PWM Init PWM Init Advanced PWM Set Duty PWM Start PWM Stop MikroElektronika 362 mikroPascal PRO for PIC32 PWM Init Prototype function PWM Init freq hz dword enabl
147. n graphic enable disable parameter Valid values 0 disable graphic dispaying and 1 enable graphic displaying Toshiba Glcd module needs to be initialized See SPI T6963C Config routine enable graphic displaying SPI T6963C graphics 1 SPI T6963C text Prototype procedure SPI T6963C text n word Enable disable text displaying Parameters n text enable disable parameter Valid values 0 disable text dispaying and 1 enable text displaying Toshiba Glcd module needs to be initialized See SPI T6963C Config routine enable text displaying SPI T6963C text 1 MikroElektronika 490 mikroPascal PRO for PIC32 SPI T6963C cursor Prototype procedure SPI T6963C cursor n word Description Set cursor on off Parameters n on off parameter Valid values 0 set cursor off and 1 set cursor on 1 Nothing Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine set cursor on SPI T6963C cursor SPI T6963C cursor blink Prototype procedure SPI T6963C cursor blink n word Description Enable disable cursor blinking Parameters n cursor blinking enable disable parameter Valid values 0 disable cursor blinking and 1 enable cursor blinking Nothing Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine enable cursor blinking SPI T6963C cursor blink l1 Library Example The following dr
148. of TFT Library 525 Library Routines 526 TFT Init 527 TFT_Set_Index 528 TFT Write Command 528 TFT Write Data 528 TFT Set Active 529 TFT Set Font 530 TFT Write Char 531 TFT Write Text 531 TFT Fill Screen 532 TFT Dot 533 TFT Set Pen 534 TFT Set Brush 535 TFT Line 537 TFT H Line 538 TFT V Line 538 TFT Rectangle 538 TFT Rectangle Round Edges 539 TFT Circle 539 TFT Image 539 TFT Partial Image 540 TFT Image Jpeg 540 TFT RGBToColor16bit 541 TFT Color16bitToRGB 541 HW Connection 542 Touch Panel Library 543 Library Dependency Tree 543 21 MikroElektronika mikoPascal PRO for PIC32 External dependencies of Touch Panel Library 543 Library Routines 543 TP_Init 544 TP_Set_ADC_Threshold 544 TP_Press_ Detect 545 TP_Get_Coordinates 546 TP_Calibrate_Bottom_Left 546 TP Calibrate Upper Right 546 TP Get Calibration Consts 547 TP Set Calibration Consts 547 Touch Panel TFT Library 548 Library Dependency Tree 548 External dependencies of Touch Panel TFT Library 548 Library Routines 548 TP TFT Init 549 TP TFT Set ADC Threshold 549 TP TFT Press Detect 550 TP TFT Get Coordinates 551 TP TFT Calibrate Min 551 TP TFT Calibrate Max 551 TP TFT Get Calibration Consts 552 TP TFT Set Calibration Consts 552 HW Connection 553 UART Library 554 Library Routines 554 UARTXx Init 555 UARTx Init Advanced 556 UARTx Data Ready 557 UARTx Tx Idle 557 UARTx Read 558 UARTx Read Text 559 UARTx Write 560 UARTx Write Text 560 UART Set Active 561 Libr
149. of alternatives for a pattern using to separate them so that bit bat bot will match any of bit bat or bot in the target string as would b i a o t The first alternative includes everything from the last pattern delimiter or the beginning of the pattern up to the first and the last alternative contains everything from the last to the next pattern delimiter For this reason it s common practice to include alternatives in parentheses to minimize confusion about where they start and end Alternatives are tried from left to right so the first alternative found for which the entire expression matches is the one that is chosen This means that alternatives are not necessarily greedy For example when matching rou rout against routine only the rou part will match as that is the first alternative tried and it successfully matches the target string this might not seem important but it is important when you are capturing matched text using parentheses Also remember that is interpreted as a literal within square brackets so if you write bit bat bot you re really only matching biao Examples rou tine te matches strings routine or route Metacharacters Subexpressions The bracketing construct may also be used for define regular subexpressions Subexpressions are numbered based on the left to right order of their opening parenthesis The first subexpression has number 1
150. of byte user IP address buffer memcpy ipAddr SPI Ethernet _getIpAddress 4 fetch IP address User should always copy the IP address from the RAM Ter returned by this routine into it s own IP address buffer These locations should not be altered by the user in any case Ethernet getGwlpAddress LN Prototype function SPI Ethernet getGwIpAddress This routine should be used when DHCP server is present on the network to fetch assigned gateway IP address Returns Pointer to the global variable holding gateway IP address Ethernet module has to be initialized See SPI Ethernet Init v gwlIpAddr array 4 of byte user gateway IP address buffer memcpy gwIpAddr SPI Ethernet getGwIpAddress 4 fetch gateway IP address User should always copy the IP address from the RAM location returned by this routine into it s own gateway IP address buffer These locations should not be altered by the user in any case Ethernet getDnslpAddress Pratotyps Prototype function SPI Ethernet getDnsIpAddress This routine should be used when DHCP server is present on the network to fetch assigned DNS IP address Retums Pointer to the global variable holding DNS IP address Ethernet module has to be initialized See SPI Ethernet Init v dnsIpAddr array 4 of byte user DNS IP address buffer memcpy dnsIpAddr SPI Ethernet getDnsIpAddress 4 fetch DNS server address User should alway
151. of different type result does not match the declared function return type Promotion When operands are of different types implicit conversion promotes the less complex type to more complex type taking the following steps bit gt byte char byte char gt word short gt integer short longint integer longint integer real Higher bytes of extended unsigned operand are filled with zeroes Higher bytes of extended signed operand are filled with bit sign if number is negative fill higher bytes with one otherwise with zeroes For example var a byte b word a i SPP b a a is promoted to word b becomes 00FF 211 MikroElektronika mikoPascal PRO for PIC32 Clipping In assignments and statements that require an expression of particular type destination will store the correct value only if it can properly represent the result of expression i e if the result fits in destination range If expression evaluates to a more complex type than expected excess of data will be simply clipped higher bytes are lost var i byte j word ff wad j SFFOF L pem i i becomes SOF higher byte SFF is lost Explicit Conversion Explicit conversion can be executed at any point by inserting type keyword byte word short integer longint or real ahead of an expression to be converted The expression must be enclosed in parentheses Explicit conversion can be performed only on the operand right of
152. of statements to be executed upon calling the procedure Calling a procedure A procedure is called by its name with actual arguments placed in the same sequence as their matching formal parameters The compiler is able to coerce mismatching arguments to the proper type according to implicit conversion rules Upon procedure call all formal parameters are created as local objects initialized by the values of actual arguments Procedure call is a self contained statement Example Here s an example procedure which transforms its input time parameters preparing them for output on Lcd procedure time prep var sec min hr byte begin Sec sec and F0 shr 4 10 sec and SOF min min and SFO shr 4 10 min and SOF hr hr and SFO shr 4 10 hr and SOF end A function can return a complex type Follow the example bellow to learn how to declare and use a function which returns a complex type MikroElektronika 198 mikroPascal PRO for PIC32 Example This example shows how to declare a function which returns a complex type program Example type TCircle record Record CenterX CenterY word Radius byte end var MyCircle TCircle Global variable function DefineCircle x y word r byte TCircle DefineCircle function returns a Record begin result CenterX x result CenterY y result Radius r end begin MyCircle DefineCircle 100 200 30 Ge
153. of the lower right rectangle corner Valid values 0 127 y bottom right y coordinate of the lower right rectangle corner Valid values 0 63 round radius radius of the rounded edge color color parameter Valid values 0 2 The parameter color determines the color of the rectangle border 0 white 1 black and 2 inverts each dot Nothing Glcd needs to be initialized see SPI Glcd Init routine Draws a filled rounded edge rectangle between dots 5 5 and 40 40 with the edge radius of 12 SPI Glcd Rectangle Round Edges 5 5 40 40 12 1 453 MikroElektronika mikoPascal PRO for PIC32 SPI Glcd Box Prototype procedure SPI Glcd Box x upper left y upper left x bottom right Y bottom right color byte Draws a box on Glcd Parameters x upper left x coordinate of the upper left box corner Valid values 0 127 y upper left y coordinate of the upper left box corner Valid values 0 63 x bottom right x coordinate of the lower right box corner Valid values 0 127 y bottom right y coordinate of the lower right box corner Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the color of the box fill O white 1 black and 2 inverts each dot tms Nohing o pass Draw a box between dots 5 15 and 20 40 SPI Gled Box 5 15 20 40 1 SPI Glcd Circle Prototype Dc SPI Gled Circle x center y center radius integer color byte
154. on boards with MCP2515 or MCP2510 via SPI interface The CAN is a very robust protocol that has error detection and signalization self checking and fault confinement Faulty CAN data and remote frames are re transmitted automatically similar to the Ethernet Data transfer rates depend on distance For example 1 Mbit s can be achieved at network lengths below 40m while 250 Kbit s can be achieved at network lengths below 250m The greater distance the lower maximum bitrate that can be achieved The lowest bitrate defined by the standard is 200Kbit s Cables used are shielded twisted pairs CAN supports two message formats Standard format with 11 identifier bits and Extended format with 29 identifier bits Important Consult the CAN standard about CAN bus termination resistance An effective CANSPI communication speed depends on SPI and certainly is slower than real CAN The library uses the SPI module for communication User must initialize appropriate SPI module before using the SPI Graphic Lcd Library For MCUs with multiple SPI modules it is possible to initialize both of them and then switch by using the SPI Set Active routine Number of SPI modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Library Dependency Tree CANSPI 9 spr External dependencies of CANSPI Library The following variables must be defined in all projects
155. one place to another e g from your work computer to your home computer Often project contains complicated search paths files involved within your project could be in a different folders even on different hard disks so it is very likely that some files will be forgotten during manual relocation In order to simplify this Export Project gives you opportunity to do this task automatically To open Export Project from Project menu select Export Project or hit Ctrl Alt E The following window will appear Export Project Select project to export oPascal PRO for PIC32 Examples Development SystemslLV32MX v6 LCD COG 2x16 1LCD mpp32 amp Select destination Folder D Project CJ In the empty input boxes current location and the destination folder of the desired project should be entered By default currently active project will be set for export You can change it any time by clicking the Open Button Once you have entered the appropriate data click Export Project button After exporting is done and if everything was OK you ll receive a message Information 1 Project successfully exported You have successfully exported the project All files From the project are now copied to D Project Now Export Project has copied all project files into desired folder and changed project search paths so you can easily move the entire folder to another location and run the project 103 Mikro
156. only in those parts of the procedure where they have useful value eg on entering the procedure variable isn t available until its definition Variables can be allocated in one part of the procedure in register W4 and in another part of the procedure in register W2 if the optimizer estimates that it is better that way That means that the local variable has no static address Warning Messages Enhancement Besides the smaller code SSA also deals with the intensive code analysis which in turn has the consequence in enhancing the warning messages For example compiler will warn the user that the uninitialized variable is used void main int y if y Variable y might not have been initialized PORTD 0 Related topics Code Optimization PIC32 Specifics mikroPascal PRO for PIC32 specifics Memory type specifiers MikroElektronika 164 mikroPascal PRO for PIC32 165 MikroElektronika mikoPascal PRO for PIC32 CHAPTER 7 PIC32 Specifics In order to get the most from the mikroPascal PRO for PIC32 compiler the user should be familiar with certain aspects of PIC32 MCU This knowledge is not essential but it can provide a better understanding of the PIC32 s capabilities and limitations and their impact on the code writing as well MikroElektronika 166 mikroPascal PRO for PIC32 Types Efficiency First of all the user should know that PIC32 s ALU which performs arithmetic operations
157. operator is the bitwise complement of the operand In the binary representation of the result every bit has the opposite value of the same bit in the binary representation of the operand not bitwise complement unary inverts each bit Example not 0x1234 equals OxEDCB Address and Indirection Operator In the mikroPascal PRO for PIC32 address of an object in memory can be obtained by means of an unary operator To reach the pointed object we use an indirection operator on a pointer See Pointers section for more details 219 MikroElektronika mikoPascal PRO for PIC32 accesses a value indirectly through a pointer result is the value at the address to which operand points ie constructs a pointer to its operand See Pointers for more details on this subject Note Besides these sizeof and explicit conversion unary operators are supported also Sizeof Operator The prefix unary operator sizeof returns an integer constant that represents the size of memory space in bytes used by its operand determined by its type with some exceptions The operator sizeof can take either a type identifier or an unary expression as an operand You cannot use sizeof with expressions of function type incomplete types parenthesized names of such types or with lvalue that designates a bit field object Sizeof Applied to Expression If applied to expression the size of an operand is determined without evaluating the expressio
158. others which vary from country to country mikroElektronika Associates reserves all rights not specifically granted in this statement mikroElektronika Visegradska 1A 11000 Belgrade Europe Phone 381 11 36 28 830 Fax 381 11 36 28 831 Web www mikroe com E mail office mikroe com 31 MikroElektronika mikoPascal PRO for PIC32 Technical Support The latest software can be downloaded free of charge via Internet you might want to bookmark the page so you could check news patches and upgrades later on http www pic32compilers com In case you encounter any problem you are welcome to our support forums at www mikroe com forum Here you may also find helpful information hardware tips and practical code snippets Your comments and suggestions on future development of the mikroPascal PRO for PIC32 are always appreciated feel free to drop a note or two on our Wishlist In our Knowledge Base www mikroe com en kb you can find the answers to Frequently Asked Questions and solutions to known problems If you can not find the solution to your problem in Knowledge Base then report it to Support Desk www mikroe com en support In this way we can record and track down bugs more efficiently which is in our mutual interest We respond to every bug report and question in a suitable manner ever improving our technical support How to Register The latest version of the mikroPascal PRO for PIC32 is always available for do
159. passed to the function see Available Lcd Commands Available Lcd Commands Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected CD RETURN HOME 321 MikroElektronika mikoPascal PRO for PIC32 Library Example The following code demonstrates usage of the Lcd Library routines Copy Code To Clipboard program Lcd COG 2x16 LCD module connections var var var var var var var var var var var var LCD_RS sbit at LATB2 bit LCD_EN sbit at LATB3 bit LCD_D4 sbit at LATB4 bit LCD D5 sbit at LATB5 bit LCD D6 sbit at LATB6 bit LCD D7 sbit at LATB7 bit LCD RS Direction sbit at LCD EN Direction sbit LCD D4 Direction sbit LCD D5 Direction sbit LCD D6 Direction sbit LCD D7 Direction sbit at at at at at End LCD module pola ions var txtl array 16 of char txt2 array 10 of char txt3 array 8 of char txt4 array 7 of char i byte procedure Move Delay begin Delay ms 500 end begin CHECON 0x32 ADIPCFG OxFFFF txtl mikroElektronika txt2 LV32MX v6 txt3 Lcd4bit txt4 example Led_Init Lcd Cmd LCD CLEAR Lcd Cmd LCD CURSOR OFF LCD Out 1 6 txt3 LCD Out 2 6 txt4 Delay ms 2000 Lcd Cmd LCD CLEAR LCD Out 1 1 txtl Lcd Out 2 4 txt2 Delay ms 500 TRISB2 bit TRISB3 bit TRISB4 bit TRISB5 bit
160. power supply for these modules may be required Library uses the SPI module for communication The user must initialize the appropriate SPI module before using the SPI Lcd Library For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by using the SPI Set Active routine See the SPI Library functions This Library is designed to work with the mikroElektronika s Serial Lcd Adapter Board pinout see schematic at the bottom of this page for details Library Dependency Tree r Port Expander SPI Lcd I 1 Lcd Constants External dependencies of SPI Lcd Library The implementation of SPI Lcd Library routines is based on Port Expander Library routines External dependencies are the same as Port Expander Library external dependencies Library Routines SPI Lcd Config SPI Lcd Out SPI Lcd Out Cp SPI Lcd Chr SPI Lcd Chr Cp SPI Lcd Cmd MikroElektronika 462 mikroPascal PRO for PIC32 SPI Lcd Config Prototype procedure SPI Lcd Config DeviceAddress byte Description Initializes the Lcd module via SPI interface Parameters DeviceAddress SPI expander hardware address see schematic at the bottom of this page Nothing Requires Global variables SPExpanderCs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined bef
161. processed section can contain further conditional clauses nested to any depth each 1FDEF must be matched with a closing SENDIF Here is an example Uncomment the appropriate flag for your application SDEFINE resolution10 SDEFINE resolutionl12 SIFDEF resolution10j code specific to 10 bit resolution SELSE SIFDEF resolutionl12 lt code specific to 12 bit resolution ELSE default code SENDIF SENDIF 231 MikroElektronika mikoPascal PRO for PIC32 Unlike STFDEF TFNDEF checks if flag is not defined by means of SDEF INE thus producing the opposite results Include Directive 1 The I parameter directive instructs mikroPascal PRO for PIC32 to include the named text file in the compilation In effect the file is inserted in the compiled text right after the SI filename directive If filename does not specify a directory path then in addition to searching for the file in the same directory as the current unit mikroPascal PRO for PIC32 will search for file in order specified by the search paths To specify a filename that includes a space surround the file name with quotation marks I My file There is one restriction to the use of include files An include file can t be specified in the middle of a statement part In fact all statements between the begin and end of a statement part must exist in the same sourc
162. routines The user puts data in the transmit buffer by using some of the SPI Ethernet 24j600 put routines The function must return the length in bytes of the TCP reply or 0 if there is nothing to transmit If there is no need to reply to the TCP requests just define this function with return 0 as a single statement Parameters remoteHost client s IP address remotePort client s TCP port localPort port to which the request is sent regqLength TCP request data field length flags structure consisted of two bit fields Copy Code To Clipboard type TEthj600PktFlags record canCloseTCP boolean flag which closes socket isBroadcast boolean flag which denotes that the IP package has been received via subnet broadcast address end 0 there should not be a reply to the request Length of TCP reply data field otherwise Ethernet module has to be initialized See SPI Ethernet 24600 Init Example This function is internally called by the library and should not be called by the user s code The function source code is provided with appropriate example projects The code should be adjusted by the user to achieve desired reply MikroElektronika 438 mikroPascal PRO for PIC32 SPI_Ethernet_24j600_UserUDP Prototype function SPI Ethernet 245600 UserUDP var remoteHost array 4 of byte remotePort destPort reqLength word var flags TEthj600PktFlags word Description This is UDP
163. sec increments Parameters year buffer to store year attribute to Upon function execution year attribute is returned through this parameter month buffer to store month attribute to Upon function execution month attribute is returned through this parameter day buffer to store day attribute to Upon function execution day attribute is returned through this parameter hours buffer to store hours attribute to Upon function execution hours attribute is returned through this parameter mins buffer to store minutes attribute to Upon function execution minutes attribute is returned through this parameter The file must be assigned see Mmc Fat Assign var year word month day hours mins byte Mmc Fat Get File Date Modified year month day hours mins Mmc Fat Get File Size Returns Thsfuonreumsszeoacefe nbyes Requires MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init The file must be previously assigned See Mmc Fat Assign var my file size dword my fen size Mmc Fat Get File Size MikroElektronika 338 mikroPascal PRO for PIC32 Mmc Fat Get Swap File Prototype Parameters MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init function Mmc Fat Get Swap File sectors cnt dword var filename string 11 file attr byte dword This function is used to create a swap file of
164. set cursor 0 0 move cursor to top left SPI T6963C cursor 0 cursor off i Draw solid boxes y SPI T6963C box 0 0 239 8 SPI T6963C WHITE SPI T6963C box 0 119 239 127 SPI T6963C WHITE p Draw rectangles Tr SIFDEF LINE DEMO SPI T6963C rectangle SPI T6963C rectangle SPI T6963C rectangle SPI T6963C rectangle SENDIF 0 0 239 127 SPI T6963C WHITE 20 20 219 107 SPI T6963C WHITE 40 40 199 87 SPI T6963C WHITI 60 60 179 67 SPI T6963C WHIT my aa my t r I Draw rounded edge rectangl SIFDEF LINE DEMO SPI T6963C Rectangle Round Edges 10 10 229 117 12 SPI T6963C WHITE SPI T6963C Rectangle Round Edges 30 30 209 97 12 SPI T6963C WHITE SPI T6963C Rectangle Round Edges 50 50 189 77 12 SPI T6963C WHITE ENDIF my TA r my f 493 MikroElektronika mikoPascal PRO for PIC32 Draw filled rounded edge rectangl SIFDEF FILL DEMO SPI T6963C Rectangle Round Edges Fill 10 10 229 SPI T6963C Rectangle Round Edges Fill 20 20 219 SPI T6963C Rectangle Round Edges Fill 30 30 209 SPI T6963C Rectangle Round Edges Fill 40 40 199 SPI T6963C Rectangle Round Edges Fill 50 50 189 SENDIF Draw a Cross ME SIFDEF LINE DEMO
165. set newly acquired duty ratio end if RB1 bit 1 then button on RB1 pressed begin Delay ms 1 current duty current duty 5 decrement current duty if current duty pwm periodl then if we decrease current duty greater then possible pwm periodl value overflow current duty pwm periodl set current duty to max possible value MikroElektronika mikoPascal PRO for PIC32 PWM Set Duty current duty 1 set newly acquired duty ratio end if RB2 bit 1 then button on RB2 pressed begin Delay ms 1 current dutyl current dutyl 5 increment current dutyl if current dutyl pwm period2 then if we increase current dutyl greater then possible pwm period2 value current dutyl 0 xeset current dutyl value to zero PWM Set Duty current dutyl 2 set newly acquired duty ratio end if RB3 bit 1 then button on RB3 pressed begin Delay ms 1 current dutyl current dutyl 5 decrement current duty if current dutyl pwm period2 then if we decrease current dutyl greater then possible pwm periodi value overflow current dutyl pwm period2 set current duty to max possible value PWM Set Duty current dutyl 2 end Delay ms 2 slow down change pace a little end end HW Connection Z7 2e 1K CI LI 1K OSCILLATOR Y PIC32MX460F512L se vec o VCC3 i VCC3 PWM demonstration MikroElektronika 366
166. small stdcall stored string threadvar to try type unit until uses var virtual volatile while with write writeonly xdata xor ydata Also mikroPascal PRO for PIC32 includes a number of predefined identifiers used in libraries You can replace them by your own definitions if you plan to develop your own libraries For more information see mikroPascal PRO for PIC32 Libraries 183 MikroElektronika mikoPascal PRO for PIC32 Identifiers Identifiers are arbitrary names of any length given to functions variables symbolic constants user defined data types and labels All these program elements will be referred to as objects throughout the help don t get confused about the meaning of object in object oriented programming Identifiers can contain the letters a to z andA to Z underscore character _ is that the first character must be a letter or an underscore and digits from 0 to 9 The only restriction Case Sensitivity mikroPascal PRO for PIC32 is not case sensitive so Sum sum and su are equivalent identifiers Uniqueness and Scope Although identifier names are arbitrary according to the stated rules if the same name is used for more than one identifier within the same scope then error arises Duplicated names are illegal within same scope For more information refer to Scope and Visibility Identifier Examples Here are some valid identifiers temperature V1 Pressure no hit
167. starting position on x axis Valid values 0 127 FontWidth page num the number of the page on which character will be written Valid values 0 7 color color parameter Valid values 0 2 The parameter color determines the color of the character 0 white 1 black and 2 inverts each dot Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Use the SPI Glcd Set Font to specify the font for display if no font is specified then the default Font Glcd System5x7 font supplied with the library will be used Write character C on the position 10 inside the page 2 SPI Gled Write Char C 10 2 1 Notes For x axis and page layout explanation see schematic at the bottom of this page SPI Glcd Write Text Prototype procedure SPI Glcd Write Text var text array 40 of char x pos page num color byte Prints text on Glcd Parameters text text to be written x pos text starting position on x axis page num the number of the page on which text will be written Valid values 0 7 color color parameter Valid values 0 2 The parameter color determines the color of the text 0 white 1 black and 2 inverts each dot Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Use the SPI_Glcd_Set_Font to specify the font for display if no font is specified then the default Font Glcd System5x7 font supplied with the library will be used
168. success while HID Write 8writebuff 64 0 do Notes Function call needs to be repeated as long as data is not successfuly sent 563 MikroElektronika mikoPascal PRO for PIC32 HID_Disable eum Nothing SCS USB HID needs to be enabled before using this function See HID_Enable Example Hib pisapeQ Cd Notes Nme USB Interrupt Proc Prototype This routine is ised for servicing various USB bus events Should be called inside USB interrupt routine procedure USBlInterrupt iv IVT ADDR USBIINTERRUPT begin USB Interrupt Proce end Do not use this function with USB_Polling_Proc only one should be used To enable servicing through interrupt USB_ INTERRUPT constant should be set it is set by default in descriptor file MikroElektronika 564 mikroPascal PRO for PIC32 USB Polling Proc Prototype procedure USB Polling Proc Description This routine is used for servicing various USB bus events It should be periodically preferably every 100 microseconds Requires Nothing while TRUE do begin USB Polling Proc kk HID Read if kk lt gt 0 then begin for cnt 0 to 64 writebuff cnt readbuff cnt HID Write writebuff 64 end end Do not use this functions with USB_Interrupt_Proc To enable servicing by polling USB INTERRUPT constant should be set to 0 it is located in descriptor file Gen Enable Prototype procedure
169. the EEPROM Watch Window select Debug Windows EEPROM from the View drop down menu The EEPROM Watch Window shows current content of the MCU s internal EEPROM memory There are two action buttons concerning the EEPROM Watch Window Read EEPROM Reads data from MCU s internal EEPROM memory and loads it up into the EEPROM window Write EEPROM Writes data from the EEPROM window into MCU s internal EEPROM memory EEPROM Watch amp Read EEPROM Write EEPROM 123 MikroElektronika mikoPascal PRO for PIC32 Code Watch Window Note Code Watch Window is available only when mikrolCD is selected as a debugger To show the Code Watch Window select Debug Windows Code from the View drop down menu The Code Watch Window shows code hex format written into the MCU There is one action button concerning the Code Watch Window Read code Reads code from the MCU and loads it up into the Code Window Code reading is resources consuming operation so the user should wait until the reading is over Also you can set an address scope in which hex code will be read CODE Watch Address Scope 000000 008000 A75010 AS22CA 470060 A64010 A902CA A74010 asozca 2088co DLE PS G DLE 460010 AS02D6 A70010 A902D6 07FF96 470060 463010 A962CA DLE lt STX gt DL A73010 AS62CA 470060 462010 A942CA A72010 A842CA 470060 DLE 08 b G DLI A61010 A922CA A71010 A
170. the code is generated in the place of the call so the call doesn t count against the nested call limit Parameters Time In ms delay time in milliseconds Valid values constant values range of applicable constants depends on the oscillator frequency UCET S NNNM Example Delay ms 1000 One second pause a MikroElektronika 150 mikroPascal PRO for PIC32 VDelay ms Prototype procedure VDelay ms Time ms word Description Creates a software delay in duration of Time ms milliseconds Generated delay is not as precise as the delay created by Delay ms Time ms delay time in milliseconds var pause word vDelayi ms pause one second pause VDelay_advanced_ms Prototype procedure VDelay advanced ms time ms Current Fosc kHz word Description Creates a software delay in duration of time in ms milliseconds a variable for a given oscillator frequency Generated delay is not as precise as the delay created by Delay ms Note that Vdelay ms is library function rather than a built in routine it is presented in this topic for the sake of convenience Parameters time ms delay time in milliseconds Current _Fosc_kHz frequency in kHz pause 1000 fosc 10000 VDelay advanced ms pause fosc Generates approximately one second pause for a oscillator frequency of 10 MHz Delay Cyc Prototype procedure Delay Cyc x word y word Creates a delay based on MCU clock Dela
171. to be written Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C setPtr T6963C_grHomeAddr start T6963C ADDRESS POINTE T6963C_waitReady Prototype Pools the status byte and loops until Toshiba Glcd module is ready Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C waitReady 503 MikroElektronika mikoPascal PRO for PIC32 T6963C_fill delist Lh procedure T6963C fill v byte start len word Fills controller memory block with given byte Parameters v byte to be written start starting address of the memory block Len length of the memory block in bytes ums NM OOOO Example resesc 11 0x95 oxoore DE O Its None SOS T6963C_dot Prototype procedure T6963C_dot x y integer color byte Draws a dot in the current graphic panel of Glcd at coordinates x y Parameters x dot position on x axis y dot position on y axis color color parameter Valid values T6963C BLACK and T6963C WHITE mum Note Example T6963C dot x0 y0 pcolor ewe Mme O OOS MikroElektronika 504 mikroPascal PRO for PIC32 T6963C_write_char Prototype Writes a char in the current text panel of Glcd at coordinates x y Parameters procedure T6963C write char c x y mode byte c char to be written x char position on x axis y char position on
172. type i e Arithmetic Types and Pointers d 0x12345678 tmp Highest d Equals 0x12 MikroElektronika 146 mikroPascal PRO for PIC32 LoWord Prototype function LoWord val longint word Description The function returns low word of val The function does not interpret bit patterns of va1 it merely returns 16 bits as found in register Parameters val input value Returns Low word of val bits 15 0 s 0x12345678 tmp LoWord d Equals 0x5678 HiWord Prototype function HiWord val longint word Description The function returns high word of val The function does not interpret bit patterns of va1 it merely returns 16 bits as found in register Parameters val input value Parameters Returns High word of val bits 21 16 0x12345678 tmp HiWord d Equals 0x1234 14 MikroElektronika mikoPascal PRO for PIC32 Inc procedure Inc var par longint Rems nonn p 4 Inc p p is now 5 Dec procedure Dec var par longint tms Non OOOO Eum rs p is HOW 3 Notes Nae SS Chr Prototype function Chr code byte char Description Function returns a character associated with the specified character coae Numbers from 0 to 31 are the standard non printable ASCII codes This is an inline routine the code is generated in the place of the call meme mg SS SA Example c Chr 10
173. used in the Real Time mode Pressing F5 marks the line selected by the user for breakpoint F6 executes code until the breakpoint is reached After reaching the breakpoint Debugger halts Here in our example we will use breakpoints for writing mikroElektronika on Lcd char by char Breakpoint is set on Lcd Chr and the program will stop everytime this function is reached After reaching breakpoint we must press F6 again to continue the program execution J E began Watch Values ADPCFG OxFFFF a ar E E 3 F j text mikroElektronika Conyers oe Or m Ej 50 a Add Remove Properties k Add All kg Remove All e i A i Led Init Select variable from list Lcd Cmd LCD CLEAR wane 9 Led Cmd LCD CURSOR OFF Search for variable by assembly name E i _text 4 E ss for i 1 to 17 do V Peripherals Freeze begin G G 57 Lcd Chr i1 i text i 1 Name Value Address ms o TRIB eR text i 0x0800 PC 0x0002E2 71 06 ms MikroElektronika 118 mikroPascal PRO for PIC32 Breakpoints are divided into two groups hardware and software breakpoints The hardware breakpoints are placed in the MCU and they provide fastest debugging Number of hardware breakpoints is limited to 8 6 instruction 2 data If all hardware brekpoints are used then the next breakpoint will be software breakpoint These breakpoints are placed inside the mikrolCD and simulate hardware breakpoint
174. var S1D13700 A0 Direction sbit at TRISCO bit var S1D13700 RES Direction sbit at TRISC3 bit var S1D13700 CS Direction sbit at FRISC4 bit End of S1D13700 module connections init display for 320 pixel width 240 pixel height S1D13700 Init 320 240 MikroElektronika 280 mikroPascal PRO for PIC32 1D13700_Write_Command Prototype MR S1D13700 Write Command command byte Description Writes a command to S1D13700 controller Parameters command command to be issued aipi3900 cs BIGHT Cursor moves right after write to display aS memory STDISTOD CS LEFT Cursor moves left after write to display memory 1D13700 CS UP Cursor moves up after write to display memory STDi3700 C8 DOWN Cursor moves down after write to display am memory Selects the gray scale depth in bits per pixel bpp S1D13700 MEMWRITE Write to display memory S1D13700 MEMREAD Read from display memory Glcd module needs to be initialized See the S1D13700 Init routine Turn the display on S1D13700 Write Command S1D13700 DISP ON S1D13700 GRAYSCALE 281 MikroElektronika mikoPascal PRO for PIC32 S1D13700 Write Parameter Prototype procedure S 1D13700 Write Parameter parameter byte Description Writes a parameter to S1D13700 controller Parameters parameter parameter to be written Requires Glcd module needs to be initialized See the S1D13700 Init routine Previously a command must be sent th
175. w arr operator will return byte ptr arr arr operator will return array 10 of byte end If F is a routine a function or procedure F returns a pointer to F Related topics Pointer Arithmetic Pointer Arithmetic Pointer arithmetic in the mikroPascal PRO for PIC32 is limited to assigning one pointer to another comparing two pointers comparing pointer to zero adding subtracting pointer and an integer value subtracting two pointers Assignment and Comparison The simple assignment operator can be used to assign value of one pointer to another if they are of the same type Assigning the integer constant 0 to a pointer assigns a null pointer value to it Two pointers pointing to the same array may be compared by using relational operators lt gt lt lt gt and gt Results of these operations are the same as if they were used on subscript values of array elements in question 207 MikroElektronika mikoPascal PRO for PIC32 var ptrl byte ptr2 byte a array 10 of byte array a containing 10 elements of type byte begin ptrl Ga 4 ptr2 a 2 if ptrl ptr2 then won t be executed as 4 is not equal to 2 if ptrl gt ptr2 then will be executed as 4 is greater than 2 if ptrl ptr2 then if the value pointed to by ptrl is equal to the value pointed to by ptr2 if ptrl gt ptr2 then if the value
176. words A page of Flash is the smallest unit of memory that can be erased at a single time The program Flash array can be programmed in one of two ways Row programming with 128 instruction words at a time Word programming with 1 instruction word at a time The CPU stalls waits until the programming operation is finished The CPU will not execute any instruction or respond to interrupts during this time If any interrupts occur during the programming cycle they remain pending until the cycle completes Library Routines Flash Write Word Flash Write Row Flash Erase Page MikroElektronika 292 mikroPascal PRO for PIC32 Flash Write Word PIE procedure FLASH Erase32 flash address longimt Writes one 32 bit word in the program Flash memory on the designated address Parameters address address of the FLASH memory word wdata data to be written moes Nm Flash Write Row Prototype procedure FLASH Write Block flash address longint data address word Description Writes one row in the program Flash memory 128 32 bit words or 512 bytes on the TRUE address Parameters address address of the FLASH memory word rdata data to be written Notes None Flash Erase Page Prototype procedure FLASH Write Init flash address longint data address word Erases one page 8 rows 1024 32 bit word 4096 bytes from the program Flash memory address starting addres
177. 0 BELLS 8 G t 408010 784010 FB8000 781F80 07FF32 B1002F 200011 470060 lt DLE gt DLE x 408810 37FFEF 2088C0 400010 FA8000 060000 FAO0002 EF2000 DLE iy7 A SPC 984700 90400E E10468 310009 2001CO 781F80 07FF78 B1002F G SO O h lt EOT 07FF31 B3C011 470060 40C810 37FFF4 FA8000 060000 FAo002 19 lt BELL gt lt DC1 gt EF2000 984700 90400E E10468 310009 200180 781F80 O7FF67 SPC i G SO GC B1002F 07FF20 B3C011 470060 40C810 37FFF4 FA8000 060000 lt SPC gt lt BELL gt E 2088EF 20FFFO0 B7A020 200000 B7A034 200040 B72044 FAD0000 i SPC 8 j SPC SF 0203D8 000000 2FFFFO B7A2A8 O7FFID 2000C0 781F80 O7FF4F lt ETX gt lt STX gt 8 gl B1002F 208610 781F80 200060 781F80 200010 781F80 O7FF87 DLE f SPC lt B1006F 208690 781F80 200060 781F80 200020 781F80 O7FF7F o O f SPC US B1006F 200CC8 273987 ED200E 3AFFFE ED2010 3AFFFC 200010 o amp lt FF gt lt SPC gt 9 781F80 07FF35 B1002F 208700 781F80 200010 781F80 200010 US x5 j BELL 781F80 O7FF6D B1006F 208810 781F80 200050 781F80 200020 US xmj BELL o gt STATUS Idle A 131 MikroElektronika mikoPascal PRO for PIC32 Software Simulator Debugger Options Debugger Options ee Function Toolbar Description Key Icon Executes the current prog
178. 1 Write 0x1234 oes None 155 MikroElektronika mikoPascal PRO for PIC32 DoGetDateTime Use the Get DateTime to get date and time of compilation as string in your code Retums Sting with date and tne when tis routine Beompled Example ecr Genere OOOO Moes None ooo GetVersion Retuns Sring wan curent comgierveson LEE GetVersion for example str will take the value of 8 2 1 6 Notes None SSCS KVAO TO KVA1 function KVAO TO KVAl Address dword dword Rems VrwdaddesiWeKSEGL o Noting Example address KVAO TO KVA1 0x9FC00000 ees None CS MikroElektronika 156 mikroPascal PRO for PIC32 KVA1 TO KVAO Prototype function KVA1 TO KVAO Address dword dword Function converts virtual address from KSEG 1 to the virtual address in the KSEGO Desired Virtual address in the KSEG1 meme vases 7 Example address KVAl TO KVAO 0xBFCO0000 me None KVA TO PA function KVA TO PA Address dword dword eme aroni Example address KVA TO PA 0xBFC00000 notes None PA TO KVAO function PA TO KVAO Address dword dword Runs oe a a Example address PA TO KVAO 0x1D000000 Naes None SSS PA_TO_KVA1 function PA TO KVA1 Address dword dword eme vaaan UOO Example address PA TO KVA1 0x1D000000 ets None OOO OOO O 157 MikroElektronika mikoPascal PRO for PIC32
179. 1 if the data has been transmitted 0 otherwise Requires Routine requires at least one UART module Used UART module must be initialized before using this routine See UARTx Init and UARTx_Init_ Advanced routines If the previous data has been shifted out send next data if UART1 Tx Idle 1 then UART1 Write data ul UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 599 MikroElektronika mikoPascal PRO for PIC32 UARTx_Read a function UARTx Read word The function receives a BE via UART Use the UARTx Data Ready function to test if data is ready first Returns Received byte Requires Routine requires at least one UART module Used UART module must be initialized before using this routine See UARTx Init and UARTx_Init_ Advanced routines UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library var receive word read data if ready if UART1 Data Ready receive VAR
180. 1 line or modify the entire PORTB register in a single line PORTB 0b00000011 This problem can be avoided by using LATx register when writing to ports rather than using PORTx registers Writing to a LATx register is equivalent to writing to a PORTx register but readings from LATx registers return the data value held in the port latch regardless of the state of the actual pin For example lets analyze the following example LATB BO 1 LATB B1 1 The first line LATB BO 1 will be decoded like in this way READ LATB is read STORE Data is stored inside a temporary internal register in the MCU OIUre reau value Read from LATB c Discharged I capacitor capacitor Actual voltage levels on MCU pins are no longer relevant when using LATx for output MODIFY Data is modified to set the RBO bit WRITE LATB is written with the modified data The output driver for RBO turns on and the _ Modify value capacitor starts to charge Write gpa pc modified value Discharged 0 l capacitor capacitor MikroElektronika 174 mikroPascal PRO for PIC32 The second line LATB B1 1 will be decoded like in this way READ LATB is read STORE Since the voltage levels on MCU pins are no longer relevant we get the expected value Store read Expected value value Read from LATB T e capacitor Actual voltage levels on MCU pins are no longer relevant when using LATx for output MODIFY Data
181. 16 of byte SPI Ethernet getBytes buffer 0x100 16 read 16 bytes starting from address 0x100 Ethernet UserTCP Prototype function SPI Ethernet UserTCP var remoteHost array 4 of byte remotePort localPort reqLength word var flags TEthPktFlags word Description This is TCP module routine It is internally called by the library The user accesses to the TCP request by using some of the SPI Ethernet get routines The user puts data in the transmit buffer by using some of the SPI Ethernet put routines The function must return the length in bytes of the TCP reply or 0 if there is nothing to transmit If there is no need to reply to the TCP requests just define this function with return 0 as a single statement Parameters remoteHost client s IP address remotePort client s TCP port localPort port to which the request is sent regqLength TCP request data field length flags structure consisted of two bit fields Copy Code To Clipboard type TEthPktFlags record canCloseTCP boolean flag which closes socket isBroadcast boolean flag which denotes that the IP package has been received via subnet broadcast address end 0 there should not be a reply to the request a S of TCP reply data field otherwise Ethernet module has to be Ethernet module has to be initialized See SPI_Ethernet_Init See SPI Ethernet Init amie This function is inte
182. 1D13700 Init routine S1D13700 Rectangle Round Edges Fill 20 20 219 107 12 S1D13700 WHITE S1D13700 Circle Prototype procedure S1D13700 Circle x center word y center word radius word color byte Description Draws a circle on Glcd Parameters x center X coordinate of the circle center y center y coordinate of the circle center radius radius size color color parameter Valid values S1D13700 BLACK Black color S1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine S1D13700 Circle 120 64 110 S1D13700 WHITE MikroElektronika 290 mikroPascal PRO for PIC32 S1D13700 Circle Fill Prototype procedure 1D13700 Circle Fill x center word y center word radius word color byte Description Draws a filled circle on Glcd Parameters x center x coordinate of the circle center y center y coordinate of the circle center radius radius size color color parameter Valid values S1D13700 BLACK Black color 1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine S1D13700 Circle Fill 120 64 110 S1D13700 WHITE S1D13700 Image Prototype procedure S1D13700 Image const image byte Description Displays bitmap on Glcd Parameters image image to be displayed Bitmap array is located in code memory Note Image dimension must match the dis
183. 245600 doPacket byte Description This is MAC module routine It processes next received packet if such exists Packets are processed in the following manner ARP amp ICMP requests are replied automatically upon TCP request the SPI Ethernet 24j600 UserTCP function is called for further processing upon UDP request the SPI Ethernet 24j600 UserUDP function is called for further processing Parameters None 0 upon successful packet processing zero packets received or received packet processed successfully 1 upon reception error or receive buffer corruption ENC2 47600 controller needs to be restarted 2 received packet was not sent to us not our IP nor IP broadcast address 3 received IP packet was not IPv4 4 received packet was of type unknown to the library Ethernet module has to be initialized See SPI Ethernet 24j600 Init while true do Ethernet 243600 doPacket process received packets Ethernet 243600 doPacket must be called as often as possible in user s code SPI Ethernet 24j600 putByte Prototype procedure SPI Ethernet 243600 putByte v byte Description This is MAC module routine It stores one byte to address pointed by the current ENC24600 write pointer EWRPT Nothing Ethernet module has to be initialized See SPI Ethernet 24j600 Init var data byte SPI Ethernet 24 600 putByte data put an byte into ENC24J600 buffer
184. 32 includes the Tools tab which enables the use of shortcuts to external programs like Calculator or Notepad You can set up to 10 different shortcuts by editing Tool0 Tool9 83 MikroElektronika mikoPascal PRO for PIC32 Options Tool Name Notepad File Name C WINDOWS NOTEPAD EXE amp Parameters 1 Macro HEX FILE NAME I Full path and name of the out i Insert Shortcut F11 NT 3 Clear all fields C Close when finished cv Output settings By modifying Output Settings user can configure the content of the output files You can enable or disable for example generation of ASM and List file Also user can choose optimization level and compiler specific settings which include case sensitivity dynamic link for string literals setting described in mikroPascal PRO for PIC32 specifics Build all files as library enables user to use compiled library emc1 on any MCU when this box is checked or for a selected MCU when this box is left unchecked For more information on creating new libraries see Creating New Library MikroElektronika 84 mikroPascal PRO for PIC32 Options Edito Output Settings mikoPascal PRO for PIC32 Integrated Tools Active Comments Editor Active Comments Editor is a tool particularly useful when working with Lcd display You can launch it from the drop down menu Tools Active Comments
185. 34 StrToWord Prototype function StrToWord var input string 5 word Converts a string to word input string to be converted Retums Word variable Requires Input string is assumed to be the correct representation of a number The conversion will end with the first character which is not a decimal digit var ww word begin StrToword 65432 Bcd2Dec function Bcd2Dec bcdnum byte byte Returns comenteddemalvae y O O O var a b byte 22 Bcd2Dec a b equals 34 581 MikroElektronika mikoPascal PRO for PIC32 Dec2Bcd function Dec2Bcd decnum byte byte FReturns CometedBCDwe O OC SSS var a b byte 22 Dec2Bcd a b equals 34 Bcd2Dec16 function Bcd2Decl6 bcdnum word word Retums Converted decmalvae SSCS var a b word 0x1234 a equals 4660 Bcd2Decl6 a b equals 1234 Dec2Bcd16 Prototype function Dec2Bcdl6 decnum word word PRetums Converted decimalvawe SSCS var a b word 2345 Dec2Bcdl16 a b equals 9029 MikroElektronika 582 mikroPascal PRO for PIC32 Setjmp Library The Setjmp library contains functions and types definitions for bypassing the normal function call and return discipline Library Routines Setjmp Longjmp Setjmp Prototype function setjmp var env array 4 of word integer 0 if the return is from direct invoca
186. 4 4 received packet was of type unknown to the library Ethernet module has to be initialized See SPI Ethernet Init while true do begin SPI Ethernet doPacket process received packets end Notes SPI Ethernet doPacket must be called as often as possible in user s code SPI Ethernet putByte Prototype procedure SPI Ethernet putByte v byte Description This is MAC module routine It stores one byte to address pointed by the current ENC28J60 write pointer EWRPT Nothing Ethernet module has to be initialized See SPI Ethernet Init var data byte SPI Ethernet putByte data put an byte into ENC28J60 buffer 409 MikroElektronika mikoPascal PRO for PIC32 SPI Ethernet putBytes Prototype procedure SPI Ethernet putBytes ptr byte n word Description This is MAC module routine It stores requested number of bytes into ENC28760 RAM starting from current ENC28J60 write pointer EWRPT location Parameters ptr RAM buffer containing bytes to be written into ENC28760 RAM n number of bytes to be written Ethernet module has to be initialized See SPI Ethernet Init var buffer array 17 of byte buffer mikroElektronika SPI Ethernet putBytes buffer 16 put an RAM array into ENC28J60 buffer SPI Ethernet putConstBytes Prototype procedure SPI Ethernet putConstBytes const ptr byte n word
187. 4 of byte gateway router IP address ipMask array 4 of byte network mask for example 255 255 255 0 dnsIpAddr array 4 of byte DNS server IP address fob doe esee eh ede ee E oe e Ee ee e Ee Re Eee ede eoe Ee dee ee ROM constant strings oy const httpHeader string 30 HTTP 1 1 200 OK 10 Content type HTTP header const httpMimeTypeHTML string 11 text html 10 10 HTML MIME type const httpMimeTypeScript string 12 text plain 10 10 TEXT MIME type const httpMethod string 5 GET web page splited into 2 parts when coming short of ROM fragmented data is handled more efficiently by linker this HTML page calls the boards to get its status and builds itself with javascript sI const indexPage string 761 MikroElektronika 420 mikroPascal PRO for PIC32 lt meta http equiv refresh content 3 url http 192 168 20 60 lt HTML gt lt HEAD gt lt HEAD gt lt BODY gt lt h1 gt PIC32 ENC28J60 Mini Web Server lt h1 gt lt a href Reload a 4 lt script sro s secript lt table gt lt tr gt lt td valign top gt lt table border 1 style font size 20px font family terminal lt tr gt lt th colspan 2 ADC th tr X tr td ANO td td script document write AN0 script td tr lt tr gt lt td gt AN1 lt
188. 592 strspn 592 strncmp 592 strstr 593 strcspn 593 strpbrk 593 strrchr 593 Itrim 594 rtrim 594 strappendpre 594 strappendsuf 594 length 594 Time Library 595 Library Routines 595 Time dateToEpoch 595 Time epochToDate 596 Time dateDiff 596 Library Example 596 TimeStruct type definition 597 Trigon Library 598 Library Functions 598 acos 598 MikroElektronika 24 mikroPascal PRO for PIC32 asin 598 atan 599 atan2 599 ceil 599 cos 599 cosh 599 eval_poly 599 exp 600 fabs 600 floor 600 frexp 600 Idexp 600 log 600 log10 600 modf 601 pow 601 sin 601 sinh 601 sqrt 601 tan 601 tanh 601 Trigonometry Library 602 Library Routines 602 sinE3 602 cosE3 602 CHAPTER 10 603 Tutorials 603 Managing Project 603 Projects 603 New Project 604 New Project Wizard Steps 604 Customizing Projects 608 Managing Project Group 608 Add Remove Files from Project 608 Project Level Defines 609 Source Files 610 Managing Source Files 610 Creating new source file 610 Opening an existing file 610 Printing an open file 610 Saving file 610 Saving file under a different name 611 Closing file 611 Search Paths 611 Paths for Source Files mpas 612 MikroElektronika 29 mikoPascal PRO for PIC32 Edit Project 613 Clean Project Folder 614 Compilation 615 Output Files 615 Assembly View 615 Creating New Library 616 Multiple Library Versions 616 Frequently Asked Questions 617 Can use your compilers and programm
189. 7 SID13700 WHITE S1D13700 Rectangle Prototype procedure 1D13700 Rectangle x0 yO xl yl word pcolor byte Description Draws a rectangle on Glcd Parameters x0 X coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner pcolor color parameter Valid values S1D13700 BLACK Black color S1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine S1D13700 rectangle 20 20 219 107 S1D13700 WHITE MikroElektronika 288 mikroPascal PRO for PIC32 S1D13700 Box Prototype procedure 1D13700 Box x0 y0 xl yl word pcolor byte Description Draws a rectangle on Glcd Parameters x0 X coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner pcolor color parameter Valid values S1D13700 BLACK Black color S1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine S1D13700 Box 0 119 239 127 S1D13700 WHITE S1D13700 Rectangle Round Edges Prototype procedure S1D13700 Rectangle Round Edges x upper left word y upper left word x bottom right word y bottom right word roun
190. 9600 delim OK while TRUE do begin if UART1_Data_Ready 1 then begin VARTI Read Text txt delim 10 UART1 Write Text txt end end 997 MikroElektronika mikoPascal PRO for PIC32 UARTx_Write procedure UARTx Write data word tms Nothing oS Requires Routine requires at least one UART module Used UART module must be initialized before using this routine See UARTx Init and UARTx_Init_ Advanced routines var data byte data xlE UART1 Write data ul UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library UARTx Write Text Requires Routine requires at least one UART module Used UART module must be initialized before using this routine See UARTx Init and UARTx Init Advanced routines UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Read text until the sequence OK is received and send back what s been received Read text until the sequ
191. ANSPISetBaudRate CANSPISetMask and CANSPISetFilter expect one of these or a bitwise combination as their argument Copy Code To Clipboard const CANSPI CONFIG DEFAULT byte SFF Z4 TATA CANSPI CONFIG PHSEG2 PRG BIT byte 01 CANSPI CONFIG PHSEG2 PRG ON byte SFF if XZXXXXXI CANSPI CONFIG PHSEG2 PRG OFF byte SFE Z4 KILIKIA CANSPI CONFIG LINE FILTER BIT byte 02 CANSPI CONFIG LINE FILTER ON byte SFF ff XXXXXX lX CANSPI CONFIG LINE FILTER OFF byte S FD LT XOX CANSPI CONFIG SAMPLE BIT byte 04 CANSPI CONFIG SAMPLE ONCE byte SFF jf XXXXXLIXX CANSPI CONFIG SAMPLE THRICE byte SFB EL XXXXNOXX CANSPI CONFIG MSG TYPE BIT byte 08 CANSPI CONFIG STD MSG byte SFF XXXX1XXX CANSPI CONFIG XTD MSG byte SF7 XXXXOXXX CANSPI CONFIG DBL BUFFER BIT byte 10 CANSPI CONFIG DBL BUFFER ON byte SFF XXXAXXXX CANSPI CONFIG DBL BUFFER OFF byte SEF L XXK XXXX CANSPI CONFIG MSG BITS byte 60 CANSPI CONFIG ALL MSG byte SFF ff XiUXXXXX CANSPI CONFIG VALID XTD MSG byte SDF TI KLOKI CANSPI CONFIG VALID STD MSG byte BF X01XXXXX CANSPI CONFIG ALL VALID MSG byte 9F f f XO 0XXXXX MikroElektronika 250 mikroPascal PRO for PIC32 You may use bitwise AND s to form config byte out of these values For example Copy Code To Cli
192. Associates with a copy of your receipt DO NOT RETURN ANY PRODUCT UNTIL YOU HAVE CALLED MIKROELEKTRONIKA ASSOCIATES FIRST AND OBTAINED A RETURN AUTHORIZATION NUMBER This Limited Warranty is void if failure of Software has resulted from an accident abuse or misapplication Any replacement of Software will be warranted for the rest of the original warranty period or thirty 30 days whichever is longer TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW MIKROELEKTRONIKA ASSOCIATES AND ITS SUPPLIERS DISCLAIM ALL OTHER WARRANTIES AND CONDITIONS EITHER EXPRESSED OR IMPLIED INCLUDED BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY FITNESS FORA PARTICULAR PURPOSE TITLE AND NON INFRINGEMENT WITH REGARD TO SOFTWARE AND THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES MikroElektronika 30 mikroPascal PRO for PIC32 IN NO EVENT SHALL MIKROELEKTRONIKA ASSOCIATES OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL INCIDENTAL INDIRECT OR CONSEQUENTIAL DAMAGES WHATSOEVER INCLUDING WITHOUT LIMITATION DAMAGES FORLOSS OF BUSINESS PROFITS AND BUSINESS INFORMATION BUSINESS INTERRUPTION OR ANY OTHER PECUNIARY LOSS ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE PRODUCT OR THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES EVEN IF MIKROELEKTRONIKA ASSOCIATES HAS BEENADVISED OF THE POSSIBILITY OF SUCH DAMAGES INANY CASE MIKROELEKTRONIKA ASSOCIATES ENTIRE LIABILITY UNDER ANY PROVISION OF THIS LICENSE AGREEMENT SHALL BE LIMIT
193. B822CA 470060 A60010 A902CA A70010 DLE DLE DI AS02CA 2088C0 A60010 A802D6 A70010 A902D6 O7FF7C 2088C0 STX SPC D A60010 370002 07FF64 370001 O7FF86 FA8000 060000 FA0002 DLE STX 7 d j 37000F 200800 9FBF40 370019 200C00 9FBF40 370016 200940 SI 7 B5 SPC 9FBF40 370013 200D40 9FBF40 370010 200800 SFBF40 370000 DC3 7 CR 97B84E 10061 32FFEE 97884E E10062 32FFEE 97B84E E10063 N a iy2N b 32FFEE 97B84E E10064 32FFEE 37FFFO 97B83E 500061 570068 iy2N d iy28 y7 gt 408010 9FBF40 781F80 07FF9B B1002F 2088CO A10010 EF2000 lt DLE gt V US 980700 97B8AE 470060 408010 E00410 32000C 97B8AE 470060 BELL 8 G f 408010 784010 FB8000 781F80 07FF32 B1002F 200011 470060 DLE DLE Qx 408810 37FFEF 2088C0 aooo10 FA8000 o60000 FADD02 EF2000 DLE G i97 A SPC 984700 90400E E10468 310009 2001CO 781F80 07FF78 B1002F G SO Gh EOT 07FF31 B3C011 470060 40C810 37FFF4 FA8000 060000 FA0002 1 lt BELL gt DC1 EF2000 984700 90400E E10468 310009 200180 781F80 07FF67 SPC i G SO GE B1002F 07FF20 B3C011 470060 40C810 37FFF4 FAB8000 060000 SPC lt BELL gt lt C 2088EF 20FFF0 B7A020 200000 B7A034 200040 B72044 FAO0000 i SPC y SPC SF 0203D8 000000 2FFFFO B7A2AB O7FFID 2000C0 781F80 O7FF4F lt
194. C WHIT SPI T6963C BLACK SPI T6963C WHIT E m K E m Draw a sprite Select other graphic panel MikroElektronika 494 mikroPascal PRO for PIC32 SPI T6963C image 8mikroE 240x128 bmp SPI T6963C displayGrPanel 1 Delay ms 1000 SIFDEF PART IAL IMAGE DEMO SPI T6963C grFill 0 SPI T6963C Partiallmage 0 0 64 64 240 128 mikroE 240x128 bmp Display partial image Delay ms 1000 SPI T6963C graphics 0 SENDIF SPI T6963C image G8mikroE 240x128 bmp SPI T6963C graphics 1 SPI T6963C displayGrPanel 0 while TRUE do Endless loop begin i If RB8 is pressed toggle the display between graphic panel 0 and graphic 1 if RB8 bit lt gt 0 then begin Inc panel panel panel and 1 SPI T6963C setPtr SPI T6963C grMemSize SPI T6963C txtMemSize panel SPI T6963C GRAPHIC HOME ADDRESS SET Delay ms 300 end i If RB9 is pressed display only graphic panel else if RB9 bit lt gt 0 then begin SPI T6963C graphics 1 SPI T6963C text 0 Delay ms 300 end i If RB10 is pressed display only text panel E else if RB10 bit 0 then begin SPI T6963C graphics 0 SPI T6963C text 1 Delay ms 300 end p If RB11 is pressed display text and graphic panels 495 MikroElektronika mikoPascal PRO for PIC32 else if RB11 bit lt gt 0 then be
195. CANSPI Extra Board or similar hardware See connection example at the bottom of this page set the appropriate filter value and message type CANSPISetOperationMode CANSPI MODE CONFIG OxFF set CONFIGURATION mode CANSPI module must be in config mode for filter settings Set id of filter Bl FI to 3 CANSPISetFilter CANSPI FILTER B1 F1 3 CANSPI CONFIG XTD MSG 22 MikroElektronika mikoPascal PRO for PIC32 CANSPIRead Prototype function CANSPIRead var id longint var Data array 8 of byte var DataLen byte var CAN RX MSG FLAGS byte byte Description If at least one full Receive Buffer is found it will be processed in the following way Message ID is retrieved and stored to location provided by the id parameter Message data is retrieved and stored to a buffer provided by the data parameter Message length is retrieved and stored to location provided by the dataLen parameter Message flags are retrieved and stored to location provided by the CANSPI RX MSG FLAGS parameter 0 if nothing is received Parameters id message identifier address data an array of bytes up to 8 bytes in length dataLen data length address CANSPI RX MSG FLAGS message flags address For message receive flags format refer to CANSPI RX MSG FLACS constants See CANSPI RX MSG FLAGS constants pum OxFFFF if one of the Receive Buffers is full message received Requires The CANSPI module must b
196. CD_EN Enable signal pin LCD D7 Direction Direction of the Data 7 pin LCD D6 Direction Direction of the Data 6 pin LCD D5 Direction Direction of the Data 5 pin LCD D4 Direction Direction of the Data 4 pin LCD RS Direction Direction of the Register Select pin LCD EN Direction Direction of the Enable signal pin must be defined before using this function LCD module connections var LCD RS sbit at LATDO bit var LCD EN sbit at LATD1 bit var LCD D4 sbit at LATBO bit var LCD DS sbit at LATB1 bit var LCD D6 sbit at LATB2 bit var LCD D7 sbit at LATB3 bit var LCD RS Direction sbit at TRISDO bit var LCD EN Direction sbit at TRISD1 bit var LCD D4 Direction sbit at TRISBO bit var LCD D5 Direction sbit at TRISB1 bit var LCD DGE Direction sbit at TRISB2 bit var LCD D7 Direction sbit at TRISB3 bit End LCD module connections Lcd Inzt r 319 MikroElektronika mikoPascal PRO for PIC32 Lcd Out NRE procedure Lcd Out row column word var text string Prints text on Lcd starting from specified position Both string variables and literals can be passed as a text Parameters row starting position row number column Starting position column number text text to be written The Lcd module needs to be initialized See Lcd Init routine Z6 ls text Hello on Lcd starting from row 1 column 3 Lcd Out 3 Herrot yj moes None Lcd Out Cp
197. CK MikroElektronika 284 mikroPascal PRO for PIC32 S1D13700 Display Cursor Prototype procedure S1D13700 Display Cursor mode byte Description Displays cursor Parameters mode mode parameter Valid values Glcd module needs to be initialized See the S1D13700 Init routine set curser on 1D13700 Display Cursor S1D13700 CURSOR ON S1D13700 Write Char Prototype procedure 1D13700 Write Char c char x word y word mode byte Description Writes a char in the current text layer of Glcd at coordinates x y Parameters c char to be written x char position on x axis column y char position on y axis row mode mode parameter Valid values In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons CSI URBES NOR In this mode the text and graphics data are combined via the logical exclusive OR S1p13900 OVEHERY AND The text and graphic data shown on display are combined via the logical AND function S1D13700 OVERLAY OR S1D13700 Write Char A 22 23 81D13700 OVERLAY OR Glcd module needs to be initialized See the S1D13700 Init routine 285 MikroElektronika mikoPascal PRO for PIC32 S1D13700 Write Text Prototype procedure 1D13700 Write Text var str string x y word mode byte Description Writes tex
198. D_PATCHREV CP0_EBASE_CPUNUM CP0_CONFIG_AT CP0_CONFIG_UDI CP0_CONFIG1_CA CP0_CONFIG1_DA CP0_CONFIG1_IS CP0_CONFIG3_SM CP0_CONFIG3_M CP0_DEBUG_DIB CP0_DEBUG_NOSST CPO DEBUG IEXI CP0 DEBUG COUNTDM CPO DEBUG DM TRACECONTROL ASD CP0 TRACECONTROL D TRACECONTROL2 SYP CP0_TRACEBPC_IBPON CP0_DEBUG2_TUP CFO TRACECENTROLZ TH 3 3 Om TRACECONTROLASD OPO TRACECONTROL U CPO TRACECONTROL2 SYP cro TRACECONTROL2 TBU MikroElektronika 160 mikroPascal PRO for PIC32 Code Optimization Optimizer has been added to extend the compiler usability cut down the amount of code generated and speed up its execution The main features are Constant folding All expressions that can be evaluated in the compile time i e constant are being replaced by their results 3 5 gt 8 Constant propagation When a constant value is being assigned to a certain variable the compiler recognizes this and replaces the use of the variable by constant in the code that follows as long as the value of a variable remains unchanged Copy propagation The compiler recognizes that two variables have the same value and eliminates one of them further in the code Value numbering The compiler recognizes if two expressions yield the same result and can therefore eliminate the entire computation for one of them Dead code ellimination The code snippets that are not being used elsewhere in the programme do not affect the final r
199. Description Draws a circle on Glcd Parameters x center x coordinate of the circle center Valid values 0 127 y center y coordinate of the circle center Valid values 0 63 radius radius size color color parameter Valid values 0 2 The parameter color determines the color of the circle line 0 white 1 black and 2 inverts each dot Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draw a circle with center in 50 50 and radius 10 SPI Glcd Circle 50 50 10 1 MikroElektronika 454 mikroPascal PRO for PIC32 SPI Gled Circle FIII Prototype procedure SPI Glcd Circle Fill x center integer y center integer radius integer color byte Draws a filled circle on Glcd Parameters x center x coordinate of the circle center Valid values 0 127 y center y coordinate of the circle center Valid values 0 63 radius radius size color color parameter Valid values 0 2 The parameter color determines the color of the circle 0 white 1 black and 2 inverts each dot ae Draw a circle with center in 50 50 and radius 10 SPI Gled Circle Fill 50 50 10 1 Ns Nee OOO S 455 MikroElektronika mikoPascal PRO for PIC32 SPI Glcd Set Font Prototype procedure SPI Glcd Set Font activeFont LongInt aFontWidth aFontHeight byte aFontOffs word Sets font that will be used with SPI Glcd Write Char and SPI Glcd Write Text routin
200. E SEC 1 SPI PRESCALE PRI 4 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE MikroElektronika 332 mikroPascal PRO for PIC32 Mmc_Fat_Assign Prototype function Mmc Fat Assign var filename array 12 of char file cre attr byte word Description Assigns file for file operations read write delete All subsequent file operations will be applied on an assigned file Parameters filename name of the file that should be assigned for file operations File name should be in DOS 8 3 file_name extension format The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does no have to take care of that The file name and extension are case insensitive The library will convert them to proper case automatically so the user does not have to take care of that Also in order to keep backward compatibility with the first version of this library file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between file name and extension i e MIKROELETXT gt MIKROELE TXT In this case last 3 characters of the string are considered to be file extension file cre attr file creation and attributes flags Each bit corresponds to the appropriate file attribute ei wask Besip o Fo or Reaony Volume Label Subdirectory 6
201. ED TO THE AMOUNT ACTUALLY PAID BY YOU FOR SOFTWARE PRODUCT PROVIDED HOWEVER IF YOU HAVE ENTERED INTOAMIKROELEKTRONIKAASSOCIATES SUPPORT SERVICES AGREEMENT MIKROELEKTRONIKA ASSOCIATES ENTIRE LIABILITY REGARDING SUPPORT SERVICES SHALL BE GOVERNED BY THE TERMS OF THAT AGREEMENT HIGH RISK ACTIVITIES Software is not fault tolerant and is not designed manufactured or intended for use or resale as on line control equipment in hazardous environments requiring fail safe performance such as in the operation of nuclear facilities aircraft navigation or communication systems air traffic control direct life support machines or weapons systems in which the failure of Software could lead directly to death personal injury or severe physical or environmental damage High Risk Activities mikroElektronika Associates and its suppliers specifically disclaim any expressed or implied warranty of fitness for High Risk Activities GENERAL PROVISIONS This statement may only be modified in writing signed by you and an authorised officer of mikroElektronika Associates If any provision of this statement is found void or unenforceable the remainder will remain valid and enforceable according to its terms If any remedy provided is determined to have failed for its essential purpose all limitations of liability and exclusions of damages set forth in the Limited Warranty shall remain in effect This statement gives you specific legal rights you may have
202. ETX gt lt STX gt 8 y B1002F 208610 781F80 200060 781F80 200010 781F80 07FF87 amp DLE f SPC lt B1006F 208690 781F80 200060 781F80 200020 781F80 O7FF7F 0 O f SPC US B1006F 200CC8 273987 ED200E 3AFFFE ED2010 SAFFFC 200010 0 amp E FF SPC t9 781F80 07FF35 B1002F 208700 781F80 200010 781F80 200010 lt US gt x 5 y BELL 0380 781F60 07FF6D B1006F 208810 781F80 200050 781F80 200020 lt US gt x m j BELL 0 71 gm gt MikroElektronika 124 mikroPascal PRO for PIC32 CHAPTER o Software Simulator Overview 125 MikroElektronika mikoPascal PRO for PIC32 Software Simulator The Source level Software Simulator is an integral component of the mikroPascal PRO for PIC32 environment It is designed to simulate operations of the Microchip PIC32 MCUs and assist the users in debugging code written for these devices Upon completion of writing your program choose Release build Type in the Project Settings window Project Settings P32MX460F512L Choose Release type if you want to use software simulator 8 000000 Build Type P Release ICD Debug Debugger Software O mikroICD After you have successfuly compiled your project you can run the Software Simulator by selecting Run Start Debugger from the drop down menu or by clicking the Start Debugger Icon B from the Debugger Too
203. Elektronika mikoPascal PRO for PIC32 Jump To Interrupt Lets you choose which interrupt you want to jump to Requirement Interrupt routine is included in project You can call Jump To Interrupt by selecting Run Jump To Interrupt from the drop down menu or by clicking the Jump To Interrupt Icon fw from the Watch Values Window Available Interrupts 0x0000 IVT CORE TIMER VECTOR Ox0001 IVT CORE SOFTWARE 0 VECTOR 0x0002 IVT CORE SOFTWARE 1 VECTOR 0x0003 IVT EXTERNAL 0 VECTOR 0x0004 IVT TIMER 1 VECTOR 0x0005 IVT INPUT CAPTURE 1 VECTOR 0x0006 IVT OUTPUT COMPARE 1 VECTOR 0x0007 IVT_EXTERNAL_1_VECTOR 0x0008 IVT TIMER 2 VECTOR 0x0009 IVT INPUT CAPTURE 2 VECTOR OxD00A IVT OUTPUT COMPARE 2 VECTOR OxO00B IVT EXTERNAL 2 VECTOR OxO00C IVT TIMER 3 VECTOR 0x000D IVT INPUT CAPTURE 3 VECTOR OxOO0E IVT OUTPUT COMPARE 3 VECTOR OxODOF IVT EXTERNAL 3 VECTOR 0x0010 IVT TIMER 4 VECTOR Ox0011 IVT INPUT CAPTURE 4 VECTOR 0x0012 IVT OUTPUT COMPARE 4 VECTOR 0x0013 IVT EXTERNAL 4 VECTOR 0x0014 IVT TIMER 5 VECTOR 0x0015 IVT INPUT CAPTURE 5 VECTOR 0x0016 IVT OUTPUT COMPARE 5 VECTOR 0x0017 IVT SPI 1 VECTOR 0x0018 IT ART 1 VECTOR 0x0019 IVT I2C 1 VECTOR 0x001A IVT CHANGE NOTICE VECTOR Ox001B IVT ADC VECTOR Ox001C IVT PMP VECTOR Ox001D IVT COMPARATOR 1 VECTOR OxOO1E IVT COMPARATOR 2 VECTOR O
204. Elektronika 136 mikroPascal PRO for PIC32 at keyword You can use the keyword at to make an alias to a variable for example you can write a library without using register names and later in the main program to define those registers for example unit MyUnit var PORTAlias byte external here in the library we can use its symbolic name inpiensntation end program MyProgram yar PORTAlias byte at PORTB this is where PORTAlias is fully defined begin end Note Bear in mind that when using at operator in your code over a variable defined through a external modifier appropriate memory specifer must be appended also bit type The mikroPascal PRO for PIC32 compiler provides a bit data type that may be used for variable declarations It can not be used for argument lists and function return values var bf bit bit variable There are no pointers to bit variables var ptr bit invalid An array of type bit is not valid var err j bity 7 nyalird Note Bit variables can not be initialized Bit variables can not be members of records Bit variables do not have addresses therefore unary operator address of is not applicable to these variables Related topics Predefined globals and constants External modifier 137 MikroElektronika mikoPascal PRO for PIC32 Interrupts The PIC32MX generates interrupt requests in response to interrupt events from peripheral modules The Interrupt
205. FT_Init Prototype procedure TFT Init display width display height word Nothing Description Initializes TFT display in the 8 bit working mode Parameters width width of the TFT panel height height of the TFT panel Requires Global variables DataPort Data Port r WR Write signal pin r RD Read signal pin r CS Chip Select signal pin r RS Register Select signal pin l RST Reset signal pin DataPort Direction Direction of Data Port WR Direction Direction of Write signal pin RD Direction Direction of Read signal pin l CS Direction Direction of Chip Select signal pin RS Direction Direction of Register Select signal pin RST Direction Direction of Reset signal pin must be defined before using this function TFT display connections var TFT DataPort byte at LATE var TFT WR sbit at LATD13 bit var TFT RD sbit at LATD12 bit var TFT CS sbit at LATC3 bit var TFT RS sbit at LATB15 bit var TFT RST sbit at LATC1 bit var TFT DataPort Direction byte at TRISE var TFT WR Direction sbit at TRISD13 bit var TFT RD Direction sbit at TRISD12 bit var TFT CS Direction sbit at TRISC3 bit var TFT RS Direction Sbit at TRISB15 bit var TFT RST Direction Sbit at TRISC1 bit End of TFT display connections Initialize 240x320 TFT display TFT Init 240 320 925 MikroElektronika mikoPascal PRO for PIC32 TFT_Set_Index Prototype procedure TFT Set Index
206. GLCD D5 Direction estaria Direction of the Data 5 pin var GLCD D6_Direction esterna Direction of the Data 6 pin var GLCD D7 Direction carnal Direction of the Data 7 pin sbit sfr Direction of the Chip Select 1 pin sbit sfr Direction of the Chip Select 2 pin sbit sfr Direction of the Register select pin sbit sfr Direction of the Read Write pin Rees MEET Direction of the Enable pin Sbir sfr Direction of the Reset pin var GLCD CS1 Direction external var GLCD CS2 Direction external var GLCD RS Direction external var GLCD RW Direction external var GLCD EN Direction external var GLCD RST Direction external Desertion examples var GLCD DO sbit at RBO bit var GLCD Dl sbit at RBl1 bit var GLCD D2 sbit at RB2 bit var G D3 sbit at RB3 bi var G D4 sbit at RDO bi var G D5 sbit at RD1 bi var GLCD D6 sbit at RD2 bi var GLCD D7 sbit at RD3 bit var GLCD CS1 sbit at D 022 LATB4 bit var GLC t sbit at LATB5 bit var GLCD RS sbit at LATFO bit var GLCD RW sbit at LATF1 bit var GLCD EN sbit at LATF4 bit var GLCD RST sbit at LATF5 bit var GLCD DO Direction URISBO bit var GLCD_D1l Direction TRISB1 bit var GLCD D2 Direction sbit at TRISB2 bit LCD D3 Direction bity D7 Direction var GLCD CS1 Direction SB4 bit var GLCD CS2 Direction SB5 bit GLCD RS Direction F
207. ID class devices and also the generic routines that can be used with vendor specified drivers USB HID Class The HID class consists primarily of devices that are used by humans to control the operation of computer systems Typical examples of HID class devices include Keyboards and pointing devices for example standard mouse devices trackballs and joysticks Front panel controls for example knobs switches buttons and sliders Controls that might be found on devices such as telephones VCR remote controls games or simulation devices for example data gloves throttles steering wheels and rudder pedals Devices that may not require human interaction but provide data in a similar format to HID class devices for example bar code readers thermometers or voltmeters Many typical HID class devices include indicators specialized displays audio feedback and force or tactile feedback Therefore the HID class definition includes support for various types of output directed to the end user Descriptor File Each project based on the USB library should include a descriptor source file which contains vendor id and name product id and name report length and other relevant information To create a descriptor file use the integrated USB HID terminal of mikroPascal PRO for PIC32 Tools USB HID Terminal The default name for descriptor file is USBdsc mpas but you may rename it Library Routines HID Enable HID Rea
208. IDLE Data is valid on IDLE to ACTIVE transition _SPI_IDLE 2 ACTIVI Nothing MCU must have the SPI module Set SPI1 to the Master Mode data length is 16 bit clock Fcy no clock scaling data sampled in the middle of interval clock IDLE state high and data transmitted at low to high clock edge SPI1 Init Advanced SPI MASTER SPI 16 BIT 1 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 IDLE SPI library routines require you to specify the module you want to use To select the desired SPI module simply change the letter x in the routine prototype for a number from 1 to 3 Number of SPI modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 398 mikroPascal PRO for PIC32 SPIx Read Prototype function SPIx Read data out word word Description Reads one word or byte depending on mode set by init routines from the SPI bus Parameters data_out dummy data for clock generation see device Datasheet for SPI modules implementation details Received data Requires Routine requires at least one SPI module Used SPI module must be initialized before using this function See the SPIx Init and SPlx Init Advanced routines read a byte from the SPI bus var take buffer byte take SPII Read Duffer SPI library routines require you to specify the modu
209. ISF1 bit GLCD EN Direction sbit at TRISF4 bit GLCD RST Direction sbit at TRISF5 bit End Glcd module connections Gled Inte 29 MikroElektronika mikoPascal PRO for PIC32 Glcd_Set_Side Prototype procedure Glcd_ Set Side x pos byte Selects Glcd side Refer to the Glcd datasheet for detailed explanation Parameters x pos Specifies position on x axis of the Glcd Valid values 0 127 Values from 0 to 63 specify the left side values from 64 to 127 specify the right side of the Glcd Glcd needs to be initialized see Glcd Init routine The following two lines are equivalent and both of them select the left side of Glcd Gled Select x cepe Gled Select Side Notes For side x axis and page a explanation see schematic at the bottom of this page Glcd Set X procedure Glcd Set X x pos byte Parameters x pos position on x axis Valid values 0 63 Rtuns nonn SS amp siiserxGsy OOOO S Notes Forside x axis and page layout explanation see schematic at the bottom ofthis page Glcd_Set_Page Prototype procedure Glcd Set Page page byte tuns Nothing OOOO Glcd needs to be initialized see Glcd Init routine Example Glec_set_Pase Sp Notes For side x axis and page layout explanation see schematic at the bottom of this page MikroElektronika 298 mikroPascal PRO for PIC32 Glcd Read Data Requires Glcd needs to be initialized see Glcd Init rout
210. If you hover the mouse over it you will see an Image preview Vs ae activeComment MikroElektronika mikoPascal PRO for PIC32 There is another way to add an active comment to an active project You can do it simply by typing a comment in old fashion way except with ac prefix So it would look like this ff ac activeComment4 Add Comment To Project Notice that when you stop typing Add Comment To Project button will show By clicking on it you will open Active Comment Editor and comment name will be already set so you need only to adjust attributes and settings After saving you can always edit your active comment by Active Comment Editor and switch between comments directly from editor If you remove a file from the Project Manager or add an Active Comment File which contains information about the file which is no longer in project and hover the mouse over the comment you will be prompted to either add file to project or remove event definition from Active Comment for this file Warning A File linked to this active comment is missing Would you like to add File to a project and make events associated with in valid or unlink file from Active Comment v Show more info If you remove active comment file from the Project Manager you ll receive this message Warning A Missing a file for this active comment Would you like to add File to a project or delete this Active Comment v
211. L MCU Therefore two different UART Library versions were made see mlk files for these two MCUs Note that these two libraries have the same Library Alias UART in both m1k files This approach enables you to have identical representation of UART library for both MCUs in Library Manager Related topics Library Manager Project Manager Managing Source Files MikroElektronika 614 mikroPascal PRO for PIC32 Frequently Asked Questions This is a list of frequently asked questions about using mikroElektronika compilers If your question is not answered on this page please contact mikroElektronika Support Desk Can use your compilers and programmer on Windows Vista Windows 7 Our compilers and programmer software are developed to work on and tested on Windows 98 Windows 2000 Windows ME Windows XP 32 and 64 bit Windows Vista 32 and 64 bit and Windows 7 32 and 64 bit and they work fine on these operating systems You can find the latest drivers on our website am getting Access is denied error in Vista how to solve this problem Please turn off User Account Control UAC This should make your software fully functional To do this follow the path in your Windows Vista logged in as administrator Control Panel User Accounts Turn User Account Control on or off uncheck Use User Account Control UAC and click OK What are differences between mikroC PRO mikroPascal PRO and mikroBasic PRO compilers Why do t
212. MikroElektronika 384 mikroPascal PRO for PIC32 Soft SPI Read Prototype function Soft SPI Read data byte byte Description This routine performs 3 operations simultaneously It provides clock for the Software SPI bus reads a byte and sends a byte sdata data to be sent Returns Byte received via the SPI bus Soft SPI must be initialized before using this function See Soft SPI Init routine var data read data send byte Read a byte and assign it to data read variable data send byte will be sent via SPI during the Read operation data read Soft SPI Read data send Soft SPI Write Prototype procedure Soft SPI Write sdata byte This routine sends one byte via the Software SPI bus sdata data to be sent Soft SPI must be initialized before using this function See Soft SPI Init Write a byte to the Soft SPI bus Soft SPI Write 0xAA Library Example This code demonstrates using library routines for Soft SPI communication Also this example demonstrates working with max7219 Eight 7 segment displays are connected to MAX7219 MAX7219 is connected to SDO SDI SCK pins are connected accordingly Copy Code To Clipboard DAC module connections var Chip Select sbit at LATDO bit SoftSpi CLK sbit at LATD6 bit SoftSpi SDI sbit at RD2 bit SoftSpi SDO sbit at LATD3 bit var Chip Select Direction sbit at TRISDO bit SoftSpi CLK Direction sbit at TRISD6 bit S
213. Mmc Write Sector Prototype function Mmc Write Sector sector dword var data array 512 of byte word The function writes 512 bytes of data to one MMC card sector Parameters sector MMC SD card sector to be written to dbuff data to be written buffer of minimum 512 bytes in length 0 if writing was successful if there was an error in sending write command 2 if there was an error in writing data rejected MMC SD card must be initialized See Mmc Init write to sector 510 of the MMC SD card var error word sectorNo dword dataBuffer array 512 of byte 510 Mmo Write Sector sectorNo dataBuffer 329 MikroElektronika mikoPascal PRO for PIC32 Mmc_Read_Cid Prototype function Mmc Read Cid var data cid array 16 of byte word The function reads 16 byte CID register data cid buffer of minimum 16 bytes in length for storing CID register content 0 if CID register was read successfully if there was an error while reading MMC SD card must be initialized See Mmc Init var error word dataBuffer array 16 of byte rror Mmc Read Cid dataBuffer Mmc Read Csd Prototype function Mmc Read Csd var data for registers array 16 of byte word The function reads 16 byte CSD register data csd buffer of minimum 16 bytes in length for storing CSD register content 0 if CSD register was read successfully if there was an error while reading
214. ModuleAddress Port Expander hardware address see schematic at the bottom of this page Requires Port Expander must be initialized See Expander Init Port Expander s PortB should be configured as input See Expander Set DirectionPortB and Expander Set DirectionPortAB routines Read a byte from Port Expander s PORTB var read data byte Expander Set _DirectionPortB 0 FF set expander s portb to be input read data Expander Read PortB 0 Expander Read PortAB Prototype Prototype function Expander Read PortAB ModuleAddress byte word Description The function reads word from Port Expander s ports PortA readings are in the higher byte of the result PortB readings are in the lower byte of the result ModuleAddress Port Expander hardware address see schematic at the bottom of this page Rtums woare Requires Port Expander must be initialized See Expander Init Port Expander s PortA and PortB should be configured as inputs See Expander Set DirectionPortA Expander Set DirectionPortB and Expander Set DirectionPortAB routines Read a byte from Port Expander s PORTA and PORTB var read data word Expander Set DirectionPortAB 0 FFFF set expander s porta and portb to be input read data Expander Read PortAB 0 391 MikroElektronika mikoPascal PRO for PIC32 Expander_Write_PortA Prototype procedure Expander Write PortA ModuleAddres
215. NSPI Library Compact Flash Library Epson S1D13700 Graphic Lcd Library Flash Memory Library Graphic Lcd Library PC Library Keypad Library Lcd Library Manchester Code Library Memory Manager Library Multi Media Card Library OneWire Library Port Expander Library PS 2 Library PWM Library RS 485 Library Software C Library Software SPI Library Software UART Library Sound Library SPI Library SPI Ethernet Library SPI Ethernet ENC24J600 Library SPI Graphic Lcd Library SPI Lcd Library SPI Lcd8 Library SPI T6963C Graphic Lcd Library T6963C Graphic Lcd Library TFT Display Library Touch Panel Library Touch Panel TFT Library UART Library USB Library MikroElektronika 236 mikroPascal PRO for PIC32 ADC Library ADC Analog to Digital Converter module is available with a number of PIC32 MCU modules ADC is an electronic circuit that converts continuous signals to discrete digital numbers ADC Library provides you a comfortable work with the module Library Routines ADC1_Init ADC1_Init_Advanced ADC1_Get_Sample ADC1 Read ADCA Init Prototype procedure ADC1 Init Description This routines configures ADC module to work with default settings The internal ADC module is set to single channel conversion 10 bit conversion resolution unsigned integer data format auto convert VRef AVdd VRef AVss inst
216. O sbit sfr var SoftSpi SDO spit at LATF3 Data Out line external bit var SoftSpi CLK sbit sfr var SoftSpi CLK sbit at LATF6 Clock line external bit var SoftSpi_SDI_Direction NE var SoftSpi SDI Direction sbit at sbit sfr external Direction of the Data In pin TRISE2 bit var SoftSpi SDO Direction var SoftSpi SDO Direction sbit at sbit sfr external Directionor Me Data UEPI TRISF3 bit var SoftSpi CLK Direction Direction of the Clock pin var SoftSpi CLK Direction sbit at sbit sfr external pin TRISF6 bit Library Routines Soft SPI Init Soft SPI Read Soft SPI Write 383 MikroElektronika mikoPascal PRO for PIC32 Soft SPI Init ums Nothing OOO Requires Global variables SoftSpi SDI Datain line SoftSpi SDO Data out line SoftSpi CLK Data clock line SoftSpi SDI Direction Direction of the Data in pin SoftSpi SDO Direction Direction of the Data out pin SoftSpi CLK Direction Direction of the Data clock pin must be defined before using this function Software SPI module var var var var var var SoftSpi SDI sbit at SoftSpi SDO sbit at SoftSpi CLK sbit at SoftSpi SDI Direction SoftSpi SDO Direction SoftSpi CLK Direction connections RF2 bit LATF3 bit LATF6 bit sbit at TRISF2 bit sbit at TRISF3 bit sbit at TRISF6 bit End Software SPI module connections Soft SPI Init Init Soft SPI
217. OM C Domo P VCb Ow Ch beetle Write text im first row I GE X0 3T HN NN paiay ma FOR acter B fer 1 0 te de sn 9 begun D Move Ly Lcd Omdi LCD SWIFT PIGET ove Detayi 8 d esxu x exsuucxesums p og em Perte erit OU n nw 3 1 nye d VESEY J iT while THEE de Tan BUS m Pest fer ii to we Mame PEM resin CU Qe E move Delay o me Teen onn rome fer iin te dn o hav ton N Led Ond ACO SHIFT BEGET Beve Peiori ine KD Den i ona awe xt es pem a EM wows re we ja aro w 3 ned X Sans E HON Free RI vt ON ed X bir RE NOON Pree RU Cen 0 I me mt CA Pirsani ma FEO Sor SNE samet Sm IS The Code Editor features adjustable Syntax Highlighting Code Folding Code Assistant Parameters Assistant Spell Checker Auto Correct for common typos and Code Templates Auto Complete The Code Explorer is at your disposal for easier project management The Project Manager alows multiple project management General project settings can be made in the Project Settings window Library manager enables simple handling libraries being used in a project The Messages Window displays all messages during compiling and linking The source level Software Simulator lets you debug executable logic step by step by watching the program flow The New Project Wizard is a fast reliable and easy way to create a project Help files are syntax and context sensitive Lik
218. OSCILLATOR vCC3 ovcca3 ovcca Example of interfacing PC to PIC32 MCU via RS485 bus with LTC485 as RS 485 transceiver 319 MikroElektronika mikoPascal PRO for PIC32 Message format and CRC calculations Q How is CRC checksum calculated on RS485 master side Copy Code To Clipboard eal const START BYTE byte 0x96 10010110 const STOP BYTE byte 0xA9 10101001 PACKAGE START BYTE 0x96 ADDRESS DATALEN DATA1 if exists DATA2 if exists DATA3 if exists CRC STOP BYTE OxA9 DATALEN bits bit7 1 MASTER SENDS SLAVE SENDS bit6 1 ADDRESS WAS XORed with 1 IT WAS EQUAL TO START BYTE or STOP BYTE 0 ADDRESS UNCHANGED bit5 0 FIXED bit4 1 DATA3 if exists WAS XORed with 1 IT WAS EQUAL TO START BYTE or STOP BYTE O0 DATA3 if exists UNCHANGED bit3 1 DATA2 if exists WAS XORed with 1 IT WAS EQUAL TO START BYTE or STOP BYTE O0 DATA2 if exists UNCHANGED bit2 1 DATA1 if exists WAS XORed with 1 IT WAS EQUAL TO START BYTE or STOP BYTE O0 DATA1 if exists UNCHANGED bitlbitO 0 to 3 NUMBER OF DATA BYTES SEND CRC generation crc send datalen xor address crc send crc send xor data 0 i LE exists crc send crc send xor datali if exists crc send crc send xor data 2 if exists erc send erc send not cre send if crc send START BYTE or crc send
219. Once the MMC SD card is initialized SPI module can be reinitialized at higher a speed See the Mmc Init and Mmc Fat Init routines MikroElektronika 326 mikroPascal PRO for PIC32 Library Dependency Tree MMC MMC FAT16 C String C Type External dependencies of MMC Library The following variable must be defined Description in all projects using MMC library P var Mmc Chip Select sbit sfr var Mmc Chip Select sbit at LATFO Chip select pin i external bit var Mmc Chip Select Direction sbit sfr external var Mmc Chip Select Direction sbit Direction of the chip select pin at TRISFO bit Library Routines Mmc Init Mmc Read Sector Mmc Write Sector Mmc Read Cid Mmc Read Csd Routines for file handling Mmc Fat Init Mmc Fat QuickFormat Mmc Fat Assign Mmc Fat Reset Mmc Fat Read Mmc Fat Rewrite Mmc Fat Append Mmc Fat Delete Mmc Fat Write Mmc Fat Set File Date Mmc Fat Get File Date Mmc Fat Get File Date Modified Mmc Fat Get File Size Mmc Fat Get Swap File 321 MikroElektronika mikoPascal PRO for PIC32 Mmc Init Prototype Description Initializes MMC through hardware SPI interface Mmc Init needs to be called before using other functions of this library 0 if MMC SD card was detected and successfully initialized 1 otherwise Requires The appropriate hardware SPI module must be previously in
220. P address Returns Pointer to the global variable holding DNS IP address Ethernet module has to be initialized See SPI_Ethernet_24j600_Init v dnsIpAddr array 4 of byte user DNS IP address buffer memcpy dnsIpAddr SPI Ethernet 24j600 getDnsIpAddress 4 fetch DNS Server address User should always copy the IP address from the RAM location returned by this routine into it s own DNS IP address buffer These locations should not be altered by the user in any case MikroElektronika 440 mikroPascal PRO for PIC32 SPI Ethernet 24j600 getlpMask Prototype function SPI Ethernet 245600 getIpMask Description This routine should be used when DHCP server is present on the network to fetch assigned DNS IP address Pointer to the global variable holding IP subnet mask Requires Ethernet module has to be initialized See SPI Ethernet 24j600 Init var IpMask array 4 of byte user IP subnet mask buffer memcpy IpMask SPI Ethernet 24j600 getIpMask 4 fetch IP subnet mask User should always copy the IP address from the RAM location returned by this routine into it s own IP subnet mask buffer These locations should not be altered by the user in any case SPI Ethernet 24j600 confNetwork Prototype procedure SPI Ethernet 243600 confNetwork var ipMask gwIpAddr dnsIpAddr array 4 of byte Description Configures network parameters IP subnet mask gateway IP address DNS IP address
221. PI Ethernet 247600 UNICAST enable CRC checking and Unicast traffic Advanced filtering available in the ENC24J600 module such as Pattern Match Magic Packet and Hash Table can not be enabled by this routine Additionally all filters except CRC enabled with this routine will work in OR mode which means that packet will be received if any of the enabled filters Parameters enF1t network traffic receive filter flags Each bit corresponds to the appropriate network traffic receive filter 0x01 MAC Broadcast traffic receive filter flag When set MAC SPI Ethernet 243600 n broadcast traffic will be enabled BROADCAST accepts it This routine will change receive filter configuration on the fly It will not in any way mess with enabling disabling receive transmit logic or any other part of the ENC24J600 module The ENC247600 module should be properly cofigured by the means of SPI Ethernet 243600 Init routine 433 MikroElektronika mikoPascal PRO for PIC32 SPI_Ethernet_24j600_Disable Prototype procedure SPI Ethernet 243600 Disable disFlt word Description This is MAC module routine This routine disables appropriate network traffic on the ENC24J600 module by the means of it s receive filters unicast multicast broadcast crc Specific type of network traffic will be disabled if a corresponding bit of this routine s input parameter is set Therefore more than one type of network traffic can be disa
222. PI Glcd H Line x start x end y pos color byte Draws a horizontal line on Glcd Parameters x start x coordinate of the line start Valid values 0 127 x end X coordinate of the line end Valid values 0 127 y pos y coordinate of horizontal line Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the line color 0 white 1 black and 2 inverts each dot Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draw a gera between dots 10 20 and 50 20 SPI Glcd H Line 205 Lig SPI Glcd Rectangle Prototype procedure SPI Glcd Rectangle x upper left y upper left Xx bottom right y bottom right color byte Draws a rectangle on Glcd Parameters x upper left x coordinate of the upper left rectangle corner Valid values 0 127 y upper left y coordinate of the upper left rectangle corner Valid values 0 63 x bottom rignt X coordinate of the lower right rectangle corner Valid values 0 127 y bottom right y coordinate of the lower right rectangle corner Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the color of the rectangle border O white 1 black and 2 inverts each dot Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draw a rectangle between dots 5 5 and 40 40 SPI Gled Rectangle 5 5 40 40 1 MikroElektronika 452
223. Port Compact Flash data port C DY Ready signal line C E Write enable signal line C E Output enable signal line C D1 Chip detect signal line CF_CE1 Enable signal line C 2 Address pin 2 CF A1 Address pin 1 CF AO Address pin 0 CF RDY direction Direction of the Ready pin CF WE direction Direction of the Write enable pin _O C C I Hj 7 E W OE UE ES C E direction Direction of the Output enable pin CF CD1 direction Direction of the Chip detect pin C El direction Direction of the Chip enable pin CF A2 direction Direction of the Address 2 pin CF Al direction Direction of the Address 1 pin CF A0 direction Direction of the Address 0 pin E aa must be defined before using this function set compact flash pinout var Cf Data Port byte at PORTD CF RDY sbit at RB7 bit CF WE sbit at LATB6 bit for writing CF OE sbit at LATB5 bit for writing CF CDI sbit at RB4 bit CF CE1 sbit at LATB3 bit for writing CF A2 3 sbit at LATB2 bit for writing CF Al 3 sbit at LATBI bit for writing CF A0 sbit at LATBO bit for writing CF RDY direction sbit at TRISB7 bit CF WE direction sbit at TRISB6 bit CF OE direction sbit at TRISB5 bit CF CD1 direction sbit at TRISB4 bit CF CE1 direction sbit at TRISB3 bit CF A2 direction sbit at TRISB2 bit CF A1 direction Sbit at TRISB1 bit CF A0 direction lt sbit at TRISBO bit end of compact fash p
224. Pre if Cf Fat Assign filename begin file has been found get its date uncomment this line 0 lt gt 0 then 0 for mikroElektronika 2009 and if so Prepare file for append ZZ CR LF Write data to assigned file reads data from it and puts it to USART To read file procedure returns size of file Write data to USART it will first be created its creation date sends to search for file that DOES exists to search for file that DOES NOT exist Cf Fat Get File Date year month day hour minute UART1 Write Text created WordToStr year outstr UART1 Write Text outstr ByteToStr month outstr 1 5 MikroElektronika 214 mikroPascal PRO for PIC32 UART1 Write Text outstr WordToStr day outstr UART1 Write Text outstr WordToStr hour outstr UART1 Write Text outstr WordToStr minute outstr UART1 Write Text outstr file has been found get its modified date Cf Fat Get File Dat odified year month day UART1 Write Text modified WordToStr year outstr UART1 Write Text outstr ByteToStr month outstr UART1 Write Text outstr WordToStr day outstr UART1 Write Text outstr WordToStr hour outstr UART1 Write Text outstr WordToStr minute outstr UART1 Write Text outstr get file size fsize Cf Fat Get File Size LongIntToStr fsize outstr
225. Project Menu Options 46 Build 47 Build Menu Options 47 Run 48 Run Menu Options 48 Tools 49 Tools Menu Options 49 Help 50 MikroElektronika mikroPascal PRO for PIC32 Help Menu Options 50 mikroPascal PRO for PIC32 IDE 51 IDE Overview 51 Code Editor 52 Editor Settings 52 Auto Save 53 Highlighter 53 Spelling 53 Comment Style 53 Code Folding 53 Code Assistant 54 Parameter Assistant 54 Bookmarks 54 Go to Line 54 Column Select Mode 55 Editor Colors 55 Auto Correct 56 Auto Complete Code Templates 57 Code Explorer 59 Routine List 60 Project Manager 60 Project Settings 62 Library Manager 63 Managing libraries using Package Manager 64 Routine List 65 Statistics 65 Memory Usage Windows 65 Variables 66 Used RAM Locations 66 SFR Locations 67 ROM Memory Usage 67 ROM Memory Constants 68 Functions 68 Functions Sorted By Name Chart 69 Functions Sorted By Size Chart 69 Functions Sorted By Addresses 70 Function Tree 70 Memory Summary 71 Messages Window 72 Quick Converter T3 Macro Editor 73 Image Preview 74 Toolbars 76 File Toolbar 77 MikroElektronika mikoPascal PRO for PIC32 Edit Toolbar Advanced Edit Toolbar Find Replace Toolbar Project Toolbar Build Toolbar Debug Toolbar Styles Toolbar Tools Toolbar View Toolbar Layout Toolbar Help Toolbar Customizing IDE Layout Docking Windows Saving Layout Auto Hide Options Code editor Tools Output settings Integrated Tools Active Comments
226. Prototype function strchr var s string ch byte word Description The function searches the string s for the first occurrence of the character cn The null character terminating s is not included in the search The function returns the position index of the first character cn found in s if no matching character was found the function returns OxFFFF mikroElektronika res strchr txt E routine will locate the character txt string and return the position of the character MikroElektronika 588 mikroPascal PRO for PIC32 strcmp Prototype function strcmp var sl s2 string integer Description The function lexicographically compares the contents of the strings s1 and s2 and returns a value indicating their relationship Value Meaning 0 sl less than s2 sl equal to s2 gt 0 sl greater than s2 The value returned by the function is determined by the difference between the values of the first pair of words that differ in the strings being compared mikroElektronika res strchr txt E routine will locate the character txt string and return the position of the character Prototype procedure strcpy var sl s2 string Description The function copies the value of the string s2 to the string s1 and appends a null character to the end of s1 mikroElektronika ee mikr strcpy txt txt sub copies string
227. RITY 0 and form value to be used CANSPI TX XTD FRAME and with CANSPIWrite CANSPI TX NO RTR FRAME Can Init Flags CANSPI CONFIG SAMPLE THRICE and form value to be used CANSPI CONFIG PHSEG2 PRG ON and with CANSPIInit CANSPI CONFIG XTD MSG and CANSPI CONFIG DBL BUFFER ON and CANSPI CONFIG VALID XTD MSG Initialize SPI2 module SPI2 Init CANSPIInitialize 1 3 3 3 1 Can Init Flags CANSPISetOperationMode CANSPI MODE CONFIG 0x CANSPISetMask CANSPI MASK B1 1 CANSPI CONFIG XTD MSG initialize external CANSPI module FF set CONFIGURATION mode set all maskl bits to ones 293 MikroElektronika mikoPascal PRO for PIC32 CANSPISetMask CANSPI MASK B2 1 CANSPI CONFIG XTD MSG set all mask2 bits to ones CANSPISetFilter CANSPI FILTER B2 F4 ID 2nd CANSPI CONFIG XTD MSG set id of filter B2 F4 to 2nd node ID CANSPISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode Set initial data to be sent RxTx Data 0 9 CANSPIWrite ID 1st RxTx Data 1 Can Send Flags send initial message while TRUE do begin endless loop Msg Rcvd CANSPIRead Rx ID RxTx Data Rx Data Len Can Rcv Flags receive message if Rx ID ID 2nd and Msg Rcvd then if message received check id begin PORTB RxTx Data 0 id correct output data at PORTD Inc RxTx Data 0 increment received data Delay ms 10 CANSPIW
228. Rectangle 20 20 219 107 MikroElektronika 536 mikroPascal PRO for PIC32 TFT Rectangle Round Edges Prototype procedure TFT Rectangle Round Edges x upper left y upper left x bottom right y bottom right round radius word Description Draws a rounded edge rectangle on TFT Parameters x upper left x coordinate of the upper left rectangle corner y upper left y coordinate of the upper left rectangle corner x bottom right x coordinate of the lower right rectangle corner y bottom right y coordinate of the lower right rectangle corner round radius radius of the rounded edge TFT module needs to be initialized See the TFT Init routine a TFT Rectangle Round Edges 20 20 219 107 12 TFT_Circle Prototype procedure TFT Circle x center y center radius integer Description Draws a circle on TFT Parameters x X coordinate of the circle center y y coordinate of the circle center r radius size TFT module needs to be initialized See the TFT Init routine PFA TFT Circle 120 64 110 TFT Image Prototype procedure TFT Image left top word image const far byte stretch byte Description Displays an image on a desired location Parameters left position of the image s left edge top position of the image s top edge image image to be displayed Bitmap array is located in code memory stretch stretches image by a given factor if
229. Show more info Click on Yes button you ll prompted for an active comment file MikroElektronika 100 mikroPascal PRO for PIC32 O Easy GSM GPRS ej activeComment amp activeComment2 My Recent Documents Files of type Active Link Files xml C Open as read only My Network If you click No comment will be removed from the source code Renaming Active Comment When you click on rename button you will be prompted to enter new name Active Comments Editor Select Active Comment activeComment Active Comment Actions New Rename Enter new Active Comment Name ctive CommentRename Rename Properties zl Attributes Url ww mikroe com Image Easy_GSM_GPRS jpg File None S Events OnLeftClick Alt OpenUrl OnRightClick None OnDbiClick OnMouseOver X PreviewImage Add Image To Project Add File To Project MikroElektronika mikoPascal PRO for PIC32 Now click again Rename button Now you have renamed your Active Comment in such a way that its filename source code name are changed I V ac activeCommentRename 30 Deleting Active Comment Deleting active comment works similar like renaming it By clicking on delete button you will remove an active comment from both code and Project Manager MikroElektronika 102 mikroPascal PRO for PIC32 Export Project This option is very convenient and finds its use in relocating your projects from
230. T location Parameters ptr const string to be written into ENC28760 RAM Number of bytes written into ENC28760 RAM Requires Ethernet module has to be initialized See SPI Ethernet Init const buffer string 16 buffer mikroElektronika SPI Ethernet putConstString buffer put a const string into ENC28J60 buffer SPI Ethernet getByte Prototype function SPI Ethernet getByte byte Description This is MAC module routine It fetches a byte from address pointed to by current ENC28J60 read pointer ERDPT Byte read from ENC28760 RAM Requires Ethernet module has to be initialized See SPI Ethernet Init var buffer byte buffer SPI Ethernet getByte read a byte from ENC28J60 buffer 411 MikroElektronika mikoPascal PRO for PIC32 SPI_Ethernet_getBytes Prototype procedure SPI Ethernet getBytes ptr byte addr word n word Description This is MAC module routine It fetches equested number of bytes from ENC28360 RAM starting from given address If value of 0xF FFF is passed as the address parameter the reading will start from current ENC28J60 read pointer ERDPT location Parameters ptr buffer for storing bytes read from ENC28560 RAM addr ENC28 J60 RAM start address Valid values 0 8192 n number of bytes to be read Ethernet module has to be initialized See SPI Ethernet Init var buffer array
231. T6963C Config routine set graphic panel 1 as current graphic panel SPI T6963C setGrPanel 1 SPI T6963C setTxtPanel Description Compute start address for selected text panel and set appropriate internal pointers All subsequent text operations will be preformed at this text panel n text panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine set text panel 1 as current text panel SPI T6963C setTxtPanel 1 MikroElektronika 488 mikroPascal PRO for PIC32 SPI T6963C panelFill Prototype procedure SPI T6963C panelFill v word Description Fill current panel in full graphic text with appropriate value 0 to clear SPI T6963C panelFill 0 None SPI T6963C grFill Iul t c EE SPI T6963C grFill 0 Nes None SPI T6963C txtFill Toshiba Glcd module needs to be initialized See SPI T6963C Config routine clear current text panel SPI T6963C txtFill 0 None 489 MikroElektronika mikoPascal PRO for PIC32 SPI_T6963C_cursor_height Prototype procedure SPI T6963C cursor height n byte Parameters n cursor height Valid values 0 7 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example SP T6963C cursor height OO OOO we None SPI T6963C graphics Prototype procedure SPI T6963C graphics n word Enable disable graphic displaying Parameters
232. T6963C rectangle round edges fill x0 yO x1 yl radius integer round radius radius of the rounded edge ee color parameter Valid values T6963C_ BLACK and T6963C WHITE Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C rectangle round edges fil1 20 20 219 107 12 T6963C WHITE T6963C box Prototype procedure T6963C box x0 y0 xl yl integer pcolor byte Draws a box on Glcd Parameters x0 x coordinate of the upper left box corner y0 y coordinate of the upper left box corner x1 X coordinate of the lower right box corner y1 y coordinate of the lower right box corner pcolor color parameter Valid values T6963C BLACK and T6963C WHITE Ruum Nong OOOO SSS Example T6963C box 0 119 239 127 T6963C WHITE Neue Ng 0 M T6963C circle Prototype procedure T6963C circle x integer r longint pcolor word Draws a circle on Glcd Parameters x x coordinate of the circle center y y coordinate of the circle center r radius size pcolor color parameter Valid values TE963C BLACK and T6963C WHITE Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C circle 120 64 110 T6963C WHITE MikroElektronika 508 mikroPascal PRO for PIC32 T6963C circle fill Prototype procedure 76963C Circle fill x integer r longint pcolor word Draws a filled circle on Glcd Parameters x x
233. TI Read MikroElektronika 556 mikroPascal PRO for PIC32 UARTx_Read_Text Prototype procedure UARTx Read Text var output delimiter string Attempts byte Description Reads characters received via UART until the delimiter sequence is detected The read sequence is stored in the parameter output delimiter sequence is stored in the parameter delimiter This is a blocking call the delimiter sequence is expected otherwise the procedure exits if the delimiter is not found Parameters Output received text Delimiter sequence of characters that identifies the end of a received string Attempts defines number of received characters in which Delimiter sequence is expected If Attempts is set to 255 this routine will continuously try to detect the Delimiter sequence Requires Routine requires at least one UART module Used UART module must be initialized before using this routine See UARTx Init and UARTx Init Advanced routines UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Read text until the sequence OK is received and send back what s been received Read text until the sequence OK is received and then send it back UART1 Init
234. This mechanism is similar to WDT var datal error counter byte procedure TimerlInt org IVT ADDR T1INTERRUPT begin counter 0 if counter gt 20 begin Soft I2C Break counter 0 reset counter end else Inc counter increment counter TIIF pit 2 07 Clear Timerl overflow interrupt flag end begin try Soft I2C Init with blocking prevention mechanism IPCO x IPCO or 0x1000 Interrupt priority level 1 TIIE bit v 1 Enable Timerl interrupts T1CON 0x8030 Timerl ON internal clock FCY prescaler 2250 Soft I2C Inzt TIIE DLE 2 OF Disable Timerl interrupts end Interrupts should be disabled before using Software C routines again see note at the top of this page MikroElektronika 380 mikroPascal PRO for PIC32 Library Example The example demonstrates use of the Software I C Library The PIC32 MCU is connected SCL SDA pins to PCF8583 RTC real time clock Program sends date time to RTC Copy Code To Clipboard program var Seco RTC Read nds minutes hours Software I2C connections var Soft I2C Scl Soft I2C Sda Soft I2C Scl Direction Soft I2C Sda Direction End Software I2C connections LCD module connections var LCD RS sbit at var LCD EN sbit at var LCD D4 sbit at var LCD D5 sbit at var LCD D6 sbit at var LCD D7 sbit at var LCD RS Direction var LCD EN Direction var LCD D4 Direction var LCD D5 Direc
235. WM Stop 1 Notes Number of available PWM channels depends on MCU Refer to MCU datasheet for details MikroElektronika 364 mikroPascal PRO for PIC32 Library Example The example changes PWM duty ratio on channels 1 and 2 continuously If LEDs are connected to channels 1 and 2 a gradual change of emitted light will be noticeable Copy Code To Clipboard program Pwm Demo var current duty old duty current dutyl old dutyl word pwm periodl pwm period2 word procedure InitMain begin CHECON 0x32 ADIPCFG OxFFFF configure pins as digital I O TRISB OxFFFF configure PORTB pins as input PORTD 0 set PORTD to 0 TRISD 0 designate PORTD pins as output end begin InitMain current duty 100 initial value for current duty current dutyl 100 initial value for current dutyl pwm periodi PWM Init 5000 1 1 2 pwm period2 PWM Init 10000 2 1 3 PWM Start 1 PWM Start 2 PWM Set Duty current duty a PWM Set Duty current dutyl 1 2 Set current duty for PWM1 Set current duty for PWM2 while TRUE do endless loop begin if RBO bit 1 then button on RBO pressed begin Delay ms 1 current duty current duty 5 increment current duty if current duty pwm periodl then if we increase current duty greater then possible pwm periodl value current duty 0 reset current duty value to zero PWM Set Duty current duty 1
236. a byte The function sets Port Expander s PortB direction Parameters ModulecAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written to the PortB direction register Each bit corresponds to the appropriate pin of the PortB register Set bit designates corresponding pin as input Cleared bit designates corresponding pin as output Port Expander must be initialized See Expander Init Set Port Expander s PORTB to be input Expander Set _DirectionPortB 0 FF Notes Noe OOS S Expander Set DirectionPortAB Prototype procedure Expander Set DirectionPortAB ModuleAddress Direction word The function sets Port Expander s PortA and PortB direction Parameters ModulecAddress Port Expander hardware address see schematic at the bottom of this page Direction data to be written to direction registers Data to be written to the PortA direction register are passed in Direction s higher byte Data to be written to the PortB direction register are passed in Direction s lower byte Each bit corresponds to the appropriate pin of the PortA PortB register Set bit designates corresponding pin as input Cleared bit designates corresponding pin as output Port Expander must be initialized See Expander Init Set Port Expander s PORTA to be output and PORTB to be input Expander Set DirectionPortAB 0 00FF Expander Set PullUpsPortA Prototype procedu
237. ack 0 not acknowledge signal will be sent after reading otherwise the acknowledge signal will be sent One byte from the Slave Requires Soft IC must be configured before using this function See Soft I2C Init routine Also START signal needs to be issued in order to use this function See Soft I2C Start routine var take byte Read data and send the not acknowledge signal take Soft I2C Read 0 Soft I2C Write Prototype function Soft I2C Write data byte byte Description Sends data byte via the I C bus Parameters data_ data to be sent 0 if there were no errors 1 if write collision was detected on the I C bus Requires Soft IC must be configured before using this function See Soft I2C Init routine Also START signal needs to be issued in order to use this function See Soft_I2C_Start routine var data error byte error Soft I2C Write data error Soft I2C Write A3 Soft I2C Stop Prototype procedure Soft I2C Stop Description Issues STOP signal Soft C must be configured before using this function See Soft I2C Init routine Issue STOP signal Soft T20 Stopi 319 MikroElektronika mikoPascal PRO for PIC32 Soft I2C Break Prototype procedure Soft I2C Break Description All Software I C Library functions can block the program flow see note at the top of this page Calling this routine from interrupt will unblock the program execution
238. activity indication This library is designed to simplify handling of the underlying hardware ENC283560 It works with any PIC32 with integrated SPI and more than 4 Kb ROM memory 38 to 40 MHz clock is recommended to get from 8 to 10 Mhz SPI clock otherwise PIC32 should be clocked by ENC28J60 clock output due to its silicon bug in SPI hardware If you try lower PIC32 clock speed there might be board hang or miss some requests SPI Ethernet library supports IPv4 protocol ARP requests ICMP echo requests UDP requests TCP requests no stack no packet reconstruction ARP client with cache DNS client UDP client DHCP client packet fragmentation is NOT supported Important Global library variable SPI Ethernet userTimerSec is used to keep track of time for all client implementations ARP DNS UDP and DHCP It is user responsibility to increment this variable each second in it s code if any of the clients is used For advanced users there is_ EthEnc283j60Private mpas unit in Uses folder of the compiler with description of all routines and global variables relevant to the user implemented in the SPI Ethernet Library The appropriate hardware SPI module must be initialized before using any of the SPI Ethernet library routines Refer to SPI Library For MCUs with multiple SPI modules it is possible to initialize them and then switch by using the SPI Set Active routine
239. al PRO for PIC32 however you may use newline to break long statements into several lines Parser will first try to get the longest possible expression across lines if necessary and then check for statement terminators Whitespace in Strings The ASCII characters representing whitespace can occur within string literals in which case they are protected from the normal parsing process they remain a part of the string For example MikroElektronika 178 mikroPascal PRO for PIC32 some string mikro foo parses into four tokens including a single string literal token some string mikro foo Comments Comments are pieces of a text used to annotate a program and are technically another form of whitespace Comments are for the programmer s use only They are stripped from the source text before parsing There are two ways to create comments in mikroPascal You can use multi line comments which are enclosed with braces or and All text between left and right brace constitutes a comment May span multiple lines Comment can be written in this way too or single line comments Any text between a double slash and the end of the line constitutes a comment spanning one line only Nested comments mikroPascal PRO for PIC32 doesn t allow nested comments The attempt to nest a comment like this i identifier word fails because the scope of the first open brace ends at t
240. al txt array 10 of char ffl ie 374 2 ff2 123 456789 ff3 0 000001234 BPloatToStr tfl txt f txt 1s 374 20001 FloatToStr ff2 txt txt is 123 45678 PloatToStr ff3 txt J txt zs 0 000000 Notes Given floating point number will be truncated to 7 most significant digits before conversion WordToStrWithZeros Prototype procedure WordToStrWithZeros input word var output array 5 of char pep Converts input word to a string The output string is right justified and the remaining positions on the aia if any are filled with zeros Parameters input unsigned integer to be converted output destination Fa Returne Notting 000000000o s var t word txt array 5 of char flans t 437 WordToStrWithZeros t txt txt is 00437 MikroElektronika 916 mikroPascal PRO for PIC32 IntToStrWithZeros Prototype procedure IntToStrWithZeros input integer var output array 6 of char Description Converts input integer to a string The output string is right justified and the remaining positions on the left if any are filled with zeros Parameters input integer number to be converted BE destination string var t integer txt array 6 of char Pp m t 3276 IntToStrWithZeros t txt txt is 03276 LongWordToStrWithZeros Prototype procedure LongWordToStrWithZeros input dword var output array 10 char Description Conv
241. al dependencies of SPI Ethernet ENC24J600 Library 431 1 MikroElektronika mikoPascal PRO for PIC32 Library Routines 432 SPI Ethernet 24j600 Init 433 SPI Ethernet 24j600 Enable 435 SPI Ethernet 24j600 Disable 436 SPI Ethernet 24j600 doPacket 437 SPI Ethernet 24j600 putByte 437 SPI Ethernet 24j600 putBytes 438 SPI Ethernet 24j600 putConstBytes 438 SPI Ethernet 24j600 putString 439 SPI Ethernet 24j600 putConstString 439 SPI Ethernet 24j600 getByte 439 SPI Ethernet 24j600 getBytes 440 SPI Ethernet 24j600 UserTCP 440 SPI Ethernet 24j600 UserUDP 441 SPI Ethernet 24j600 getlpAddress 441 SPI Ethernet 24j600 getGwlpAddress 442 SPI Ethernet 24j600 getDnslpAddress 442 SPI Ethernet 24j600 getlpMask 443 SPI Ethernet 24j600 confNetwork 443 SPI Ethernet 24j600 arpResolve 444 SPI Ethernet 24j600 sendUDP 444 SPI Ethernet 24j600 dnsResolve 445 SPI Ethernet 24j600 initDHCP 446 SPI Ethernet 24j600 doDHCPLeaseTime 447 SPI Ethernet 24j600 renewDHCP 447 SPI Graphic Lcd Library 448 Library Dependency Tree 448 External dependencies of SPI Lcd Library 448 Library Routines 448 SPI Glcd Init 449 SPI Glcd Set Side 450 SPI Glcd Set Page 450 SPI Glcd Set X 450 SPI Glcd Read Data 451 SPI Glcd Write Data 451 SPI Glcd Fill 452 SPI Glcd Dot 452 SPI Glcd Line 453 SPI Glcd V Line 453 SPI Glcd H Line 454 SPI Glcd Rectangle 454 SPI Glcd Rectangle Round Edges 455 SPI Glcd Rectangle Round Edges Fill 455 SPI Glcd Box 456 SPI Glcd Circle 456 SPI Glcd Circle
242. al image image image to be displayed Bitmap array can be located in both code and RAM memory due to the mikroPascal PRO for PIC pointer to const and pointer to RAM equivalency Toshiba Glcd module needs to be initialized See T6963C init routine Draws a 10x15 part of the image starting from the upper left corner on the coordinate 10 12 Original image size is 16x32 T6963C PartizalImage 10 12 10 15 16 32 Cimage Use the integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd T6963C sprite Prototype procedure T6963C sprite px py byte const pic byte sx sy byte Fills graphic rectangle area px py to px sx py sy with custom size picture Parameters px x coordinate of the upper left picture corner Valid values multiples of the font width py y coordinate of the upper left picture corner pic picture to be displayed sx picture width Valid values multiples of the font width sy picture height Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C sprite 76 einstein 119 draw a sprite If ox and sx SECRET are not multiples of the font width they will be scaled to the nearest lower number that is a multiple of the font width MikroElektronika 910 mikroPascal PRO for PIC32 T6963C_set_cursor Prototype procedure T6963C_set_cursor x y byte Se
243. alized See SPI Ethernet 24600 Init IpAddr array 4 of byte IP address IpAddr IpAddr IpAddr IpAddr 192 168 1s Le 0 0 0 0 SPI Ethernet 24j600 arpResolve IpAddr 5 get MAC address behind the above IP address wait 5 secs for the response The Ethernet services are not stopped while this routine waits for ARP reply The incoming packets will be processed normaly during this time SPI Ethernet 24j600 sendUDP Prototype function SPI Ethernet 243600 sendUDP var destIP array 4 of byte sourcePort destPort word pkt byte pktLen word byte This is UDP module routine It sends an UDP packet on the network Parameters Gest IP remote host IP address sourcePort local UDP source port number destPort destination UDP port number pkt packet to transmit pktLen length in bytes of packet to transmit 1 UDP packet was sent successfully 0 otherwise Ethernet module has to be initialized See SPI Ethernet 24j600 Init IpAddr array 4 of byte remote IP address IpAddr IpAddr 192 168 1 1 0 0 IpAddr 0 IpAddr 0 SPI Ethernet 24j600 sendUDP IpAddr 10001 10001 Hello 5 send Hello message to the above IP address from UDP port 10001 to UDP port MikroElektronika A12 mikroPascal PRO for PIC32 SPI Ethernet 24j600 dnsResolve Prototype function SPI Ethernet 243600 dnsResolve var host string tmax byte word D
244. alled a phi function is inserted so that these multiple definitions are merged In mikroPascal PRO for PIC32 SSA s main goal is in allocating local variables into the RX space instead onto the frame To do that SSA has to make an alias and data flow analysis of the Control Flow Graph Besides these savings there are a number of compiler optimization algorithms enhanced by the use of SSA like Constant Propagation Dead Code Elimination Global Value Numbering Register Allocation Changes that SSA brings is also in the way in which routine parameters are passed When the SSA is enabled parameters are passed through a part of the RX space which is reserved exclusively for this purpose Allocating local variables and parameters in RX space has its true meaning for those architectures with hardware frame Enabling SSA optimization in compiler is done by checking nibox from the Output Settings Menu Lets consider a trivial case program Example procedure SSA Test y integer k integer begin if y k then asm nop end end begin SSA Test 5 5 end With SSA enabled procedure SSA _ Test is consisted of 3 asm instructions MikroElektronika 162 mikroPascal PRO for PIC32 Example mpas 29 if yt k then 0x9D000000 0x033A1021 ADDU R2 R25 R26 0x9D000004 0x10400002 BEQ R2 RO L SSA Test2 0x9D000008 0x70000000 NOP Without SSA enabled procedure SSA_Test is consisted of 5 asm
245. als 1230 because 1234 0001 0010 0011 0100 5678 0101 0110 0111 1000 and 0001 0010 0011 0000 that s 1230 i Similarly 1234 or 5678 equals 567C 1234 xor 5678 equals 444C not 1234 equals EDCB 211 MikroElektronika mikoPascal PRO for PIC32 Unsigned and Conversions If a number is converted from less complex to more complex data type the upper bytes are filled with zeroes If a number is converted from more complex to less complex data type the data is simply truncated the upper bytes are lost For example var a byte b word a SAA b SFOFO b b and a a is extended with zeroes b becomes 00A0 Signed and Conversions If number is converted from less complex to more complex data type the upper bytes are filled with ones if sign bit is 1 number is negative the upper bytes are filled with zeroes if sign bit is O number is positive If number is converted from more complex to less complex data type the data is simply truncated the upper bytes are lost For example var a byte b word a i I2 b 70FF b b and a a is sign extended with the upper byt qual to SFF b becomes 70F4 Bitwise Shift Operators Binary operators sn1 and shr move the bits of the left operand by a number of positions specified by the right operand to the left or right respectively Right operand has to be positive and less than 255 With shift lef
246. aluated according to certain conversion grouping associativity and precedence rules which depend on the operators in use presence of parentheses and data types of the operands The precedence and associativity of the operators are summarized in Operator Precedence and Associativity The way operands and subexpressions are grouped does not necessarily specify the actual order in which they are evaluated by mikroPascal PRO for PIC Expression Evaluation General Rule Expression are evaluated according to the right side operands Operations are done at higher operand level with signed operands taking precedence Example a byte b word c integer a b word level c integer level b c integer level w Left side exception In arithmetic expression left side is considered in the following manner If the left side size in bytes is greater than higher operand size then evaluation is done at one level above higher operand level to get correct calculations Example a dword b byte a b 5 this is done at word level 221 MikroElektronika mikoPascal PRO for PIC32 Conditional expressions Conditional expressions may differ from the same code in assignment expressions due to left side exception Example a dword b byte if b 5 then byte level general rule will not give same result as as b 5 word level general rule left sid xception if a then if b
247. ameters Fclk Khz Peripheral Bus Clock frequency in kHz scl requested serial clock rate Nothing Requires MCU with the I C module PC library routines require you to specify the module you want to use To select the desired C module simply change the letter x in the routine prototype for a number from 1 to 5 Number of IC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library I2Cx Start ums Nothing Requires MCU with at least one IPC module Used 1 C module must be initialized before using this function See I2Cx Init routine Issue START signal IZCi Start FC library routines require you to specify the module you want to use To select the desired IC module simply change the letter x in the routine prototype for a number from 1 to 5 Number of I C modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 309 MikroElektronika mikoPascal PRO for PIC32 I2Cx_Restart Reums Noting S Requires MCU with at least one I C module Used lC module must be initialized before using this function See I2Cx Init routine Issue RESTART signal I2Cl Restart FC library routines require you to specify the module you want to use To select the desired C module simply change the letter x in the routine prototype for a number from 1 to 5 Number of IC m
248. amp procedure M Open File Append begin filename 7 B Mmc Fat Assign filename 0 Mmc Fat Set File Date 2009 1 23 17 22 0 Mmc Fat Append Prepare file for append file contents for mikroElektronika 2009 Prepare file for append file contents 26 10 Z4 LE Mmc Fat Write file contents 27 5 Write data to assigned file end Opens an existing file reads data from it and puts it to USART procedure M Open File Read begin filename 7 B Mmc_Fat_Assign filename 0 Mmc Fat Reset size To read file procedure returns size of file while size gt 0 do begin Mmc Fat Read character UART1 Write character Write data to UART Dec size end end J a Ee Deletes a file If file doesn t exist it will first be created Le and then deleted procedure M Delete File begin filename 7 E Mmc Fat Assign filename 0 Mmc Fat Delete end jj eme a Tests whether fil xists and if so sends its creation date 2d and file size via USART procedure M Test File Exist var fsize longint year word month day hour minute byte outstr array 12 of char begin filename 7 B if Mmc Fat Assign filename 0 lt gt 0 then begin file has been found get its date Mmc Fat Get File Date year month day hour minute UART1 Write Text created WordToStr year outstr UART1 Write Text outstr ByteToStr
249. array 2 of char Description Converts input number to a string containing the number s hexadecimal representation The output string is right justified and remaining positions on the left if any are filled with zeros Parameters input signed short number to be converted da destination string var t short txt array 2 of char t c 100 Short ToHex t txt txt is 9C WordToHex Prototype procedure WordToHex input word var output array 4 of char Description Converts input number to a string containing the number s hexadecimal representation The output string is right justified and remaining positions on the left if any are filled with zeros Parameters input unsigned integer to be converted output destination string Nothing var t word txt array 4 of char t c l1ll WordToHex t txt Jf txt is 0457 519 MikroElektronika mikoPascal PRO for PIC32 IntToHex Prototype procedure IntToHex input integer var output array 64 of char Description Converts input number to a string containing the number s hexadecimal representation The output string is right justified and remaining positions on the left if any are filled with zeros Parameters input signed integer number to be converted output destination string var input integer txt string 4 NE input 32768 IntToHex input txt tzt as 180007 LongWordToHex Protot
250. art result result SPI Ethernet putConstString Q0indexPage2 HTML page second part end return to the library with the number of bytes to transmit end i this function is called by the library the user accesses to the UDP request by successive calls to SPI Ethernet getByte the user puts data in the transmit buffer by successive calls to SPI Ethernet putByte the function must return the length in bytes of the UDP reply or 0 if nothing to transmit if you don t need to reply to UDP requests just define this function with a return 0 as single statement function SPI Ethernet UserUDP var remoteHost array 4 of byte remotePort destPort reqLength word var flags TEthPktFlags word var tmp string 5 begin result 0 reply is made of the remote host IP address in human readable format byteToStr remoteHost 0 dyna first IP address byte dyna 3 byteToStr remoteHost 1 tmp second dyna 4 tmp 0 dyna 5 tmp l1 dyna 6 tmp 2 dyna 7 byteToStr remoteHost 2 tmp second dyna 8 tmp 0 dyna 9 tmp 1 dyna 10 tmp 2 dyna 11 byteToStr remoteHost 3 tmp second dyna 12 tmp 0 dyna 13 tmp 1 dyna 14 tmp 2 dyna 15 add separator MikroElektronika 424 mikroPascal PRO for PIC32 then remote host port number WordToStr remotePort tmp dyna 16 tmp 0 dy
251. ary Example 562 HW Connection 563 USB Library 564 USB HID Class 564 Descriptor File 564 Library Routines 564 HID Enable 565 HID Read 565 HID Write 565 HID Disable 566 USB Interrupt Proc 566 USB Polling Proc 567 MikroElektronika 22 mikroPascal PRO for PIC32 Gen_Enable 567 Gen_Read 568 Gen_Write 568 Library Example 569 HW Connection 569 Miscellaneous Libraries 570 Button Library 570 Library Routines 570 Button 570 Button 571 C Type Library 571 Library Functions 571 isalnum 571 isalpha 572 iscntrl 572 isdigit 572 isgraph 572 islower 572 ispunct 573 isspace 573 isupper 573 isxdigit 573 toupper 573 tolower 573 Conversions Library 574 Library Dependency Tree 574 Library Routines 574 ByteToStr 575 ShortToStr 575 WordToStr 576 IntToStr 576 LongToStr 577 LongWordToStr 577 FloatToStr 578 WordToStrWithZeros 578 IntToStrWithZeros 579 LongWordToStrWithZeros 579 LongIntToStrWithZeros 580 ByteToHex 580 ShortToHex 581 WordToHex 581 IntToHex 582 LongWordToHex 582 LongIntToHex 582 StrToInt 583 StrToWord 583 MikroElektronika 23 mikoPascal PRO for PIC32 Bcd2Dec 583 Dec2Bcd 584 Bcd2Dec16 584 Dec2Bcd16 584 Setjmp Library 585 Library Routines 585 Setjmp 585 Longjmp 585 Library Example 586 Sprint Library 587 Library Dependency Tree 587 Functions 587 memchr 588 memcmp 588 memcpy 589 memmove 589 memset 589 strcat 590 strcat2 590 strchr 590 strcmp 591 strcpy 591 strlen 591 strncat 591 strncpy
252. ascal PRO for PIC32 Also it is possible to add all variables in the Watch Values Window by clicking AddAll button To remove a variable from the Watch Values Window just select the variable that you want to remove and then click the 96 Remove button or press the Delete key It is possible to remove all variables from the Watch Values Window by clicking Remove All button You can also expand collapse complex variables i e struct type variables strings etc by clicking the appropriate button or beside variable name Watch Values AES Bi Ex Select variable from list PC 0x00028E 9655 99 ms Double clicking a variable or clicking the S Properties button opens the Edit Value window in which you can assign a new value to the selected variable register Also you can choose the format of variable register representation between decimal hexadecimal binary float or character All representations except float are unsigned by default For signed representation click the check box next to the Signed label D Edit Value PORTB Representation S Dec O Hex O Bin O Float O Char C Signed OK Cancel An item s value can also be changed by double clicking item s value field and typing the new value directly 121 MikroElektronika mikoPascal PRO for PIC32 RAM Window The RAM Window is available from the drop down menu View Debug Windows RAM The RAM Window displays the ma
253. ascal PRO for PIC32 In first case compiler will recognize your attempt but in order to save Flash space and boost performance it will automatically replace all instances of this constant in code with it s literal value In the second case your constant will be placed in Flash in the exact location specified To place a routine on a specific address in Flash memory you should write the following procedure proc par byte org 0x9D000000 begin Procedure will start at address 0x9D000000 end org directive can be used with main routine too For example program Led Blinking begin org 0x9D000000 main procedure starts at 0x9D000000 end Directive orgall Use the orgall directive to specify the address above which all routines and constants will be placed Example begin orgall 0x9D000000 All the routines constants in main program will be above the address 0x9D000000 end 143 MikroElektronika mikoPascal PRO for PIC32 Built in Routines mikroPascal PRO for PIC32 compiler provides a set of useful built in utility functions Built in functions do not have any special requirements You can use them in any part of your project The Delay us and Delay ms routines are implemented as inline i e code is generated in the place of a call so the call doesn t count against the nested call limit The Vdelay ms Vdelay advanced ms Delay Cyc Delay Cyc Long Get Fosc kHz and Get Fosc Per_ Cyc are
254. at RF2 bit external a var Soft I2C Scl Direction Direction of the Soft IC Clock var Soft I2C Scl Direction sbit at Sbit sfr external pin TRISF3 bit var Soft I2C Sda Direction 3 var Soft I2C Sda Direction sbit at shiti afr external Direction of the Soft I C Data pin TRISF2 bit Library Routines Soft I2C Init Soft I2C Start Soft I2C Read Soft I2C Write Soft I2C Stop Soft I2C Break 371 MikroElektronika mikoPascal PRO for PIC32 Soft I2C Init Rms non OOOO SSS Requires Global variables Soft I2C Scl Soft I C clock line Soft I2C Sda Soft FC data line Soft I2C Scl Pin Direction Direction of the Soft I C clock pin Soft I2C Sda Pin Direction Direction of the Soft I C data pin must be defined before using this function Software I2C connections var Soft IZC Sel sbit at RF3 bit Soft I2C Sda sbit at RF2 bit Soft I2C Scl Direction sbit at TRISF3 bit Soft I2C Sda Direction sbit at TRISF2 bit End Software I2C connections Soft I2C Inzt Soft I2C Start Reums Nothing Software I C must be configured before using this function See Soft I2C Init routine Issue START signal Soft I2C Start MikroElektronika 378 mikroPascal PRO for PIC32 Soft I2C Read Prototype function Soft I2C Read ack word byte Description Reads one byte from the slave Parameters ack acknowledge signal parameter If the
255. at Rewrite for loop l to 55 do begin file contents 0 file contents 1 Cf Fat Write file contents LIN end end 0 E LEN 1 Set filename for single file tests byte loop div 10 48 byte loop mod 10 48 write data to the assigned file 213 MikroElektronika mikoPascal PRO for PIC32 ff sesh eaSrasss Opens an existing file and appends data to it Lf and alters the date time stamp procedure M Open File Append begin filename 7 B Cf Fat Assign filename 0 Cf Fat Set File Date 2009 Cf Fat Append file contents file contents 26 13 file contents 27 10 Cf Fat Write file contents 27 pa 237 LX 22 Em 7 end fg ee Opens an existing file procedure M Open File Read begin filename 7 B Cf Fat Assign filename 0 Cf Fat Reset size while size 0 do begin Cf Fat Read character UART1 Write character Dec size end end jf ene IE EE Deletes a file If file doesn t exist if and then deleted procedure M Delete File begin filename 7 F Cf Fat Assign filename 0 Cf Fat Delete end f Tests whether fil xa SES ad and file size via USART procedure M Test File Exist var fsize longint year word month day hour minute byte outstr array 12 of char begin filename 7 B uncomment this line filename 7
256. awing demo tests advanced routines of the SPI T6963C Glcd library Hardware configurations in this example are made for the LV 32MX v6 board and PIC32MX460F512L Copy Code To Clipboard program SPI T6963C 240x128 uses Lib SPIT6963C Const var Port Expander module connections SPExpanderRST sbit at LATD8 bit for writing to output pin always use latch SPExpanderCS sbit at LATD9 bit for writing to output pin always use latch SPExpanderRST Direction sbit at TRISD8 bit SPExpanderCS Direction sbit at TRISD9 bit End Port Expander module connections var panel byte current panel i word general purpose register curs byte cursor visibility Cposx cposy word cursor x y position txt txtl string 29 txt2 string 21 491 MikroElektronika mikoPascal PRO for PIC32 begin SDEFINE COMPLETE EXAMPLE SDEFINE LINE DEMO SDEFINE FILL DEMO SDEFINE PARTIAL IMAGE DEMO txtl EINSTEIN WOULD HAVE LIKED mE txt GLCD LIBRARY DEMO WELCOME txt2 Partial image demo CHECON 0x32 ADIPCFG OxFFFF initialize AN pins as digital TRISBG bit l Set RB8 as input TRISB9 bit 1 Set RB9 as input TRISB10 bit 1 Set RB10 as input TRISB11 bit 1 Set RB11 as input TRISB12 bit 1 Set RB12 as input TRISBI3 bit 1 Set RB13 as input bait 2 x8 bit i xs bie Q zs init display for 240 pixel width and 128 pixel heigh
257. ay GrLayer 285 S1D13700 Display TxtLayer 286 S1D13700 Set Cursor 286 S1D13700 Display Cursor 287 S1D13700 Write Char 287 S1D13700 Write Text 288 S1D13700 Dot 288 S1D13700 Line 289 S1D13700 H Line 289 S1D13700 V Line 290 S1D13700 Rectangle 290 S1D13700 Box 291 S1D13700 Rectangle Round Edges 291 S1D13700 Rectangle Round Edges Fill 292 MikroElektronika 12 mikroPascal PRO for PIC32 S1D13700 Circle 292 S1D13700 Circle Fill 293 S1D13700 Image 293 S1D13700 Partiallmage 294 Flash Memory Library 294 Library Routines 294 Flash Write Word 295 Flash Write Row 295 Flash Erase Page 295 Graphic Lcd Library 296 Library Dependency Tree 296 External dependencies of Graphic Lcd Library 297 Library Routines 298 Glcd Init 298 Glcd Set Side 300 Glcd Set X 300 Glcd Set Page 300 Glcd Read Data 301 Glcd Write Data 301 Glcd Fill 302 Glcd Dot 302 Glcd Line 302 Glcd V Line 303 Glcd H Line 303 Glcd Rectangle 304 Glcd Rectangle Round Edges 304 Glcd Rectangle Round Edges Fill 305 Glcd Box 305 Glcd Circle 306 Glcd Circle Fill 306 Glcd Set Font 307 Glcd Write Char 308 Glcd Write Text 308 Glcd Image 309 Glcd Partiallmage 309 lC Library 310 Library Routines 310 I2Cx Init 310 I2Cx Init Advanced 311 I2Cx Start 311 I2Cx Restart 312 I2Cx Is Idle 312 I2Cx Read 313 I2Cx Write 313 I2Cx Stop 314 Library Example 314 MikroElektronika 13 mikoPascal PRO for PIC32 Keypad Library 316 External dependencies of Keypad Library 316 L
258. ble for mobile applications such as PDAs MP3 players or mobile measurement equipment Although this controller is small it has a capability of displaying and merging text and graphics and it manages all interfacing signals to the displays Row and Column drivers For creating a custom set of Glcd images use Glcd Bitmap Editor Tool Important When using this library with PIC32 family MCUs be aware of their voltage incompatibility with certain number of T6963C based Glcd modules So additional external power supply for these modules may be required Glcd size based initialization routines can be found in setup library files located in the Uses folder The user must make sure that used MCU has appropriate ports and pins If this is not the case the user should adjust initialization routines The library uses the SPI module for communication The user must initialize the appropriate SPI module before using the SPI T6963C Glcd Library For MCUs with multiple SPI modules it is possible to initialize both of them and then switch by using the SPI Set Active routine See the SPI Library functions This Library is designed to work with mikroElektronika s Serial Glcd 240x128 and 240x64 Adapter Boards pinout see schematic at the bottom of this page for details To use constants located in Lib SPIT6963C Const mpas file user must include it the source file uses Lib SPIT6963C Const Some mikroElektronika s adapter boards have pino
259. bled at the same time For this purpose predefined library constants see the table below can be ORed to form appropriate input value Parameters i sr 1t network traffic receive filter flags Each bit corresponds to the appropriate network traffic receive filter 0x01 MAC Broadcast traffic receive filter flag When set MAC SPI Ethernet 243600 broadcast traffic will be disabled BROADCAST multicast traffic will be disabled MULTICAST Pe footnoted e S 7 0x80 MAC Unicast traffic receive filter flag When set MAC SPI Ethernet 24 600 unicast traffic will be disabled UNICAST Ethernet module has to be initialized See SPI Ethernet 24 600 Init SPI Ethernet 24j600 Disable SPI Ethernet 247600 CRC Ethernet 24j600 UNICAST disable CRC checking and Pg traffic Advanced filtering available in the ENC24J600 module such as Pattern Match Magic Packet and Hash Table can not be disabled by this routine This routine will change receive filter configuration on the fly It will not in any way mess with enabling disabling receive transmit logic or any other part of the ENC247600 module The NC243600 module should be properly cofigured by the means of SPI Ethernet 243600 Init routine The ENC243600 module should be properly cofigured by the means of SPI Ethernet 24j600 Init routine MikroElektronika 434 mikroPascal PRO for PIC32 SPI Ethernet 24j600 doPacket Prototype function SPI Ethernet
260. bles of volatile word These identifiers have an external linkage and are visible in the entire project When creating a project the mikroPascal PRO for PIC32 will include an appropriate mpas file from defs folder containing declarations of available SFRs and constants such as PORTB ADPCFG etc All identifiers are in upper case identical to nomenclature in the Microchip datasheets For a complete set of predefined globals and constants look for Defs in the mikroPascal PRO for PIC32 installation folder or probe the Code Assistant for specific letters Ctrl Space in the Code Editor Predefined project level defines mikroPascal PRO for PIC32 provides predefined project level defines that you can use in your project First one is equal to the name of selected device for the project For example SIFDEF P32MX460F512L SENDIF Second one is equal to the family name SIFDEF PIC32 SENDIF Related topics Project Level Defines MikroElektronika 134 mikroPascal PRO for PIC32 Accessing Individual Bits The mikroPascal PRO for PIC32 allows you to access individual bits of 32 bit variables It also supports sbit and bit data types Lets use the Zero bit as an example This bit is defined in the definition file of the particular MCU as const Z 1 var Z bit sbit at SR Bl1 To access this bit in your code by its name you can write something like this Clear Zero Bit SR Z 0 In th
261. c kHz is a library function rather than a built in routine it is presented in this topic for the sake of convenience Get_Fosc_Per_Cyc Prototype function Get Fosc Per Cyc word Description Function returns device s clock per cycle rounded to the nearest integer Note that Get Fosc Per Cyc is library function rather than a built in routine it is presented in this topic for the sake of convenience Returns Device clock in kHz var clk per cyc word elk per cyc Get Fose Per Cyc Reset Prototype procedure Reset This procedure is equal to assembler instruction reset eum Noting Example neset 77 resets mewo OOOO etes None SCS 153 MikroElektronika mikoPascal PRO for PIC32 ClrWat Prototype procedure ClrWdt This procedure is equal to assembler instruction cl wat Rems Nothing SS Example ermar 7 Gies p OOOO oes None S DisableContextSaving Prototype procedure DisableContextSaving Description Use the DisableContextSaving to instruct the compiler not to automatically perform context Switching This means that no register will be saved restored by the compiler on entrance exit from interrupt service routine This enables the user to manually write code for saving registers upon entrance and to restore them before exit from interrupt Parameters None This routine must be called from main DisableContextSaving instruct t
262. cal PRO for PIC32 break continue exit goto asm Statement mikroPascal PRO for PIC32 allows embedding assembly in the source code by means of the asm statement Note that you cannot use numerals as absolute addresses for register variables in assembly instructions You may use symbolic names instead listing will display these names as well as addresses You can group assembly instructions with the asm keyword asm block of assembly instructions end The only types whose name remains the same in asm as it is in the mikroPascal PRO for PIC32 are registers e g INTCON PORTB WREG GIE etc mikroPascal PRO for PIC32 comments are allowed in embedded assembly code Accessing variables Depending on the place of declaration accessing a variable can be done in several ways Accessing global variable 1 If declared under implementation section visible only in the file where it was declared source file _ name variable name 2 If declared in the interface section visible throughout the whole project variable name gt 3 If accessing registers declared through register rx or sfr specifiers visible throughout the whole project variable name Accessing local variable lt routine name variable name gt Accessing routine parameter FARG routine name variable name gt MikroElektronika 228 mikroPascal PRO for PIC32 Here is an example of using asm instructions prog
263. card abbr CF further in text CF cards are widely used memory elements commonly used with digital cameras Great capacity and excellent access time of only a few microseconds make them very attractive for microcontroller applications In CF card data is divided into sectors One sector usually comprises 512 bytes Routines for file handling the Cf Fat routines are not performed directly but successively through 512B buffer Important Routines for file handling can be used only with FAT16 file system Library functions create and read files from the root directory only Library functions populate both FAT1 and FAT2 tables when writing to files but the file data is being read from the FAT1 table only i e there is no recovery if the FAT1 table gets corrupted If MMC SD card has Master Boot Record MBR the library will work with the first available primary logical partition that has non zero size If MMC SD card has Volume Boot Record i e there is only one logical partition and no MBRs the library works with entire card as a single partition For more information on MBR physical and logical drives primary secondary partitions and partition tables please consult other resources e g Wikipedia and similar Before writing operation make sure not to overwrite boot or FAT sector as it could make your card on PC or digital camera unreadable Drive mapping tools such as Winhex can be of great assistance Library Dependency
264. case that errors were encountered during compiling the compiler will report them and won t generate a hex file The Messages Window will display errros at the bottom of the window by default The compiler also reports warnings but these do not affect the output only errors can interefere with the generation of hex Messages Errors Warnings Hints Line Message No Message Text Unit 1 mPPIC32 exe DBG pP32MX460F512L MSF DL SS 133 Compilation Started C Program Files Mikroelektronika mikroPascal PRO for PI 1015 Hint Compiling unit C Program Files Mikroelektroni __Lib_Delays mpas 1010 Hint Unit Lib Delays mpas has been recompiled Lib Delays mpas 134 Compiled Successfully C Program Files Mikroelektronika mikroPascal PRO For PI 133 Compilation Started C Program Files Mikroelektronika mikroPascal PRO For PI 1015 Hint Compiling unit C Program Files Mikroelektroni LCD mpas 1010 Hint Unit LCD mpas has been recompiled LCD mpas 134 Compiled Successfully C Program Files Mikroelektronika mikroPascal PRO For PI 139 All Files Compiled in 16 ms 1144 Used RX bytes 32 100 Free RX bytes 0 0 Used RX bytes 32 100 Free RX bytes 0 0 1144 Static RAM bytes 46 Dynamic RAM bytes 32718 Static RAM bytes 46 Dynamic RAM bytes 32718 1144 Used ROM bytes 3356 1 Free ROM bytes Used ROM bytes 3356 1 Free ROM bytes 52093 145 Project Linked Successfully LCD mpp32 140 Lin
265. cies of Touch Panel Library The following variables must be defined in Description all projects using Touch Panel Library var DriveA sbit sfr external var DriveA sbit at LATC13 bit var DriveB sbit sfr external var DriveB sbit at LATC14 bit var DriveA Direction sbit sfr Direction of the DriveA pin var DriveA Direction sbit at external TRISCI3 bit var DriveB Direction sbit sfr Direction of the DriveB pin var DriveB Direction sbit at external TRISC14 bit Library Routines TP Init TP Set ADC Threshold TP Press Detect TP Get Coordinates TP Calibrate Bottom Left TP Calibrate Upper Right TP Get Calibration Consts TP Set Calibration Consts 541 MikroElektronika mikoPascal PRO for PIC32 TP_Init Prototype procedure TP ee due i width word display height word readX ChNo byte readY ChNo byte Initialize touch panel display Default touch panel ADC threshold value is set to 3900 Parameters display width set display width display height set display height readX ChNo read X coordinate from desired ADC channel readY ChNo read Y coordinate from desired ADC channel Before calling this function initialize ADC module ADC1 Init Initalize ADC module TP Init 128 Initialize touch panel dimensions 128x64 TP_Set_ADC_Threshold eee procedure TP Set ADC Threshold threshold word Set custom ADC threshold value ca
266. clicking the Seven Segment Editor Icon min from Tools toolbar Seven Segment Editor Common cathode 113 Com i UDP Terminal The mikroPascal PRO for PIC32 includes the UDP Terminal You can launch it from the drop down menu Tools UDP Terminal MikroElektronika UDP Terminal Settings IP Address 192 168 020 025 Connect Send mikroElektronika Append CR Send as typing Pie F Send as number mikroElektronika mikroElektronika MikroElektronika 92 mikroPascal PRO for PIC32 USART Terminal The mikroPascal PRO for PIC32 includes the USART communication terminal for RS232 communication You can launch it from the drop down menu Tools USART Terminal or by clicking the USART Terminal Icon A from Tools toolbar Send kj mikroElektronika Send Repeat sending Support ASCH AppendNew Line 65 Sendascu Repeat sending every ge 190 3 miseris aes amr mE rt viv ex mikoPascal PRO for PIC32 Active Comments The idea of Active Comments is to make comments alive and give old fashioned comments new meaning and look From now on you can assign mouse event on your comments and tell your comments what to do on each one For example on left mouse click open some web address in your browser on mouse over show some picture and on mouse double click open some file Suppose we are writing a example for a GSM GPSR module which is
267. co1 brate Botton lef 77 Calibration of bottom eft comer Notes None LL TP_Calibrate_Upper_Right Reums Nang SS Example TP Calibrate Upper Right Calibration of upper right corner Notes None SSS MikroElektronika 544 mikroPascal PRO for PIC32 TP Get Calibration Consts Prototype procedure TP Get Calibration Consts x min word x max word y min word y max word Description Gets calibration constants after calibration is done and stores them in x min x max y min and y max parameters Parameters x min x coordinate of the bottom left corner of the working area x max X coordinate of the upper right corner of the working area y min y coordinate of the bottom left corner of the working area y max y coordinate of the upper right corner of the working area TP Get Calibration Consts x min y min 8x max y max calibration constants TP Set Calibration Consts Prototype procedure TP Set Calibration Consts x min word x max word y min word y max word Sets calibration constants Parameters min X coordinate of the bottom left corner of the working area X coordinate of the upper right corner of the working area y coordinate of the bottom left corner of the working area 2 y coordinate of the upper right corner of the working area TP Set Calibration Consts 148 3590 519 3370 Set calibration constants 515 MikroElektronika
268. connected to the EasyPIC6 and we would like to provide a photo of our hardware jumpers cables etc within the example It would also be nice to put some documentation about chip we are using and a GSM module extra board Now we can have all those things defined in one single comment using Active Comment Editor New Active Comment When you start Active Comment Editor for the first time from the View menu from editor s pop up menu or by pressing Ctrl Alt P you will get an empty editor Active Comments Editor Select Active Comment Active Comment Actions New Rename Delete Properties Add Image to Project AGG File To Project By clicking the New button you are prompted to enter a name for the comment MikroElektronika 94 mikroPascal PRO for PIC32 Active Comments Editor Enter comment name activeComment Active Comment Actions New Rename Properties Attributes Url Image File 3 Events OnLeftClick Alt N OnRightClick OnDblClick OnMouseOver Add Image To Project Add File To Project You can notice that when you start typing a name properties pane is automatically displayed so you can edit properties if you wish AComment will be is created when you click Save button Properties are consisted of two major categories Attributes and Events Attributes can be URL Valid web address Image Image has to be previously added to Proj
269. d local declarations begin end end Note Constants types and variables used in the implementation section are inaccessible to other units This feature is not applied to the procedures and functions in the current version but it will be added to the future ones Functions and procedures must have the same declarations in the interface and implementation section Otherwise compiler will report an error Scope and Visibility Scope The scope of an identifier is a part of the program in which the identifier can be used to access its object There are different categories of scope which depends on how and where identifiers are declared Identifier is declared in the declaration of a Scope extends from the point where it is declared to the end of the program function or procedure current block including all blocks enclosed within that scope Identifiers in the outermost scope file scope of the main unit are referred to as globals while other identifiers are locals Identifier is declared in the interface section Scope extends the interface section of a unit from the point where it is of a unit declared to the end of the unit and to any other unit or program that uses that unit Identifier is declared in the implementation Scope extends from the point where it is declared to the end of the unit section of a unit but not within the block of The identifier is available to any function or procedure in the
270. d HID Write HID Disable USB Interrupt Proc USB Polling Proc Gen Enable Gen Read Gen Write MikroElektronika 962 mikroPascal PRO for PIC32 HID Enable Prototype procedure HID Enable readbuff byte writebuff byte Enables USB HID communication Parameters readbuff Read Buffer writebuff Write Buffer These parameters are used for HID communication HID Enable amp readbuff amp writebuff 0D 0000000000000 amp readbuff amp writebuff e i edem sd are aha aaa SSSA This function needs to be called before using other routines of USB HID Library HID Read Receives message from host and stores it in the Read Buffer If the data reading has failed the function returns 0 Otherwise it returns number of characters received from the host USB HID needs to be enabled before using this function See HID Enable retry until success while HID Read 0 do HID Write Prototype function HID Write writebuff byte len byte byte Function sends data from Write Buffer writebuff to host Parameters writebuff Write Buffer same parameter as used in initialization see HID Enable Len specifies a length of the data to be transmitted pun If the data transmitting has failed the function returns 0 Otherwise it returns number of transmitted bytes USB HID needs to be enabled before using this function See HID Enable retry until
271. d LCD CURSOR OFF lf Turn cursor off SPI Lcd8 Out 1 6 mikroE Print text to Lcd lst row 6th column SPI Lcd8 Chr CP Append SPI Lcd8 Out 2 1 text Print text to Led 2nd row lst column Delay ms 2000 Moving text for counter 0 to 3 do Move text to the right 4 times begin Spi Lcd8 Cmd LCD SHIFT RIGHT Move Delay end while TRUE do Endless loop begin for counter 0 to 6 do Move text to the left 7 times begin Spi Lcd8 Cmd LCD SHIFT LEFT Move Delay end for counter 0 to 6 do Move text to the right 7 times begin Spi Lcd8 Cmd LCD SHIFT RIGHT Move Delay end end end 473 MikroElektronika mikoPascal PRO for PIC32 VOCS D2 CBDDZ DDDD DDD DDD2 OSCILLATOR g 1 o imm PIC32MX460F512L s06 C o we LI L 1 Saar OT Adjustment illl d LLLI t ovCc3 ovcca a zz SPI Lcd8 HW connection MikroElektronika 474 mikroPascal PRO for PIC32 SPI T6963C Graphic Lcd Library The mikroPascal PRO for PIC32 provides a library for working with Glcds based on TOSHIBA T6963C controller via SPI interface The Toshiba T6963C is a very popular Lcd controller for the use in small graphics modules It is capable of controlling displays with a resolution up to 240x128 Because of its low power and small outline it is most suita
272. d pin byte time word ActiveState byte word Description The function eliminates the influence of contact flickering upon pressing a button debouncing The Button pin is tested just after the function call and then again after the debouncing period has expired If the pin was in the active state in both cases then the function returns 255 true Parameters port button port address pin button pin time debouncing period in milliseconds active state determines what is considered as active state Valid values 0 logical zero and 1 logical one 255 if the pin was in the active state for given period 0 otherwise program Button Test var oldstate bit begin oldstate 0 ADPCFG OxFFFF initialize AN pins as digital TRISD OxFFFF initialize PORTD as input TRISB 0x0000 initialize PORTB as output MikroElektronika 568 mikroPascal PRO for PIC32 Button while TRUE begin if Button PORTD O0 1 1 detect logical one on RBO pin oldstate 1 if oldstate and Button PORTD O 1 0 begin detect one to zero transition on RBO pin LATB not LATB oldstate 0 end end endless loop end C Type Library The mikroPascal PRO for PIC32 provides a set of library functions for testing and mapping characters Library Functions isalnum isalpha iscntrl isdigit isgraph islower ispunct isspace isupper isxdigit toup
273. d Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd 485 MikroElektronika mikoPascal PRO for PIC32 SPI_T6963C_sprite Prototype eas SPI T6963C sprite px py byte const pic byte sx sy byte Fills UE rectangle area px py to px sx py sy with custom size picture Parameters x x coordinate of the upper left picture corner Valid values multiples of the font width py y coordinate of the upper left picture corner pic picture to be displayed sx picture width Valid values multiples of the font width sy picture height Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C sprite 76 4 einstein 119 draw a sprite If ox and sx parameters are not multiples of the font width they will be scaled to the nearest lower number that is a multiple of the font width SPI T6963C set cursor y cursor position column number ums Nin OSS yS Example SPI T6963C set cursor cposx cposy Nes None OOS SPI T6963C clearBit Prototype procedure SPI T6963C clearBit b byte Clears control port bit s Parameters bit mask The function will clear bit x on control port if bit x in bit mask is set to 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine clear bits 0 and 1 on control port SPI T6963C clearBit 0x03 Notes Nm OOOO Mi
274. d optional description target device device flags config word device clock list of the project source files with paths binary files emcl image files other files Note that the project does not include files in the same way as preprocessor does see Add Remove Files from Project 601 MikroElektronika mikoPascal PRO for PIC32 New Project The easiest way to create a project is by means of the New Project Wizard drop down menu Project New Project or by clicking the New Project Icon from Project Toolbar New Project Wizard Steps Start creating your New project by clicking Next button New Project Wizard Welcome to the New Project Wizard This wizard helps you e Create a new project e Select the device for your project e Setup device clock e Add project files Click Next to continue New Project Wizard Step 1 6 Select the device you want to use Device Name P32MX460F512L Cancel MikroElektronika 602 mikroPascal PRO for PIC32 Step Two Enter the oscillator frequency value New Project Wizard Step 2 6 Setup the clock for example 11 0592 MHz Device Clock 10 000000 Cancel Step Three Specify the location where your project will be saved New Project Wizard Step 3 6 Specify where your project will be saved Project File Name C Hello World Hello World mpp32 Cancel 603 MikroElektronika m
275. d radius word color byte Description Draws a rounded edge rectangle on Glcd Parameters x upper left x coordinate of the upper left rectangle corner y upper left y coordinate of the upper left rectangle corner x bottom right x coordinate of the lower right rectangle corner y bottom right y coordinate of the lower right rectangle corner round radius radius of the rounded edge pcolor color parameter Valid values S1D13700 BLACK Black color 1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine S1D13700 Rectangle Round Edges 20 20 219 107 12 S1D13700 WHITE 289 MikroElektronika mikoPascal PRO for PIC32 S1D13700 Rectangle Round Edges Fill Prototype procedure S1D13700 Rectangle Round Edges Fill x upper left word y upper left word x bottom right word y bottom right word round radius word color byte Description Draws a filled rounded edge rectangle on Glcd Parameters x upper left x coordinate of the upper left rectangle corner y upper left y coordinate of the upper left rectangle corner x bottom right x coordinate of the lower right rectangle corner y bottom right y coordinate of the lower right rectangle corner round radius radius of the rounded edge pcolor color parameter Valid values S1D13700 BLACK Black color S1D13700 WHITE White color Glcd module needs to be initialized See the S
276. de values from 64 to 127 specify the right side Glcd needs to be initialized for SPI communication see SPI Glcd Init routine The following two lines are equivalent and both of them select the left side of Glcd SPI Glcd Set Side 0 SPI Gled Set Side 10 Notes For side x axis and page layout explanation see schematic at the bottom of this page SPI Glcd Set Page Prototype procedure SPI Glcd Set Page page byte Retums r255 page number Vaid values Example SPI Gled Set Page S S O Notes For side x ans and page layout explanation see schematic al the bottom ofthis page SPI Glcd Set X Prototype procedure SPI Glcd Set X x pos byte Sets x axis position to x pos dots from the left border of Glcd within the selected side Parameters x pos position on x axis Valid values 0 63 Rems No OOOO Dampe ser erca sexes O OOOO Notes Forside x axis and page layout explanation see schematic atthe botom ofthis pags MikroElektronika 448 mikroPascal PRO for PIC32 SPI Glcd Read Data Description Reads data from the current location of Glcd memory and moves to the next location One byte from Glcd memory Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Glcd side x axis position and page should be set first See the functions SPI Glcd Set Side SPI Glcd Set X and SPI Glcd Set Page Parameters None
277. declaration creates two instances of TDot called m and n A field can be of previously defined record type For example Structure defining a circle type TCircle record radius real center TDot end Accessing Fields You can access the fields of a record by means of dot as a direct field selector If we have declared variables circlel and circle2 of previously defined type TCircle var circlel circle2 TCircle we could access their individual fields like this MikroElektronika 210 mikroPascal PRO for PIC32 circlel radius 3 7 circlel center x 0 0 circlel center y Accessing the fields is possible via the with statement as well You can also commit assignments between complex variables if they are of the same type circle2 circlel This will copy values of all fields Types Conversions Conversion of variable of one type to a variable of another type is typecasting mikroPascal PRO for PIC32 supports both implicit and explicit conversions for built in types Implicit Conversion Compiler will provide an automatic implicit conversion in the following situations statement requires an expression of particular type according to language definition and we use an expression of different type operator requires an operand of particular type and we use an operand of different type function requires a formal parameter of particular type and we pass it an object
278. diagrama to open R in a new window Project Name Cil pevelopment SystemsiLvaaek ved COG Sayida Tee IRI OAM remiron so Functions Sorted By Size Chart Sorts and displays functions by their sizes in a chart like form Double cick on diagram to open it in a new window Project Name C14 Development SystemslLV32Mx v lL CD COG 2x16 lLcd mda Time 131 2011 1 03 40 FM vesvumiros com mikoPascal PRO for PIC32 Functions Sorted By Addresses Sorts and displays functions by their addresses in the ascending order 1 800 000 000 1 500000 000 Double click on diagram to open R in a new window Project Name C t Development SystemslL VX2MX v6lLCD COG 2x16 yiLed mep32 ermine com Function Tree Displays Function Tree with the relevant data for each function Project Name C Development Systems V32MX v l CD COG 2x16 lcd mca Time 1 31 2011 1 03 40 PM weeny mires com mikroPascal PRO for PIC32 Memory Summary Displays summary of RAM and ROM memory in a pie like form mikoPascal PRO for PIC32 Messages Window Messages Window displays various informations and notifications about the compilation process It reports for example time needed for preprocessing compilation and linking used RAM and ROM space generated baud rate with error percentage etc The user can filter which notifications will Messages Window display by checking Errors Warning and Hints box In
279. diff Time dateDiff tsl ts2 diff 86163870 end TimeStruct type definition type TimeStruct record ss byte seconds mn byte minutes hh byte hours md byte day in month from 1 to 31 wd byte day in week monday 0 tuesday 1 sunday 6 mo byte month number from 1 to 12 and not from 0 to 11 as with unix C time yY word year Y2K compliant from 1892 to 2038 end mikoPascal PRO for PIC32 Trigon Library The mikroPascal PRO for PIC32 provides a set of library functions for floating point math handling See also Predefined Globals and Constants for the list of predefined math constants Library Functions acos asin atan atan2 ceil COS cosh eval_poly exp fabs floor frexp ldexp log log10 modf pow sin sinh sqrt tan tanh acos Prototype function acos x real real Description Function returns the arc cosine of parameter x that is the value whose cosine is x The input parameter x must be between 1 and 1 inclusive The return value is in radians between 0 and M inclusive Example res acos 0 5 res 1 047198 asin Prototype function asin x real real Description Function returns the arc sine of parameter x that is the value whose sine is x The input parameter x must be between 1 and 1 inclusive The return value is in radians between 1 2 and 11 2 i
280. digits matches the character whose ASCII value is nn If you need wide Unicode character code you can use x nnnn where nnnn one or more hexadecimal digits xnn char with hex code nn Xx nnnn char with hex code nnnn one byte for plain text and two bytes for Unicode t tab HT TAB same as x09 n newline NL same as x0a Vr car return CR same as x0d X form feed FF same as x0c a alarm bell BEL same as x07 Ve escape ESC same as x1b Examples unsigned x20int matches unsigned int note space in the middle tunsigned matches unsigned predecessed by tab Character classes You can specify a character class by enclosing a list of characters in which will match any of the characters from the list If the first character after the is the class matches any character not in the list 105 MikroElektronika mikoPascal PRO for PIC32 Examples count aeiou r finds strings countar counter etc but not countbr countcr etc count aeiou r finds strings countbr countcr etc but not countar counter etc Within a list the character is used to specify a range so that a z represents all characters between a and z inclusive If you want itself to be a member of a class put it at the start or end of the list or precede it with a backslash If you want you may place it at the start of list or precede it with
281. e SPI Glced Circle Fill SPI Glcd Set Font SPI Glcd Write Char SPI Gled Write Text SPI Gled Image SPI Gled Partiallmage SPI Glcd Init Prototype procedure SPI Glcd Init DeviceAddress byte Description Initializes the Glcd module via SPI interface Parameters DeviceAddress SPI expander hardware address see schematic at the bottom of this page Nothing Requires Global variables SPExpanderCs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before using this function The SPI module needs to be initialized See SPIx_Init and SPIx Init Advanced routines Port Expander module connections var SPExpanderRST sbit at LATFO bit SPExpanderCS sbit at LATFI bit SPExpanderRST Direction sbit at TRISFO bit SPExpanderCS Direction sbit at TRISF1 bit End Port Expander module connections If Port Expander Library uses SPI module SPI Init Initialize SPI module used with PortExpander SPI Glcd Init 0 44 MikroElektronika mikoPascal PRO for PIC32 SPI Glcd Set Side Prototype procedure SPI Glcd Set Side x pos byte Selects Glcd side Refer to the Glcd datasheet for detail explanation Parameters x pos position on x axis Valid values 0 127 The parameter x os specifies the Glcd side values from 0 to 63 specify the left si
282. e non greedy similar to 0 1 n exactly n times non greedy n atleast n times non greedy n m atleast n but not more than m times non greedy So digits in curly brackets of the form n m specify the minimum number of times to match the item n and the maximum m The form n is equivalent to n n and matches exactly n times The form n matches n or more times There is no limit to the size of n or m but large numbers will chew up more memory and slow down execution If a curly bracket occurs in any other context it is treated as a regular character 107 MikroElektronika mikoPascal PRO for PIC32 Examples count r B matches strings like counter countelkjdflkj9r and countr count 4r matches strings like counter countelkjdflkj9r but not countr count r matches strings like counter countar and countr but not countelkj9r counte 2 r matches string counteer counte 2 r matches strings like counteer counteeer counteeer etc counte 2 3 r matches strings like counteer or counteeer but not counteeeer A little explanation about greediness Greedy takes as many as possible non greedy takes as few as possible For example b and b applied to string abbbbc return bbbb b returns b b returns empty string b 2 3 returns bb b 2 3 returns bbb Metacharacters Alternatives You can specify a series
283. e k character of the txt string 591 MikroElektronika mikoPascal PRO for PIC32 Itrim Bin iba procedure ltrim var astring string The trims the Ee spaces of the string mikrol ltrim txt trims the leading 2 spaces of the txt string rtrim PTORAUBe procedure rtrim var astring string The procedure trims the zii spaces of the string mikroE FELTON ERE trims the trailing 2 spaces of the txt string and adds terminating null character to the result strappendpre ere procedure strappendpre letter char var sl string The procedure dient character at the beginning of the string txt ikroE strappendpre m txt adds letter m at the beginning of the txt string strappendsuf NS Li procedure strappendsuf var sl string letter char The TM appends character at the end of the string mikro strappendsuf E txt adds letter E at the end of the txt string length pee function length var s string word The function returns E of passed string xt mikrol res length txt calculates and returns the length of the txt string MikroElektronika 592 mikroPascal PRO for PIC32 Time Library The Time Library contains functions and type definitions for time calculations in the UNIX time format which counts the number of seconds since the epoch
284. e 0 CANSPI FILTER B1 F2 byte 1 CANSPI FILTER B2 Fl byte 2 CANSPI FILTER B2 F2 byte 3 CANSPI FILTER B2 F3 byte 4 CANSPI FILTER B2 F4 byte 5 MikroElektronika 292 mikroPascal PRO for PIC32 Library Example The code is a simple demonstration of CANSPI protocol This node initiates the communication with the 2nd node by sending some data to its address The 2nd node responds by sending back the data incremented by 1 This 1st node then does the same and sends incremented data back to the 2nd node etc Code for the first CANSPI node Copy Code To Clipboard program Can Spi 1st const ID 1st const ID 2nd J2ILTs 3 longint longint var Can Init Flags Can Send Flags Can Rcv Flags Rx Data Len word RxTx Data array 8 of byte Msg Rcvd byte Tx ID Rx ID dword CANSPI module connections var CanSpi CS sbit at LATFO bit CanSpi CS Direction sbit at TRISFO bit CanSpi Rst sbit at LATF1 bit CanSpi Rst Direction sbit at TRISFl bit word can flags received data length in bytes can rx tx data buffer reception flag can rx and tx ID End CANSPI module connections begin CHECON 0x32 ADIPCFG OxFFFF configure AN pins as digital I O PORTB 0 clear PORTB TRISB 0 set PORTB as output Can Init Flags 0 Can Send Flags 0 clear flags Can Rev Flags 0 Can Send Flags CANSPI TX PRIO
285. e Init 590 1 MikroElektronika 262 mikroPascal PRO for PIC32 Cf_Write_Byte Prototype procedure Cf Write Byte data byte Description Writes a byte to Compact Flash sector buffer location currently pointed to by writing pointers These pointers will be autoicremented upon reading When sector buffer is full its contents will be transfered to appropriate flash memory sector data byte to be written Requires The corresponding MCU ports must be appropriately initialized for CF card See Cf Init CF card must be initialized for writing operation See Cf Write Init var data byte data OxAA Cf Write Byte data Cf Read Sector Prototype procedure Cf Read Sector sector number dword var buffer array 512 of byte Description Reads one sector 512 bytes Read data is stored into buffer provided by the buffer parameter Parameters sector number sector to be read buffer data buffer of at least 512 bytes in length Nothing Requires The corresponding MCU ports must be appropriately initialized for CF card See Cf Init read sector 22 var data array 512 of byte Cf Read Sector 22 data Cf Write Sector Prototype procedure Cf Write Sector sector number dword var buffer array 512 of byte Description Writes 512 bytes of data provided by the buffer parameter to one CF sector Parameters sector number sector to be written to buffer data buffe
286. e SPI library is done by the SPI Set Active function both SPI modules have to be previously initialized Library Routines SPIx Init SPIx Init Advanced SPIx Read SPIx Write SPI Set Active 395 MikroElektronika mikoPascal PRO for PIC32 SPIx_Init Prototype procedure SPIx Init Description Configures and initializes the SPI module with default settings Default settings Master mode 8 bit data mode Serial clock set to System clock 64 Slave Select disabled Input data sampled in the middle of interval Clock idle state low Serial output data changes on transition from idle clock state to active clock state Parameters None MCU must have the SPI1 module Initialize the SPI1 module with default settings SPII Triit SPI library routines require you to specify the module you want to use To select the desired SPI module simply change the letter x in the routine prototype for a number from 1 to 3 Number of SPI modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Switching between the SPI modules in the SPI library is done by the SPI Set Active function both SPI modules have to be previously initialized MikroElektronika 396 mikroPascal PRO for PIC32 SPIx Init Advanced Prototype procedure SPIx Init Advanced master mode data mode clock divider slave select data sample clock idle ed
287. e Set Index index byte TFT RS Lo LATD procedure Write Command cmd byte TFT RS Lo LATD procedure Write Data data word TFT RS 1 Lo LATE Hi data Lo LATD Lo data TFT WR 0 TFT WR 1 procedure main TRISE 0 TRISD 0 TFT Set Active Set Index Write Command Write Data TET Tnit 320 2420 521 MikroElektronika mikoPascal PRO for PIC32 TFT_Set_Font Prototype procedure TFT Set Font activeFont const far byte font color word font orientation byte Description Sets font its color and font orientation Parameters activeFont desired font Currently only TFT defaultFont Tahoma14x16 is supported font color sets font color font orientation Sets font orientation FO HORIZONTAL Horizontal orientation FO VERTICAL Vertical orientation TFT module needs to be initialized See the TFT Init routine Pee TFT Set Font TFT defaultFont CL BLACK FO HORIZONTAL MikroElektronika 028 mikroPascal PRO for PIC32 TFT_Write_Char Prototype procedure TFT Write Char ch x y word Description Writes a char on the TFT at coordinates x y c char to be written x char position on x axis y char position on y axis TFT module needs to be initialized See the TFT Init routine Example TFT Write Char A 22 23 TFT Write Text Prototype procedure TFT Write Text var text string x y word Nothin
288. e appropriate hardware and software for using the mikrolCD select mikrolCD Debug Build Type before compiling the project Project Settings Choose ICD Debug type if you want to use mikroICD debug Build Type O Release ICD Debug Debugger Q Software mikroIcD Now compile the project by pressing Ctrl F9 or by pressing Build Icon on Build Toolbar Se SO2 TOOO C L L C CAc Ci Run the mikrolCD by selecting Run gt Start Debugger from the drop down menu or by clicking the Start Debugger Icon IET Starting the Debugger makes more options available Step Into Step Over Run to Cursor etc Line that is to be executed is color highlighted blue by default There is also notification about the program execution and it can be found in the Watch Window yellow status bar Note that some functions take more time to execute execution is indicated with Running message in the Watch Window Status Bar 47 1E Ei Bx Select variable from list Related topics mikrolCD Debugger Example mikroICD Debug Windows mikrolCD Debugger Options MikroElektronika 114 mikroPascal PRO for PIC32 mikrolCD Debugger Options Debugger Options Function Toolbar Description Key Icon Run Pause Debugger Run Pause Debugger F6 Executes the current program line then halts If the executed Step Into program line calls another routine the debugger steps into the routine and halts after
289. e channel x timer prescale use timer x word word Initializes the PWM module with duty ratio O Parameters freq hz PWM frequency in Hz refer to device datasheet for correct values in respect with Fosc enable channel x number of PWM channel to be initialized Refer to MCU s datasheet for available PWM channels timer prescale timer prescaler parameter Valid values 1 8 64 and 256 use timer x timerto be used with the PWM module Valid values 2 Timer2 and 3 Timer3 OxFFFF if timer settings are not valid otherwise returns calculated timer period MCU must have the HW PWM Module Initializes the PWM module at 5KHz channel 1 no clock prescale timer2 var pwm periodl word pwm periodi PWM Init 5000 1 0 2 Notes Number of available PWM channels depends on MCU Refer to MCU datasheet for details PWM Init Advanced Prototype function PWM Init Advanced freq hz Fpb kHz dword enable channel x timer prescale use timer x word word Initializes the PWM module with duty ratio 0 Parameters freq _ hz PWM frequency in Hz Fpb_kHz Peripheral Bus Clock frequency in kHz enable channel x number of PWM channel to be initialized Refer to MCU s datasheet for available PWM channels timer prescale timer prescaler parameter Valid values 1 8 64 and 256 use_timer_x timer to be used with the PWM module Valid values 2 Timer2 and 3 Timer3 OxFFFF if timer se
290. e drop down menu Search Paths Path C Program Files Mikroelektronika mikroPascal PRO For PIC321defsl C Program Files Mikroelektronika mikroPascal PRO for PIC32 uses C Program Files Mikroelektronika mikroPascal PRO for PIC32 Examples Development Systems L 32MX v6 LCD 609 MikroElektronika mikoPascal PRO for PIC32 Following options are available icon Description Add Search Path Remove Search Path ca Purge Invalid Paths Paths for Source Files mpas You can specify either absolute or relative path to the source file If you specify a relative path mikroPascal PRO for PIC32 will look for the file in following locations in this particular order 1 the project folder folder which contains the project file mpp32 2 your custom search paths 3 mikroPascal PRO for PIC32 installation folder gt Uses folder Related topics File Menu File Toolbar Project Manager Project Settings MikroElektronika 610 mikroPascal PRO for PIC32 Edit Project Edit Project gives you option to change MCU you wish to use change its oscillator frequency and build type Also Edit Project enables you to alter specific configuration bits of the selected device As you alter these bits appropriate register values will be updated also This can be viewed in the Configuration Registers pane When you have finished configuring your device you can save bit configuration as a scheme using Save sc
291. e file See also Predefined Project Level Defines Linker Directives mikroPascal PRO for PIC32 uses an internal algorithm to distribute objects within memory If you need to have a variable constant or a routine at the specific predefined address use the linker directives absolute and org When using these directives be sure to use them in proper memory segments i e for functions it is the KSEGO and for variables it is the KSEG1 Linker directives are used with the virtual addresses Directive absolute Directive absolute specifies the starting address in RAM for a variable If the variable is multi byte higher bytes will be stored at the consecutive locations Directive absolute is appended to declaration of a variable Variable x will occupy 1 word 16 bits at address 0xA0000000 var x word absolute 0xA0000000 Variable y will occupy 2 words at addresses 0xA0000000 and 0xA0000002 var y longint absolute 0xA0000000 Be careful when using the absolute directive as you may overlap two variables by accident For example Nariable i will occupy 1 word at address 0xA0000002 var i word absolute 0xA0000002 Variable will occupy 2 words at 0xA0000000 and 0xA0000002 thus changing i changes jj at the same time and vice versa var jj longint absolute 0xA0000000 MikroElektronika 232 mikroPascal PRO for PIC32 Directive org Directive org specifies the starting address of a constant or a routin
292. e following memory type specifiers can be used code data rx reserved for compiler purposes only E code The code memory type may be used for allocating constants in program memory puts txt in program memory const txt ENTER PARAMETER code This memory specifier is used when storing variable to the Data RAM puts data buffer in data ram var data buffer char data rx Description This memory specifier allows variable to be stored in the working registers space reserved for compiler purposes only puts y in Rx space var y char rx sfr This memory specifier allows user to access special function registers It also instructs compiler to maintain same identifier in source and assembly Example var y char sfr puts y in SFR space Note If none of the memory specifiers are used when declaring a variable data specifier will be set as default by the compiler Related topics PIC32 Memory Organization Accessing individual bits SFRs Constants Functions 171 MikroElektronika mikoPascal PRO for PIC32 Read Modify Write Problem The Microchip microcontrollers use a sequence known as Read Modify Write RMW when changing an output state 1 or 0 on a pin This can cause unexpected behavior under certain circumstances When your program changes the state on a specific pin for example RBO in PORTB the microcontroller first READs all 8 bits of the PORTB register whic
293. e in ROM It is appended to the constant or a routine declaration To place a constant array in Flash memory write the following Constant array MONTHS will be placed starting from the address 0x9D000000 const MONTHS i array l1 12 of byte 1 31 28 31 30 31 90 31 91 30 31 30 91 org 0x800 If you want to place simple type constant into Flash memory instead of following declaration const SimpleConstant byte OxAA org 0x9D000000 use an array consisting of single element const SimpleConstant array 1 of byte 0xAA org 0x9D000000 In first case compiler will recognize your attempt but in order to save Flash space and boost performance it will automatically replace all instances of this constant in code with it s literal value In the second case your constant will be placed in Flash in the exact location specified To place a routine on a specific address in Flash memory you should write the following procedure proc par byte org 0x9D000000 begin Procedure will start at address 0x9D000000 end org directive can be used with main routine too For example program Led Blinking begin org 0x9D000000 main procedure starts at 0x9D000000 end Directive orgall Use the oxga11 directive to specify the address above which all routines and constants will be placed Example begin orgall 0x9D000000 All the routines constants in main program will be above the address 0x9D000000 end 233
294. e in a mode in which receiving is possible See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page check the CANSPI1 module for received messages If any was received do something var msg rcvd rx flags data len byte data array 8 of byte msg id longint CANSPISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode CANSPI1 module must be in mode in which receive is possible clear message CANSPIRead msg id data data len rx flags then MikroElektronika 248 mikroPascal PRO for PIC32 CANSPIWrite Prototype function CANSPIWrite id longint var Data array 8 of byte DataLen CANSPI TX MSG FLAGS byte byte Description If at least one empty Transmit Buffer is found the function sends message in the queue for transmission Parameters id CAN message identifier Valid values 11 or 29 bit values depending on message type standard or extended Data data to be sent DataLen data length Valid values 0 8 CANSPI TX MSG FLAGS message flags Valid values CANSPI_ TX MSG FLAGS constants See CANSPI TX MSG FLAGS constants 0 if all Transmit Buffers are busy OxFFFF if atleast one Transmit Buffer is available Requires The CANSPI module must be in mode in which transmission is poss
295. e in any modern Windows application you may customize the layout of mikroPascal PRO for PIC32 to suit your needs best Spell checker underlines identifiers which are unknown to the project In this way it helps the programmer to spot potential problems early much before the project is compiled Spell checker can be disabled by choosing the option in the Preferences dialog F12 49 MikroElektronika mikoPascal PRO for PIC32 Code Editor The Code Editor is advanced text editor fashioned to satisfy needs of professionals General code editing is the same as working with any standard text editor including familiar Copy Paste and Undo actions common for Windows environment Available Code Editor options are Editor Settings Editor Colors Auto Correct Auto Complete and Style Editor Settings Main Editor Settings Features are Auto Save Highlighter Spelling Comment Style Code Folding Code Assistant Parameter Assistant Bookmarks and Go to Line Options Editor Settings Editor Settings Pora ws 1H V Restore Last Opened Project Restore All Opened Files iW Editor Colors 4 If Opened File Is Externally Modified Prompt for action Reload file but do not prompt Ignore externally made changes Save Breakpoints Save Bookmarks Auto Correct Auto Save V Enable Auto Save Timeout Interval 3 minutes Highlighter V Highlight brackets V Highlight begin end pairs Spelling
296. e library Library Routines Ow Reset Ow Read Ow Write 945 MikroElektronika mikoPascal PRO for PIC32 Ow_Reset Prototype function Ow Reset var port word pin word word Issues OneWire reset signal for D818x20 Parameters port OneWire bus port pin OneWire bus pin 0 if the device is present 1 if the device is not present Devices compliant with the Dallas OneWire protocol Issue Reset signal on One Wire Bus connected to pin RF6 Ow Reset amp PORTF 6 ges None OOS Ow_Read Prototype function Ow Read var port word pin word byte Reads one byte of data via the OneWire bus Parameters port OneWire bus port pin OneWire bus pin Returns Data read from an external device over the OneWire bus Devices compliant with the Dallas OneWire protocol Read a byte from the One Wire Bus connected to pin RF6 var read data byte read_ data Ow_Read PORTF Ow_Write Prototype procedure Ow Write var port word pin data byte Writes one byte of data via the OneWire bus Parameters port OneWire bus port pin OneWire bus pin data data to be written Devices compliant with the Dallas OneWire protocol Send a byte to the One Wire Bus connected to pin RF6 Ow Write amp PORTF 6 OxCC MikroElektronika 346 mikroPascal PRO for PIC32 Port Expander Library mikroPascal PRO for PIC32 provides a library for communication with the
297. e mikroPascal PRO for PIC32 UART Library provides comfortable work with the Asynchronous full duplex mode Important UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Switching between the UART modules in the UART library is done by the UART_Set_Active function UART modules have to be previously initialized Library Routines UARTx Init UARTx Init Advanced UARTx Data Ready UARTx Tx Idle UARTx Read UARTx Read Text UARTx Write UARTx Write Text UART Set Active MikroElektronika 092 mikroPascal PRO for PIC32 UARTX Init Prototype procedure UARTx Init baud rate dword Description Configures and initializes the UART module The internal UART module module is set to continue operation in IDLE mode default Tx and Rx pins loopback mode disabled 8 bit data no parity 1 STOP bit transmitter enabled generate interrupt on transmission end interrupt on reception enabled Address Detect mode disabled baud rate requested baud rate Nothing Routine requires the UART module Initialize hardware UART1 module and establish communication at 2400 bps UART1_Init 2400 Refer to the device data she
298. e range of the counter s type More legible way to create an endless loop in Pascal is to use the statement while TRUE do MikroElektronika 226 mikroPascal PRO for PIC32 While Statement Use the while keyword to conditionally iterate a statement The syntax of the while statement is while expression do statement statement is executed repeatedly as long as expression evaluates true The test takes place before the statement is executed Thus if expression evaluates false on the first pass the loop does not execute Here is an example of calculating scalar product of two vectors using the while statement 0 i 0 while i n do begin S i S alil biij i i 1l1 end Probably the easiest way to create an endless loop is to use the statement while TRUE do Repeat Statement The repeat statement executes until the condition becomes true The syntax of the repeat statement is repeat statement until expression statement is executed repeatedly as long as expression evaluates false The expression is evaluated after each iteration so the loop will execute statement at least once Here is an example of calculating scalar product of two vectors using the repeat statement repeat begin end until i n 221 MikroElektronika mikoPascal PRO for PIC32 Jump Statements The jump statement when executed transfers control unconditionally There are four such statements in mikroPas
299. e selected variable register Also you can choose the format of variable register representation between decimal hexadecimal binary float or character All representations except float are unsigned by default For signed representation click the check box next to the Signed label B Edit Value PORTB DER Representation Dec O Hex O Bin O Float O char C Signed OK Cancel An item s value can also be changed by double clicking item s value field and typing the new value directly MikroElektronika 128 mikroPascal PRO for PIC32 RAM Window The RAM Window is available from the drop down menu View Debug Windows RAM The RAM Window displays the map of MCU s RAM with recently changed items colored red The user can edit and change the values in the RAM window mikrolCD Specific RAM window content will be written to the MCU before the next instruction execution Lcd4bit mikroE ikroElektronike EasydsPIC4 Stopwatch Window The Software Simulator Stopwatch Window is available from the drop down menu View Debug Windows Stopwatch The Stopwatch Window displays a Current Count of cycles time since the last Software Simulator action Stopwatch measures the execution time number of cycles from the moment Software Simulator has started and can be reset at any time Delta represents the number of cycles between the lines where Software Simulator action has started and ended
300. eclarations constants variables labels and types for the project You do not define routines in the interface section Instead state the prototypes of routines from implementation section that you want to be visible outside the unit Prototypes must match the declarations exactly Implementation Section Implementation section hides all irrelevant innards from other units allowing encapsulation of code Everything declared below the keyword implementation is private i e has its scope limited to the file When you declare an identifier in the implementation section of a unit you cannot use it outside the unit but you can use it in any block or routine defined within the unit By placing the prototype in the interface section of the unit above the implementation you can make the routine public i e visible outside of unit Prototypes must match the declarations exactly MikroElektronika 192 mikroPascal PRO for PIC32 Variables Variable is an object whose value can be changed during the runtime Every variable is declared under unique name which must be a valid identifier This name is used for accessing the memory location occupied by a variable Variables are declared in the declaration part of the file or routine each variable needs to be declared before being used Global variables those that do not belong to any enclosing block are declared below the uses statement above the keyword begin Specifying a data ty
301. ect Project Manager gt Images File File has to be previously added to Project Project Manager gt Other Files There are four predefined event types you can apply to an Active Comment 1 OnLeftClick Alt 2 OnRightClick 3 OnDoubleClick 4 OnMouseOver 95 MikroElektronika mikoPascal PRO for PIC32 First three event types can have one of the following three actions 1 OpenUrl Opens entered URL in default Web browser 2 OpenFile Opens a file within a default program associated with the file extension defined by Windows 3 None Does nothing The fourth event OnMouseOver has only 2 actions 1 Previewlmage Shows image when cursor is moved over a comment 2 None Does nothing Attributes are tightly bounded with events For example you can not have OnLeftClick Alt gt OpenFile if there is no file attribute set or if there is no file added to project The same behavior applies to image attribute Let s start editing our Active Comment by entering some valid web address in the URL field J Attributes www mikroe com Image File J Events OnLeftClick Alt OnRightClick OnDbiClick OnMouseOver For every Active Comment a XML file will be created containing all valid information regarding the Active Comment attributes events etc and it is automatically added to Project manager after saving it Project Manager icai RS RBS act e P Easy_GSM_GPRS mpp32 Bg Sources amp
302. ect Setting Window affects currently active project only so in case more than one project is open you have to ensure that exactly the desired project is set as active one in the Project Manager Also you can change configuration bits of the selected chip in the Edit Project window Managing Project Group mikroPascal PRO for PIC32 IDE provides convenient option which enables several projects to be open simultaneously If you have several projects being connected in some way you can create a project group The project group may be saved by clicking the Save Project Group Icon fy from the Project Manager window The project group may be reopened by clicking the Open Project Group Icon e All relevant data about the project group is stored in the project group file extension mpdsgroup Add Remove Files from Project The project can contain the following file types mpas source files emc1 binary files pid project level defines files image files ihex EEPROM files hex asmand 1st files see output files These files can not be added or removed from project other files Project Manager 1 1 2535 189 S 15 M j AP at MS s S EZESEITTECETTEH a Sources T6963C 240x128 mpas einstein bmp mpas mikroe bmp mpas 3 Binaries T6963C_240x128 mel E Project level defines 4 Image Files mikroE_240x128 bmp amp 7j EEPROM Files T6963C 240x128 ihex Active Comments Files 4 Output Files T6963C 240x128 hex
303. ed 0 if file does not exist and no new file is created 1 if file already exists or file does not exist but a new file is created CF card and CF library must be initialized for file operations See Cf Fat Init create file with archive attributes if it does not already exist Cf Fat Assign MIKRO007 TXT 0xA0 Notes Long File Names LFN are not supported 265 MikroElektronika mikoPascal PRO for PIC32 Cf_Fat_Reset e procedure Cf Fat Reset var size dword Opens currently assigned file for reading Parameters size buffer to store file size to After file has been open for reading its size is returned through this parameter Requires CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign var size dword Cf Fat Reset size Cf Fat Read Prototype procedure Cf Fat Read var bdata byte Description Reads a byte from currently assigned file opened for pem Upon function execution file pointers will be set to the next character in the file bdata buffer to store read byte to Upon this function execution read byte is returned through this parameter Requires CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign File must be open for reading See Cf Fat Reset var bdata byte Cf Fat Read bdata MikroElektronika 266
304. ee SPI T6963C Config routine Example SPI T6963C write char A 22 23 SPI T6963C ROM MODE AND MikroElektronika 480 mikroPascal PRO for PIC32 SPI T6963C write text Prototype procedure SPI T6963C write text var str array 10 of byte x y mode byte Writes text in the current text panel of Glcd at coordinates x y Parameters str text to be written x text position on x axis y text position on y axis mode mode parameter Valid values SPI T6963C ROM MODE OR SPI T6963C ROM MODE XOR SPI T6963C ROM MODE AND and SPI T6963C ROM MODE TEXT Mode parameter explanation OR Mode In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in negative mode i e white text on black background AND Mode The text and graphic data shown on the display are combined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet Nothing Toshiba Glcd module needs to be initialized See SPI T6963C Config routine E I7 SPI T6963C write text GLCD LIBRARY D 0 0 SPI T6963C ROM
305. eight of the original image image image to be displayed Bitmap array can be located in both code and RAM memory due to the mikroPascal PRO for PIC pointer to const and pointer to RAM equivalency Nothing Requires Glcd needs to be initialized see Glcd Init routine Draws a 10x15 part of the image starting from the upper left corner on the coordinate 10 12 Original image size is 16x32 Gled Partiallmage 10 12 10 15 16 32 image Use the mikroPascal PRO for PIC32 integrated Glcd Bitmap Editor Tools Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd 307 MikroElektronika mikoPascal PRO for PIC32 lC Library The PC full master I C module is available with a number of the PIC32 MCU models The mikroPascal PRO for PIC32 provides a library which supports the master I C mode Important FC library routines require you to specify the module you want to use To select the desired IC module simply change the letter x in the routine prototype for a number from 1 to 3 Number of I C modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Library Routines 2Cx Init 2Cx Init Advanced 2Cx Start 2Cx Restart 2Cx Is Idle 2Cx Read 2Cx Write 2Cx Stop I2Cx Init Prototype procedure I2Cx Init scl longint Description This function configures and initializes the desired IC mod
306. ektronika 404 mikroPascal PRO for PIC32 Library Routines SPI Ethernet Init SPI Ethernet Enable SPI Ethernet Disable SPI Ethernet doPacket SPI Ethernet putByte SPI Ethernet putBytes SPI Ethernet putString SPI Ethernet putConstString SPI Ethernet putConstBytes SPI Ethernet getByte SPI Ethernet getBytes SPI Ethernet UserTCP SPI Ethernet UserUDP SPI Ethernet setUserHandlers SPI Ethernet getlpAddress SPI Ethernet getGwlpAddress SPI Ethernet getDnslpAddress SPI Ethernet getlpMask SPI Ethernet confNetwork SPI Ethernet arpResolve SPI Ethernet sendUDP SPI Ethernet dnsResolve SPI Ethernet initDHCP SPI Ethernet doDHCPLeaseTime SPI Ethernet renewDHCP SPI Ethernet Init Prototype procedure SPI Ethernet Init mac byte ip byte fullDuplex byte Description This is MAC module routine It initializes ENC28J60 controller This function is internaly splited into 2 parts to help linker when coming short of memory ENC28J60 controller settings parameters not mentioned here are set to default receive buffer start address 0x0000 receive buffer end address 0x19AD transmit buffer start address 0x19AF transmit buffer end address 0x1FFF RAM buffer read write pointers in auto increment mode receive filters set to default CRC MAC Unicast MAC Broadcast in OR mode flow control with TX and RX pause frames in full duplex mode
307. em before exit from interrupt MikroElektronika 110 mikroPascal PRO for PIC32 Interrupt Example Here is a simple example of handling the interrupts from Timer1 if no other interrupts are allowed program Timerl interrupt procedure TimerlInt iv IVT TIMER 1 ilevel 7 ics ICS_SRS begin TlIF bit 0 Clear TLIF LATB not PORTB Invert PORTB end begin ADIPCFG OxFFFF Initialize AN pins as digital TRISB 0 initialize PORTB as output LATB OxAAAA Initialize PORTB value TMR1 0 reset timer value to zero PRI 65000 Load period register TIIPO bit 1 set interrupt Ti1IP1 bit 1 priority T1IP2 bit 1 Lf wee 7 TCKPSO bit 1 Set Timer Input Clock TCKPS1 bit 1 Prescale value to 1 256 EnableInterrupts TLIE bit z 1 Enable Timerl Interrupt ON TICON bit 1 Enable Timerl end 141 MikroElektronika mikoPascal PRO for PIC32 Linker Directives mikroPascal PRO for PIC32 uses an internal algorithm to distribute objects within memory If you need to have a variable constant or a routine at the specific predefined address use the linker directives absolute and org When using these directives be sure to use them in proper memory segments i e for functions it is the KSEGO and for variables it is the KSEG1 Linker directives are used with the virtual addresses Directive absolute Directive absolute
308. em to proper case automatically so the user does not have to take care of that Also in order to keep backward compatibility with the first version of this library file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between file name and extension i e MIKROELETXT gt MIKROELE TXT In this case last 3 characters of the string are considered to be file extension file attr file creation and attributes flags Each bit corresponds to the appropriate file attribute s Number of the start sector for the newly created swap file if there was enough free space on the MMC SD card to create file of required size 0 otherwise MikroElektronika mikoPascal PRO for PIC32 Try to create a swap file with archive atribute whose size will be at least 1000 sectors If it succeeds it sends No of start sector over UART var size dword size Mmc Fat Get Swap File 1000 mikroE txt 0x20 if size lt gt 0 then begin VARTI Write 0xAA UART1 Write Lo size UART1 Write Hi size UART1 Write Higher size UART1 Write Highest size UART1 Write 0xAA end Notes Long File Names LFN are not supported Library Example This project consists of several blocks that demonstrate various aspects of usage of the Mmc Fat16 library These are Creation of new file and writing down to it Opening existing file and re writing it writing from start of
309. en into the MCU There is one action button concerning the Code Watch Window Read code_ Reads code from the MCU and loads it up into the Code Window Code reading is resources consuming operation so the user should wait until the reading is over Also you can set an address scope in which hex code will be read CODE Watch Address Scope 000000 A75010 AB822CA 470060 464010 A902CA A74010 AS02CA 2088CO0 DLE PS G DLE A60010 A802D6 A70010 A902D6 07FF96 470060 63010 A962CA DLE STX DL A73010 A862CA 470060 A62010 A942CA A72010 AB842CA 470060 DLE 08 b G DLI A61010 A922CA A71010 A822CA 470060 A60010 ASO2CA A70010 DLE DLE O DI asozca 2088CO A60010 AS02D6 A70010 A902D6 O7FF7C 2088C0 E lt STX gt SPC D A60010 370002 07FF64 370001 07FF86 FA8000 060000 FAO002 DLE lt STX gt 7d y lt 37000F 200800 9FBF40 370019 200c00 OFBF40 370016 200940 lt SI gt 7 lt BS gt lt SPC gt 9FBF40 370013 200D40 9FBF40 370010 200800 9FBF40 370000 DC3 7 CR 97B84E E10061 32FFEE 97B84E E10062 32FFEE 97B84E E10063 N a ij2N b 32FFEE 97B84E E10064 32FFEE 37FFFO 97B83E 500061 570068 iy2N d iy28j75 408010 9FBF40 781F80 O7FF9B B1002F 2088CO0 AI10010 EF2000 lt DLE gt US 980700 97B8AE 470060 408010 00410 32000C 97B8AE 47006
310. ence OK is received and then send it back UART1 Init 9600 delim OK while TRUE do begin if UART1 Data Ready 1 then begin UART1 Read Text txt delim 10 UART1 Write Text txt end end MikroElektronika 558 mikroPascal PRO for PIC32 UART Set Active Prototype procedure UART Set Active read ptr TUART Rd Ptr write ptr TUART Wr Ptr ready ptr TUART Rdy Ptr tx idle ptr TUART TX Idle Ptr Description Sets active UART module which will be used by UARTx Data Ready UARTx Read and UARTx Write routines Parameters Parameters read ptr UARTx Read handler write ptr UARTx Write handler ready ptr UARTx Data Ready handler tx idle ptr UARTx Tx Idle handler Requires Routine is available only for MCUs with multiple UART modules Used UART module must be initialized before using this routine See UARTx Init and UARTx Init Advanced routines UART1 Init 9600 initialize UART1 module UART2 Init 9600 initialize UART2 module RS485Master Init initialize MCU as Master UART Set Active 8UART1 Read UART1 Write QUARTI Data Ready QUARTI Tx Idle set UART1 active RS485Master Send dat 1 160 send message through UARTI UART Set Active UART2 Read UART2 Write UART2 Data Ready UART2 Tx Idle set UART2 active RS485Master Send dat 1 160 send through UART2 559 MikroElektronika mikoPascal PRO for PIC32 Library Example This e
311. er in s1 does not match a character in s2 a value of 0 is returned If all characters in s1 are found in s2 the length of s1 is returned not including the terminating null character txt WMnikroElektronika txt sub mikr res strspn txt txt sub routne returns 4 strncmp Prototype function strncmp var sl s2 string len word integer Description The function lexicographically compares the first len characters of the strings s1 and s2 and returns a value indicating their relationship Value Meaning 0 sl less than s2 sl equal to s2 gt 0 sl greater than s2 The value returned by the function is determined by the difference between the values of the first pair of words that differ in the strings being compared within first 1 en words txt mikroElektronika txt sub mikr res strncmp txt_sub txt 3 compares the first 3 characters from the string txt with the sting txt sub and returns a difference MikroElektronika 590 mikroPascal PRO for PIC32 strstr Prototype function strstr var sl s2 string word Description The function locates the first occurrence of the string s2 in the string s1 excluding the terminating null character The function returns a number indicating the position of the first occurrence of s2 in s1 if no string was found the function returns OxFFFF If s2 is a null string the function returns 0
312. er on Windows Vista Windows 7 617 am getting Access is denied error in Vista how to solve this problem 617 What are differences between mikroC PRO mikroPascal PRO and mikroBasic PRO compilers Why do they have different prices 617 Why do your PIC compilers don t support 12F508 and some similar chips 617 What are limitations of demo versions of mikroElektronika s compilers 617 Why do still get demo limit error when purchased and installed license key 617 have bought license for the older version do have to pay license for the new version of the com piler 618 Do your compilers work on Windows Vista Windows 7 618 What does this function procedure routine do 618 try to compile one of the provided examples and nothing happens what is the problem 618 Can get your library sources need to provide all sources with my project 618 Can use code developed in your compilers in commercial purposes Are there some limitations 618 Why does an example provided with your compilers doesn t work 618 Your example works if use the same MCU you did but how to make it work for another MCU 618 need this project finished can you help me 619 Do you have some discount on your compilers development systems for students professors 619 have a question about your compilers which is not listed here Where can find an answer 619 MikroElektronika 26 mikroPascal PRO for PIC32 21 MikroElektr
313. erts input dword to a string The output string is right justified and the remaining positions on the left if any are filled with zeros Parameters input unsigned long number to be converted output destination string var t dword txt array 10 of char Jd deans t 12345678 LongWordToStrWithZeros t txt txt is 0012345678 911 MikroElektronika mikoPascal PRO for PIC32 LongIntToStrWithZeros Prototype m LongIntToStrWithZeros input longint var output array 11 of char Converts input longint to a string The output string is right justified and the remaining positions on the left if any are filled with zeros Parameters input signed long number to be converted output destination string var t longint txt array 11 of char rz NO t 12345678 LongIntToStrWithZeros t txt txt is 0012345678 ByteToHex Prototype procedure ByteToHex input byte var output array 2 of char ada Converts input number to a string containing the number s hexadecimal representation The output naa is right justified and remaining positions on the left if any are filled with zeros Parameters input byte to be converted output destination string Returns Nothing var t byte txt array 2 of char t r 2 II txe ag OZ MikroElektronika 918 mikroPascal PRO for PIC32 ShortToHex Prototype procedure ShortToHex input short var output
314. erwise Requires Ethernet module has to be initialized See SPI Ethernet Init This function is internally called by the library and should not be called by the user s code The function source code is provided with appropriate example projects The code should be adjusted by the user to achieve desired reply SPI Ethernet setUserHandlers Prototype procedure SPI Ethernet setUserHandl ERE TSPI Ethernet UserTGOP UDPHandler TSPI Ethernet UserUDP Description Sets pointers to User TCP and UDP handler function implementations which are automatically called by SPI Ethernet library Parameters TCPHandler TCP request handler UDPHandler UDP lt lt II CENE handler Returns Nothing eee SPI Ethernet UserTCP and SPI Ethernet UserUDP have to be previously defined SPI Ethernet setUs rHandlers 80SPI Ethernet UserTCP QSPI Ethernet _ UserUDP Since all libraries are built for SSA SSA restrictions regarding function pointers dictate that modules that use SPI Ethernet setUserHandlers must also be built for SSA 43 MikroElektronika mikoPascal PRO for PIC32 SPI Ethernet getlpAddress Prototype Prototype function SPI Ethernet getIpAddress This routine should be used when DHCP server is present on the network to fetch assigned IP address Returns Pointer to the global variable holding IP address Ethernet module has to be initialized See SPI Ethernet Init va ipAddr array 4
315. es activeFont font to be set Needs to be formatted as an array of char aFontWidth width of the font characters in dots aFontHeight height of the font characters in dots aFontOffs number that represents difference between the mikroPascal PRO for PIC32 character set and regular ASCII set eg if A is 65 in ASCII character and A is 45 in the mikroPascal PRO for PIC32 character set aFontOffs is 20 Demo fonts supplied with the library have an offset of 32 which means that they start with space The user can use fonts given in the file Lib GLCDFonts file located in the Uses folder or create his own fonts List of supported fonts Font Glcd System3x5 Font Gled System5x7 Font Gled 5x7 Font Glcd Character8x7 For the sake of the backward compatibility these fonts are supported also System3x5 equivalent to Font Glcd System3x5 FontSystem5x7 v2 equivalent to Font Gl1cd System5x7 font5x7 equivalent to Font Gl1cd 5x7 Character8x7 equivalent to Font Glcd Character8x7 Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Use the custom 5x7 font myfont which starts with space 32 dus say MikroElektronika 456 mikroPascal PRO for PIC32 SPI Glcd Write Char Prototype procedure SPI Glcd Write Char chrl x pos page num color byte Description Prints character on Glcd Parameters chr1 character to be written x pos character
316. escription This is DNS module routine It sends an DNS request for given host name and waits for DNS reply If the requested host name was resolved it s IP address is stored in library global variable and a pointer containing this address is returned by the routine UDP port 53 is used as DNS port Parameters host host name to be resolved tmax time in seconds to wait for an reply pointer to the location holding the IP address the requested host name was resolved 0 otherwise Ethernet module has to be initialized See SPI Ethernet 24600 Init var remoteHostIpAddr array 4 of byte user host IP address buffer SNTP server Zurich Switzerland Integrated Systems Lab Swiss Fed Inst of Technology 129 132 2 21 swisstime ethz ch Service Area Switzerland and Europe memcpy remoteHostIpAddr SPI Ethernet 245600 dnsResolve swisstime ethz pght By Ayy The Ethernet services are not stopped while this routine waits for DNS reply The incoming packets will be processed normaly during this time User should always copy the IP address from the RAM location returned by this routine into it s own resolved host IP address buffer These locations should not be altered by the user in any case M3 MikroElektronika mikoPascal PRO for PIC32 SPI Ethernet 24j600 initDHCP Prototype function SPI Ethernet 247600 initDHCP tmax byte byte Description This is DHCP module routine I
317. est i 0 copy httpMethod to ram for use in memcmp routine for i 0 to 4 do tmp i httpMethod i if memcmp getRequest tmp 5 lt gt 0 then only GET method is supported here begin result 0 exit end Inc httpCounter one more request done if getRequest 5 s then if request path name starts with s store dynamic data in transmit buffer begin the text string replied by this request can be interpreted as javascript Statements by browsers MikroElektronika 422 mikroPascal PRO for PIC32 result result text MIME type SPI Ethernet putConstString httpHeader result SPI Ethernet putConstString 8httpMimeTypeScript add AN2 value to reply WordToStr ADC1 Get Sample 0 dyna tmp var ANO result result tmp result Fa E result SPI Ethernet putString Qtmp result SPI Ethernet putString dyna result SPI Ethernet putString 8tmp add AN3 value to reply WordToStr ADCl Get Sample 1 dyna tmp var AN1 result result result result tmp c 4 result result add PORTB value SPI_Ethernet_putString tmp SPI Ethernet putString dyna SPI Ethernet putString tmp buttons to reply tmp var PORTB result result SPI Ethernet putString tmp WordToStr PORTB dyna result result SPI Ethernet putString dyna tmp i u res
318. esult of the application They are automatically removed Stack allocation Temporary registers Stacks are being used more rationally allowing VERY complex expressions to be evaluated with a minimum stack consumption Local vars optimization No local variables are being used if their result does not affect some of the global or volatile variables Better code generation and local optimization Code generation is more consistent and more attention is payed to implement specific solutions for the code building bricks that further reduce output code size Related topics SSA Optimization PIC32 specifics mikroPascal PRO for PIC32 specifics Memory type specifiers 161 MikroElektronika mikoPascal PRO for PIC32 Single Static Assignment Optimization Introduction In compiler design static single assignment form often abbreviated as SSA form or SSA is an intermediate representation IR in which every variable is assigned exactly once An SSA based compiler modifies the program representation so that every time a variable is assigned in the original program a new version of the variable is created A new version of the variable is distinguished renamed by subscripting the variable name with its version number or an index so that every definition of each variable in a program becomes unique At a joining point of the control flow graph where two or more different definitions of a variable meet a hypothetical function c
319. et Layout Icon To remove the layout from the drop down list select the desired layout from the list and click the Delete Layout Icon lie Default Layout Code Layout Debug Layout NENNEN Auto Hide Auto Hide enables you to see more of your code at one time by minimizing tool windows along the edges of the IDE when not in use Click the window you want to keep visible to give it focus Click the Pushpin Icon 2X on the title bar of the window MikroElektronika 82 mikroPascal PRO for PIC32 DER DOR EZ Project Manager a EE EESTI P RE s ENTER B e Sources 2 Lcd mpas Ce Binaries 73 Project level defines 7j Image Files 7 EEPROM Files Active Comments Files amp 7j Output Files 25 Lcd hex Lcd asm 173 Other Files e amp Lcd mpr mM UR PNE ETT S saBeuey paload fii aeure w palo PP TETEE ai When an auto hidden window loses focus it automatically slides back to its tab on the edge of the IDE While a window is auto hidden its name and icon are visible on a tab at the edge of the IDE To display an auto hidden window move your pointer over the tab The window slides back into view and is ready for use Options Options menu consists of three tabs Code Editor Tools and Output settings Code editor The Code Editor is advanced text editor fashioned to satisfy needs of professionals Tools The mikroPascal PRO for PIC
320. et for baud rates allowed for specific Fosc The compiler will choose for which speed the calculation is to be performed high or low This does not mean that it is the best choice for desired baud rate If the baud rate error generated in this way is too big then UARTx_Init_Advanced routine which allows speed select be used UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Switching between the UART modules in the UART library is done by the UART_Set_Active function UART modules have to be previously initialized Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 553 MikroElektronika mikoPascal PRO for PIC32 UARTx Init Advanced Prototype procedure UARTx Init Advanced baud rate freq Khz dword high low parity stop bits byte Configures and initializes the UART module with user defined settings Parameters baud rate requested baud rate freq Khz Peripheral Bus Clock frequency in kHz high low speed High low speed selection parameter Valid values parity Parity and data selection parameter Valid values stop bits stop bit selection parameter Valid values Predefined library const One stop bit UART ONE STOPBIT Two stop bit UART TWO STOPBITS Routine requires the UART module
321. etry functions are implemented in integer format in order to save memory Library Routines sinE3 cosE3 sinE3 Prototype function sinE3 angle deg word integer Description The function calculates sine multiplied by 1000 and rounded to the nearest integer result round sin angle deg 1000 angle deg input angle in degrees Retums The function returns the sine of input parameter multiplied by 1000 var res integer E3 45 result is 707 PED Return value range 1000 1000 cosE3 Prototype function cosE3 angle deg word integer Description The function calculates cosine multiplied by 1000 and rounded to the nearest integer result round cos angle deg 1000 angle deg input angle in degrees Retums The function returns the cosine of input parameter multiplied by 1000 var res integer cosE3 196 result is 193 me Return value range 1000 1000 MikroElektronika 600 mikroPascal PRO for PIC32 CHAPTER 10 Tutorials Managing Project Projects The mikroPascal PRO for PIC32 organizes applications into projects consisting of a single project file extension mpp32 and one or more source files extension mpas mikroPascal PRO for PIC32 IDE allows you to manage multiple projects see Project Manager Source files can be compiled only if they are part of a project The project file contains the following information project name an
322. f the key is pressed and O if it is released 1 if reading of a key from the keyboard was successful 0 if no key was pressed PS 2 keyboard needs to be initialized See Ps2 Config routine var value special pressed word Press Enter to continue repeat if Ps2 Key Read value special pressed then is rega 13 and special 1 then break until 1 399 MikroElektronika mikoPascal PRO for PIC32 Special Function Keys 7 F8 F9 F10 F11 F12 Enter Page Up Page Down Backspace Insert Delete Windows Ctrl Shift Alt Print Screen Pause Caps Lock Home Scroll Lock Num Lock Left Arrow Right Arrow Up Arrow Down Arrow Escape Tab Value returned 10 11 12 13 14 15 16 17 19 1 28 1 32 33 34 C C C ooo 2 3 C ee o 2 He LIEN jo je jo soo st 2 ss ja jo MikroElektronika mikroPascal PRO for PIC32 Library Example This simple example reads values of the pressed keys on the PS 2 keyboard and sends them via UART Copy Code To Clipboard program PS2 Example var keydata special down byte var PS2 Data sbit at RDO bit PS2 Clock sbit at RD1 bit PS2 Data Direction sbit at TRISDO bit PS2 Clock Direction sbit at TRISD1 bit begin CHECON 0x32 ADIPCFG OxFFFF Configure AN pins as digital I O UART1 Init 56000 Initialize UART module at 19200 bps Ps2 Config Init PS 2 Keyboard Delay
323. file Opening existing file and appending data to it writing from end of file Opening a file and reading data from it sending it to UART terminal Creating and modifying several files at once Reading file contents Deleting file s Creating the swap file see Help for details Copy Code To Clipboard program MMC FAT Test MMC module connections var MMC chip select sbit at LATG9 bit for writing to output pin always use latch var MMC chip select direction sbit at TRISG9 bit eof MMC module connections const LINE LEN 43 var err txt string 20 file contents string LINE LEN filename string 14 File names character byte loop loop2 byte size longint buffer array 512 of byte MikroElektronika 340 mikroPascal PRO for PIC32 UART write text and new line carriage return line feed procedure UART Write Line var uart text string begin UART1 Write Text uart text UART1 Write 13 UART1 Write 10 end Jg Creates new file and writes some data to it procedure M Create New File begin filename 7 A Set filename for single file tests Mmc Fat Set File Date 2011 1 12 11 9 0 Set file date amp time info Mmc Fat Assign filename OxA0 Will not find file and then create file Mmc Fat Rewrite To clear file and start with new data for
324. for PIC32 Introduction to mikroPascal PRO for PIC32 The PIC32 is a 32 bit family of general purpose microcontrollers This is the Microchip s first inherent 32 bit data microcontroller family It builds upon the MIPS M4K 32 bit core offering high performance hardware multiply divide unit programmable user and kernel memory partition through an unified 4GB virtual memory space with powerful peripherals to address a wide range of applications Having a wide range of application being prized for its efficiency PIC32 MCUS are a natural choice for developing embedded systems mikroPascal PRO for PIC32 provides a successful match featuring highly advanced IDE ANSI compliant compiler broad set of hardware libraries comprehensive documentation and plenty of ready to run examples Features mikroPascal PRO for PIC32 allows you to quickly develop and deploy complex applications Write your source code using the built in Code Editor Code and Parameter Assistants Code Folding Syntax Highlighting Auto Correct Code Templates and more Use included mikroPascal PRO for PIC32 libraries to dramatically speed up the development data acquisition memory displays conversions communication etc Monitor your program structure variables and functions in the Code Explorer Generate commented human readable assembly and standard HEX compatible with all programmers Use the integrated mikroICD In Circuit Debugger Real Time debuggin
325. for PIC32 where iv reserved word that inform the compiler that it is an interrupt service routine IVT_ADC appropriate Interrupt Vector ilevel 7 Interrupt priority level 7 ics Interrupt Context Saving Interrupt Context Saving can be performed in several ways 1 ICS_SOFT Context saving is carried out by the software 2 ICS_SRS Shadow Register set is use for context saving 3 ICS_OFF No context saving 4 ICS AUTO Compiler chooses whether the ICS SOFT or ICS SRS will be used User can explicitly declare starting interrupt routine address using org directive procedure interrupt org 0x9D000000 iv IVT ADC ilevel 7 ics ICS SOFT begin Interrupt service routine code end Function Calls from Interrupt Calling functions from within the interrupt routine is possible The compiler takes care about the registers being used both in interrupt and in main thread and performs smart context switching between two of them saving only the registers that have been used in both threads It is not recommended to use a function call from interrupt In case of doing that take care of stack depth Use the DisableContextSaving to instruct the compiler not to automatically perform context switching This means that no register will be saved restored by the compiler on entrance exit from interrupt service routine This enables the user to manually write code for saving registers upon entrance and to restore th
326. ft SPI Read 387 Soft SPI Write 387 Library Example 387 Software UART Library 389 Library Routines 389 Soft UART Init 389 Soft UART Read 390 Soft UART Write 390 Soft UART Break 391 Library Example 392 Sound Library 393 Library Routines 393 Sound Init 393 MikroElektronika 16 mikroPascal PRO for PIC32 Sound Play 393 Library Example 394 HW Connection 396 SPI Library 397 Library Routines 397 SPIx Init 398 SPIx Init Advanced 399 SPIx Read 401 SPIx Write 401 SPI Set Active 402 Library Example 402 HW Connection 404 SPI Ethernet Library 405 Library Dependency Tree 405 External dependencies of SPI Ethernet Library 406 Library Routines 407 SPI Ethernet Init 407 SPI Ethernet Enable 409 SPI Ethernet Disable 410 SPI Ethernet doPacket 411 SPI Ethernet putByte 411 SPI Ethernet putBytes 412 SPI Ethernet putConstBytes 412 SPI Ethernet putString 413 SPI Ethernet putConstString 413 SPI Ethernet getByte 413 SPI Ethernet getBytes 414 SPI Ethernet UserTCP 414 SPI Ethernet UserUDP 415 SPI Ethernet setUserHandlers 415 SPI Ethernet getlpAddress 416 Ethernet getGwlpAddress 416 SPI Ethernet getDnslpAddress 416 SPI Ethernet getlpMask 417 SPI Ethernet confNetwork 417 SPI Ethernet arpResolve 418 SPI Ethernet sendUDP 418 SPI Ethernet dnsResolve 419 SPI Ethernet initDHCP 420 SPI Ethernet doDHCPLeaseTime 420 SPI Ethernet renewDHCP 421 Library Example 422 HW Connection 429 SPI Ethernet ENC24J600 Library 430 Library Dependency Tree 430 Extern
327. function of a given type but rather a new name for a given type In other words the type declaration is identical to a normal declaration but instead of objects it declares types It is a common practice to name custom type identifiers with starting capital letter this is not required by the mikroPascal PRO for PIC32 For example Let s declare a synonym for byte type Distance byte Now synonym Distance can be used as type identifier var i Distance declare variable i of byte 213 MikroElektronika mikoPascal PRO for PIC32 Type Qualifiers The type qualifiers const and volatile are optional in declarations and do not actually affect the type of declared object Qualifier const The qualifier const implies that a declared object will not change its value during runtime In declarations with the const qualifier all objects need to be initialized The mikroPascal PRO for PIC32 treats objects declared with the const qualifier the same as literals or preprocessor constants If the user tries to change an object declared with the const qualifier compiler will report an error For example const PI byte 3 14159 Qualifier volatile The qualifier volatile implies that a variable may change its value during runtime independently from the program Use the volatile modifier to indicate that a variable can be changed by a background routine an interrupt routine or I O port Declaring an object to
328. g Description Writes text on the TFT at coordinates x y Parameters text text to be written x text position on x axis y text position on y axis TFT module needs to be initialized See the TFT Init routine TFT Write Text TFT LIBRARY DF 929 MikroElektronika mikoPascal PRO for PIC32 TFT_Fill_Screen Prototype procedure TFT Fill Screen color word Description Fills screen memory block with given color Parameters color color to be filled TFT module needs to be initialized See the TFT_Init routine Example TFT_Fill_Screen CL muc CS MikroElektronika 530 mikroPascal PRO for PIC32 TFT Dot Prototype procedure TFT Dot x y integer color word Description Draws a dot on the TFT at coordinates x y Parameters x dot position on x axis y dot position on y axis color color parameter Valid values TFT module needs to be initialized See the TFT Init routine Example TFT Dot 50 50 CL BLACK 531 MikroElektronika mikoPascal PRO for PIC32 TFT_Set_Pen Prototype procedure TFT Set Pen pen color word pen width byte Nothing Description Sets color and thickness parameter for drawing line circle and rectangle elements Parameters pen color Sets color pen width sets thickness TFT module needs to be initialized See the TFT Init routine Example TFT Set Pen CL BLACK 10
329. g panel As you type the actual parameter the next expected parameter will become bold channel byte DC Rea Bookmarks Bookmarks make navigation through a large code easier To set a bookmark use Ctrl Shifttnumber The same princliple applies to the removal of the bookmarks To jump to a bookmark use Ctrl number Go to Line The Go to Line option makes navigation through a large code easier Use the shortcut Ctrl G to activate this option MikroElektronika 52 mikroPascal PRO for PIC32 Column Select Mode This mode changes the operation of the editor for selecting text When column select mode is used highlighted text is based on the character column position of the first character selected to the column of the last character of text selected Text selected in this mode does not automatically include all text between the start and end position but includes all text in the columns between the first and last character selected Column mode editing is sometimes referred to as block mode editing as the act of selecting text forms a rectangle To enter this mode press Alt Left mouse button drag the mouse towards the desired direction thus selecting the text Editor Colors Options Editor Colors Schemes Editor Settings Current Scheme Office 2003 Blue v Delete Scheme Setup Editor Colors e Element Assembler Auto Correct Binary Character Comment z Float Hexadecimal Identifier Ille
330. g tool to monitor program execution on the hardware level Inspect program flow and debug executable logic with the integrated Software Simulator Use Single Static Assignment optimization to shrink your code to even smaller size Get detailed reports and graphs RAM and ROM map code statistics assembly listing calling tree and more Active Comments enable you to make your comments alive and interactive mikroPascal PRO for PIC32 provides plenty of examples to expand develop and use as building bricks in your projects Copy them entirely if you deem fit that s why we included them with the compiler Where to Start In case that you re a beginner in programming the PIC32 microcontrollers read carefully the PIC32 Specifics chapter It might give you some useful pointers on the PIC32 constraints code portability and good programming practices If you are experienced in Pascal programming you will probably want to consult mikroPascal PRO for PIC32 Specifics first For language issues you can always refer to the comprehensive Language Reference A complete list of included libraries is available at mikroPascal PRO for PIC32 Libraries If you are not very experienced in Pascal programming don t panic mikroPascal PRO for PIC32 provides plenty of examples making it easy for you to go quickly through it We suggest that you first consult Projects and Source Files first and then start browsing the examples that you re the mo
331. gal Char Number Octal Preprocessor Reserved Word Space String Symbol Web link DEFINE PWM SEQUENCE ON Auto Complete Text Attributes E Bold E Underline Italic T Strikeout Foreground Background Black v mmm Black vj Active Line Color LLL custom V Show Active Line Gutter Colors Gradient From Gradient To CSS Sky Blue white Font R Blue Tools Output mikoPascal PRO for PIC32 Editor Colors option allows user to set change and save text and color settings organized in schemes Schemes represent custom graphical appearance that can be applied to GUI Graphical User Interface to satisfy tastes of different users Auto Correct Auto Correct option facilitates the user in such a fashion that it automatically corrects common typing or spelling errors as it types Options Auto Correct Original Replacement Editor Settings V Enable Auto Correct AL AA Editor Colors Auto Correct Auto Complete ue LAM Style Advanced JS Tools V Correct Case to Match Declaration v Show Notification J Output This option is already set up to automatically correct some words For example if you type whie1 it will be corrected to while when you press the spacebar while Autocorrect from whiel to while MikroElektronika 54 mikroPascal PRO for PIC32 The user can easi
332. ge word Configures and initializes the SPI module with user defined settings Parameters Parameters master mode data mode clock divider slave select data sample clock idle and determine the working mode for SPI The master mode parameter determines the working mode for SPI module he parameter data mode the data length mode which can be 8 bits per transmitions cycle 16 bits br 32 bits he parameter clock divider determines the value of the SPI clock speed Used only in the Maste Mode Clock Divider Value Valid values from 2 to 1024 he parameter slave select determines whether the Slave Select SS pin is used in communication alid in the Slave Mode only Slave Select Enable Disable SS used for the Slave mode SPI SS ENABLE SS not used for the Slave mode SPI SS DISABLE he parameter data sample determines the sample moment phase of input data Data Sampling Moment Lo sampled in the middle of data output SPI DATA SAMPL IDDLE Data sampled at end of data output time SPI DATA SAMPLE END 397 MikroElektronika mikoPascal PRO for PIC32 Parameters The parameter clock idle determines the behaviour of the SPI clock CLK line in IDLE phase IDLE state is Lo ACTIVE state is Hi E state is Hi ACTIVE state is Lo The parameter edge determines on which clock edge data is considered to be valid Clock Edge Data is valid on ACTIVE to IDLE transition SPI ACTIVE 2
333. gin SPI T6963C graphics 1 SPI T6963C text 1 Delay ms 300 end i If RB12 is pressed SG change cursor else if RB12 bit lt gt 0 begin Inc curs if curs 3 curs 0 case curs of 0 no cursor SPI T6963C cursor 0 then then 1 begin blinking cursor SPI T6963C cursor 1 SPI T6963C cursor blink 1 end 2 begin non blinking cursor SPI T6963C cursor 1 SPI T6963C cursor blink 0 end end Delay ms 300 end i If RB13 is pressed perform the Partial image m else SIFDEF PARTIAL IMAGE DEMO if RB13 bit 1 then begin SPI T6963C setGrPanel PI T6963C setTxtPanel PI T6963C txtFill 0 PI T6963C setGrPanel PI T6963C setTxtPanel PI T6963C graphics 1 PI T6963C text 1 PI T6963C displayGrPanel 1 PI T6963C write text txt2 5 15 demonstration SPI T6963C ROM MODE XOR DNANNNANNNMN elay 1sec SPI T6963C grFill 0 SPI T6963C PartialImage 0 Delay ms 1500 0 64 64 240 128 mikroE 240x128 bmp MikroElektronika 496 mikroPascal PRO for PIC32 PI T6963C PartialImage 0 SPI x D 1298 128 Delay ms 1500 240 SPI T6963C PartialImage 0 Delay ms 1500 0 240 128 240 SPI T6963C txtFill 0 SPI T6963C write text txt SPI T6963C write text txtl end SENDIF Move cursor Inc cposx if cposx begin Cposx 0 Inc cposy if cposy cposy end
334. gned file Parameters year buffer to store year attribute to Upon function execution year attribute is returned through this parameter month buffer to store month attribute to Upon function execution month attribute is returned through this parameter da y buffer to store day attribute to Upon function execution day attribute is returned through this parameter hours buffer to store hours attribute to Upon function execution hours attribute is returned through this parameter nins buffer to store minutes attribute to Upon function execution minutes attribute is returned through this parameter Nothing Requires CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign var year word month day hours mins byte Cf Fat Get File Date year month day hours mins Cf Fat Get File Date Modified Prototype procedure Cf Fat Get File Date Modified var year word var month byte var day byte var hours byte var mins byte Description Retrieves the last modification date time of the currently assigned file Parameters year buffer to store year of modification attribute to Upon function execution year of modification attribute is returned through this parameter month buffer to store month of modification attribute to Upon function execution month of modification attribute is returned through this parameter
335. h represents the states of all 8 pins in PORTB RB7 RBO The microcontroller then stores this data in the MCU The bit associated with RB that you ve commanded to MODIFY is changed and then the microcontroller WRITES all 8 bits RB7 RBO back to the PORTB register During the first reading of the PORT register you will be reading the actual state of the physical pin The problem arises when an output pin is loaded in such a way that its logic state is affected by the load Instances of such loads are LEDs without current limiting resistors or loads with high capacitance or inductance For example if a capacitor is attached between pin and ground it will take a short while to charge when the pin is set to 1 On the other hand if the capacitor is discharged it acts like a short circuit forcing the pin to 0 state and therefore a read of the PORT register will return 0 even though we wrote a 1 to it Lets analyze the following example PORTB BO 1 PORTB B1 1 Assume that the PORTB is initially set to zero and that all pins are set to output Let s say we connect a discharged capacitor to RBO pin The first line PORTB BO 1 will be decoded like in this way READ PORTB is read STORE Data is stored inside a temporary internal register in the MCU Store read value gt 0000000 s 1 Read from pins boou c Discharged REGISTER T capacitor ETEC pep pe Discharged capacitor 00000000
336. han once Array Declaration Array types are denoted by constructions in the following form array index start index end of type Each of the elements of an array is numbered from index start through index end The specifier index start can be omitted along with dots in which case it defaults to zero Every element of an array is of type and can be accessed by specifying array name followed by element s index within brackets Here are a few examples of array declaration var weekdays array 1 7 of byte samples array 50 of word begin Now we can access elements of array variables for example samples 0 1 if samples 37 0 then Constant Arrays Constant array is initialized by assigning it a comma delimited sequence of values within parentheses For example Declare a constant array which holds number of days in each month const MONTHS array 1 12 of byte 31 28 31 30 31 30 31 31 30 31 30 31 The number of assigned values must not exceed the specified length The opposite is possible when the trailing excess elements are assigned zeroes For more information on arrays of char refer to Strings Multi dimensional Arrays Multidimensional arrays are constructed by declaring arrays of array type These arrays are stored in memory in such way that the right most subscript changes fastest i e arrays are stored in rows Here is a sample 2 dimensional array m array 5 of array 10 of byte 2 d
337. he OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in the negative mode i e white text on black background AND Mode The text and graphic data shown on display are combined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C write text GLCD LIBRARY DE 0 0 T6963C ROM MODE XOR T6963C line Prototype procedure T6963C line x0 yO xl yl integer pcolor byte Draws a line from x0 yO to x1 y1 Parameters x0 x coordinate of the line start y0 y coordinate of the line end x1 X coordinate of the line start y1 y coordinate of the line end pcolor color parameter Valid values T963C BLACK and T6963C WHITE mms Re DEUIIEESEURL Example 16963C_line 0 239 127 T6963C WHITE LT LL co US MikroElektronika 506 mikroPascal PRO for PIC32 T6963C rectangle Prototype procedure T6963C rectangle x0 yO xl yl integer pcolor byte Draws a rectangle on Glcd
338. he bottom of this page PullUps data for choosing pull up down resistors configuration PortA pull up down resistors configuration is passed in Pul 1Ups s higher byte PortB pull up down resistors configuration is passed in PullUps s lower byte Each bit corresponds to the appropriate pin of the PortA PortB register Set bit enables pull up for corresponding pin Port Expander must be initialized See Expander Init Set Port Expander s PORTB pull up resistors Expander Set PullUpsPortB 0 OxFF 3559 MikroElektronika mikoPascal PRO for PIC32 Library Example The example demonstrates how to communicate with Port Expander MCP23S17 Note that Port Expander pins A2 A1 AO are connected to GND so Port Expander Hardware Address is 0 Copy Code To Clipboard program PortExpander Port Expander module connections var SPExpanderRST sbit at LATFO bit SPExpanderCS sbit at LATF1 bit SPExpanderRST Direction sbit at TRISFO bit SPExpanderCS Direction sbit at TRISF1 bit End Port Expander module connections var counter word begin counter 0 CHECON 0x32 ADIPCFG OXFFFF Configure AN pins as digital TRISB 0x00 LATB OxFF If Port Expander Library uses SPI1 module SPI2 Init Advanced SPI MASTER SPI 8 BIT 4 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE LOW SPI ACTIVE 2 IDLE Expander Init 0 Initialize Port Expander Expander Set DirectionPortA 0 0x00 Set E
339. he compiler not to automatically perform context switching moes Ne OOS MikroElektronika 154 mikroPascal PRO for PIC32 SetFuncCall Prototype procedure SetFuncCall FuncName string Description If the linker encounters an indirect function call by a pointer to function it assumes that any routine whose address was taken anywhere in the program can be called at that point if it s prototype matches the pointer declaration Use the SetFuncCall directive within routine body to instruct the linker which routines can be called indirectly from that routine setruncCasll called funclr ex1 Routines specified in the SetFunCCall argument list will be linked if the routine containing SetFunCCall directive is called in the code no matter whether any of them was explicitly called or not Thus placing Set FuncCal1l directive in main will make compiler link specified routines always FuncName function name procedure f irst p q byte begin SetFuncCall second let linker know that we will call the routine second end pes d The Set FuncCal1 directive can help the linker to optimize function frame allocation in the compiled stack SetOrg Prototype procedure SetOrg RoutineName string address longint Use the SetOrg routine to specify the starting address of a routine in ROM Parameters RoutineName routine name address starting address ums Noting S Example SetOrg UART
340. he first closed brace Y This gives us word which would generate a syntax error 119 MikroElektronika mikoPascal PRO for PIC32 Tokens Token is the smallest element of a mikroPascal PRO for PIC32 program meaningful to the compiler The parser separates tokens from the input stream by creating the longest token possible using the input characters in a left to right scan mikroPascal PRO for PIC32 recognizes the following kinds of tokens keywords identifiers constants operators punctuators also known as separators Token Extraction Example Here is an example of token extraction Take a look at the following example code sequence end flag 0 First note that end_flag would be parsed as a single identifier rather than as the keyword end followed by the identifier flag The compiler would parse it as the following four tokens end flag variable identifier assignment operator 0 literal statement terminator Note that parses as one token the longest token possible not as token followed by token MikroElektronika 180 mikroPascal PRO for PIC32 Literals Literals are tokens representing fixed numeric or character values The data type of a constant is deduced by the compiler using such clues as numeric value and format used in the Source code Integer Literals Integral values can be represented in decimal hexadecimal or binary notation In decimal nota
341. heme button In case you need this scheme in another project you can load it using LoadScheme button There is also a Default button which lets you select default configuration bit settings for the selected device Edit Project PLL Input Divider 2x Divider PLL Multiplier MCU Name P32MX460F512L 20x Multiplier USB PLL Input Divider 12x Divider USB PLL Enable Disabled and Bypassed System PLL Output Clock Divider PLL Divide by 1 telea S UA 32 RS ril MCU and Oscillator Oscillator Frequency MHz 8 000000 Interrupt Control O Single Vector Base Address Jse SRS EBASE Ox 9FCO 1000 Oscillator Selection Bits Primary Osc XT HS EC Secondary Oscillator Enable Enabled Internal External Switch Over Enabled Primary Oscillator Configuration 1FCOZFF4 Ox00008751 XT osc mode 1FCOZFF8 Ox001485A2 1FCOZFFC OxllOFFOOB CLKO Output Signal Active on the OSCO Pin Enabled Peripheral Clock Divisor General Output Settings Pb Clkis Sys Clk 1 Related topics Project Settings Customizing Projects 611 MikroElektronika mikoPascal PRO for PIC32 Clean Project Folder This menu gives you option to choose which files from your current project you want to delete Files marked in bold can be easily recreated by building a project Other files should be marked for deletion only with a grea
342. hen default statement in the else clause if there is some is executed Here s a simple example of the case statement case operator of result nl n2 TIt result t nl n2 1 4 result nl n2 result nl n2 else result 0 end Also you can group values together for a match Simply separate the items by commas case reg of 0 opmode 0 1 2 3 4 opmode 1 Sip Op 72 opmode 2 end In mikroPascal PRO for PIC32 values in the case statement can be variables too case byte variable of byte varl opmode 0 this will be compiled correctly byte var2 opmode 1 avoid this case compiler will parse a variable followed by colon sign as label byte var3 adding a comment solves the parsing problem opmode 2 end Nested Case statement Note that the case statements can be nested values are then assigned to the innermost enclosing case statement 225 MikroElektronika mikoPascal PRO for PIC32 Iteration Statements Iteration statements let you loop a set of statements There are three forms of iteration statements in mikroPascal PRO for PIC32 for while do repeat You can use the statements break and continue to control the flow of a loop statement break terminates the statement in which it occurs while continue begins executing the next iteration of the sequence For Statement The for statement implements an iterative loop and requires
343. herwise the compiler may not be able to comprehend the program correctly When writing code follow the model presented below The main unit should look like this program program name uses include other units f ROKK RK Kk kk kk kk kk KCK I kk KK kk kk IA ko ke ek kk ke kkk kk Declarations globals J BR RK KK kk kCkCkck kk kk kk Ckck kc kckck kc kckckckckckck kc kckckckckckck kc kckckokckckckokckok ck kk constants declarations const types declarations type variables declarations var Name Name2 type absolute 0x123 external volatile register Sft labels declarations label procedures declarations procedure procedure name parameter list local declarations begin end functions declarations function function name parameter list return type local declarations begin end EEKE kk kk kk kk k k kk Ck Ck k k A k kc kCkCkCkCkCkCk k k k k k k k k KCk Ck Ck k ck k ck k ck k ck ck oko Program body J BR RK KK HK KR RK kc kckck kc kckck kckckck kc kckckckckckck I ok kk begin write your code here end 187 MikroElektronika mikoPascal PRO for PIC32 Organization of Other Units Units other than main start with the keyword unit Implementation section starts with the keyword implementation Follow the model presented below unit unit name uses include other units J BK RK RK KK kK RR A A kc kckckckckckck ok I ok
344. hey have different prices Basically there is little differences between these compilers mikroC PRO is standardized with ANSI C and it is much more complex and it is far more difficult to write the compiler for it We used a lot more resources for making it than what we used for mikroPascal and mikroBasic We also worked on some very complex topics such as floating point typedef union a completely new debugger and many other Because of that there is difference in price Why do your PIC compilers don t support 12F508 and some similar chips Unfortunately our PIC compilers don t support 12F508 and similar chips because these chips are designed to use 12 bit wide instructions Our compiler support MCUs which use 14 bit or wider instructions What are limitations of demo versions of mikroElektronika s compilers The only limitation of the free demo version is that it cannot generate hex output over 2K of program words Although it may sound restrictive this margin allows you to develop practical working applications without ever thinking of demo limit If you intend to develop really complex projects in one of our compilers you should consider purchasing the license key Why do still get demo limit error when purchased and installed license key If you are first time installing and registering compiler you need to follow instructions exactly as described in registration procedure License is valid only for the computer from which re
345. his file Therefore it is recommended to erase such file if it exists before calling this function If it is not erased and there is still enough space for a new swap file this function will delete it after allocating new memory space for a new swap file The purpose of the swap file is to make reading and writing to CF media as fast as possible by using the Cf_Read_Sector and Cf_Write_Sector functions directly without potentially damaging the FAT system Swap file can be considered as a window on the media where the user can freely write read data It s main purpose in the this library is to be used for fast data acquisition when the time critical acquisition has finished the data can be re written into a normal file and formatted in the most suitable way Parameters sectors cnt number of consecutive sectors that user wants the swap file to have filename name of the file that should be assigned for file operations The file name should be in DOS 8 3 file_name extension format The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does not have to take care of that The file name and extension are case insensitive The library will convert them to proper case automatically so the user does not have to take care of that Also in order to keep backward compatibility with the first version of this librar
346. ible See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page send message extended CAN message with the appropriate ID and data var tx flags byte data array 8 of byte msg id longint CANSPISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode CANSPI must be in mode in which transmission is possible tx flags CANSPI TX PRIORITY 0 and CANSPI TX XTD FRAME set message CANSPI Constants There is a number of constants predefined in the CANSPI library You need to be familiar with them in order to be able to use the library effectively Check the example at the end of the chapter CANSPI OP MODE Constants The CANSPI OP MODE constants define CANSPI operation mode Function CANSPISetOperationMode expects one of these as it s argument 249 MikroElektronika mikoPascal PRO for PIC32 Copy Code To Clipboard const _CANSPI MODE BITS byte SEO Use this to access opmode bits _CANSPI MODE NORMAL byte 0 _CANSPI MODE SLEEP byte 20 _CANSPI MODE LOOP byte 40 CANSPI MODE LISTEN byte 60 _CANSPI MODE CONFIG byte 80 CANSPI_CONFIG_FLAGS Constants The CANSPI CONFIG FLAGS constants define flags related to the CANSPI module configuration The functions CANSPIInit C
347. ibrary Routines 316 Keypad_Init 316 Keypad Key Press 317 Keypad Key Click 317 Library Example 318 HW Connection 319 Lcd Library 320 Library Dependency Tree 320 Keypad Key Click 320 Library Routines 320 Lcd Init 321 Lcd Out 322 Lcd Out Cp 322 Lcd Chr 322 Lcd Chr Cp 323 Lcd Cmd 323 Available Lcd Commands 323 Library Example 324 Memory Manager Library 326 Library Routines 326 Heap Init 326 GetMem 326 FreeMem 327 MM LargestFreeMemBlock 327 MM TotalFreeMemSize 327 Multi Media Card Library 328 Secure Digital Card 328 Secure Digital High Capacity Card 328 Library Dependency Tree 329 External dependencies of MMC Library 329 Library Routines 329 Mmc Init 330 Mmc Read Sector 331 Mmc Write Sector 331 Mmc Read Cid 332 Mmc Read Csd 332 Mmc Fat Init 333 Mmc Fat QuickFormat 334 Mmc Fat Assign 335 Mmc Fat Reset 336 Mmc Fat Read 336 Mmc Fat Rewrite 337 Mmc Fat Append 337 Mmc Fat Delete 337 MikroElektronika 1 mikroPascal PRO for PIC32 Mmc_Fat_Write 338 Mmc_Fat_Set_File_Date 338 Mmc Fat Get File Date 339 Mmc Fat Get File Date Modified 340 Mmc Fat Get File Size 340 Mmc Fat Get Swap File 341 Library Example 342 HW Connection 347 OneWire Library 347 Library Routines 347 Ow Reset 348 Ow Read 348 Ow Write 348 Port Expander Library 349 Library Dependency Tree 349 External dependencies of Port Expander Library 349 Library Routines 349 Expander Init 350 Expander Init Advanced 351 Expander Read Byte 352 Expander Write
348. ified in project settings SDEVICE CLOCK clock as specified in project settings COMPILERS current compiler version These macros can be used in template code see template ptemplate provided with mikroPascal PRO for PIC32 installation MikroElektronika 56 mikroPascal PRO for PIC32 Code Explorer The Code Explorer gives clear view of each item declared inside the source code You can jump to a declaration of any item by double clicking it or pressing the Enter button Also besides the list of defined and declared objects code explorer displays message about the first error and it s location in code Code Explorer 24 L7 Gg web links http fwww mikroe com Uses C9 main 5 LCD RS LCD EM LCD D4 LCD D5 LCD D6 LCD D7 LCD RS Direction LCD EN Direction LCD D4 Direction LCD DS Direction LCD D6 Direction LCD D7 Direction 5 txt txt2 txts txt4 ei M QG ove Delay The following options are available in the Code Explorer kon Descriptor Expand Collapse all nodes in tree EJ Locate declaration in code 5 MikroElektronika mikoPascal PRO for PIC32 Routine List Routine list diplays list of routines and enables filtering routines by name Routine list window can be accessed by pressing Ctrl L You can jump to a desired routine by double clicking on it or pressing the Enter button Also you can sort routines by
349. ikoPascal PRO for PIC32 Step Four Add project file to the project if they are avaiable at this point You can always add project files later using Project Manager New Project Wizard Step 4 6 Add project files if they are available at this point You can always add project files later using the Project Manager in IDE Add File To Project C Projects Hello World mpas File Name C Projects Hello World mpas Remove Remove All Cancel Step Five Select inital Library Manager state New Project Wizard Select initial Library Manager state Include Libraries Include All Default C Include None Advanced Selecting all libraries is recommended For beginners Selecting libraries manually using Library Manager recommended For advanced users results in Faster compilation Libary Manager Help Cancel MikroElektronika 604 mikroPascal PRO for PIC32 Step Six Click Finish button to create your New Project New Project Wizard Step 6 6 You have successfully created a new project Click Finish to save the changes and to close the wizard f Open Edit Project window to set Configuration bits Finish Cancel Related topics Project Manager Project Settings 605 MikroElektronika mikoPascal PRO for PIC32 Customizing Projects You can change basic project settings in the Project Settings window You can change chip and oscillator frequency Any change in the Proj
350. illegal assignments are trapped mikroPascal PRO for PIC32 supports many standard predefined and user defined data types including signed and unsigned integers of various sizes arrays strings pointers and records Type Categories Types can be divided into simple types arrays strings pointers records MikroElektronika 200 mikroPascal PRO for PIC32 Simple Types Simple types represent types that cannot be divided into more basic elements and are the model for representing elementary data on machine level Basic memory unit in mikroPascal PRO for PIC32 has 32 bits Here is an overview of simple types in mikroPascal PRO for PIC32 me Swe oe O real 32 bit 1 17549435082 10 38 6 80564774407 1038 int64 64 bit 9223372036854775808 z 92233720368547 75807 uint64 64 bit 0 18446744073709551615 You can assign signed to unsigned or vice versa only using the explicit conversion Refer to Types Conversions for more information Derived Types The derived types are also known as structured types They are used as elements in creating more complex user defined types The derived types include arrays pointers records 201 MikroElektronika mikoPascal PRO for PIC32 Arrays An array represents an indexed collection of elements of the same type called the base type Because each element has a unique index arrays unlike sets can meaningfully contain the same value more t
351. imensional array of size 5x10 A variable m is an array of 5 elements which in turn are arrays of 10 byte each Thus we have a matrix of 5x10 elements where the first element is m 0 0 and last one is n 4 9 The first element of the 4th row would be m 31 0 MikroElektronika 202 mikroPascal PRO for PIC32 Strings A string represents a sequence of characters equivalent to an array of char It is declared like this string name string length The specifier Length is a number of characters the string consists of The string is stored internally as the given sequence of characters plus a final n1 character zero which is introduced to terminate the string It does not count against the string s total length A null string is stored as a single null character You can assign string literals or other strings to string variables String on the right side of an assignment operator has to be shorter or of equal length than the one on the right side For example var msgl string 20 msg2 string 19 begin msgl This is some message msg2 Yet another message msgl msg2 this is ok but vice versa would be illegal Alternately you can handle strings element by element For example var string 5 S mik s 0 is char literal m S 1 is char literal i s 2 is char literal k s 3 is zero s 4 is undefined s 5 is undefined Be careful when handling strings in this way si
352. ine Glcd side x axis position and page should be set first See functions Glcd Set Side Glcd Set X and Glcd Set Page var data byte Glcd Read Data data Glcd Read Data This routine needs to be called twice After the first call data is placed in the buffer register After the second call data is passed from the buffer register to data lines Glcd Write Data Prototype procedure Glcd Write Data data byte Nothing Description Writes one byte to the current location in Glcd memory and moves to the next location Parameters data data to be written Requires Glcd needs to be initialized see Glcd Init routine Glcd side x axis position and page should be set first See functions Glcd Set Side Glcd Set X and Glcd Set Page var data byte Glcd Write Data data 299 MikroElektronika mikoPascal PRO for PIC32 Gled Fill Prototype Procedure Glcd Fill pattern byte Description Fills Glcd memory with the byte pattern To clear the Glcd screen useGicd Fill 0 To fill the screen completely use Glcd_ Fill OxFF ea byte to fill Glcd memory with Glcd needs to be initialized see Glcd Init routine Clear screen Gled Fall Ope Glcd Dot Prototype procedure Glcd Dot x pos y pos color byte Draws a dot on Glcd at coordinates x pos y pos Parameters x pos x position Valid values 0 127 y pos y position Valid values 0 63 color color parameter
353. ing 00000 Requires CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign File must be open for writing See Cf Fat Rewrite or Cf Fat Append var file contents array 42 of byte Cf Fat Write file contents 42 write data to the assigned file Cf Fat Set File Date Prototype procedure Cf Fat Set File Date year word month byte day byte hours byte mins byte seconds byte Description Sets the date time stamp Any subsequent file writing operation will write this stamp to currently assigned file s time date attributes Parameters year year attribute Valid values 1980 2107 month month attribute Valid values 1 12 da y day attribute Valid values 1 31 hours hours attribute Valid values 0 23 mins minutes attribute Valid values 0 59 seconds seconds attribute Valid values 0 59 Nothing Requires CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign File must be open for writing See Cf Fat Rewrite or Cf Fat Append Cf Fat Set File Date 2005 9 30 17 41 0 MikroElektronika 268 mikroPascal PRO for PIC32 Cf Fat Get File Date Prototype procedure Cf Fat Get File Date var year word var month byte var day byte var hours byte var mins byte Description Reads time date attributes of currently assi
354. inout CE IDIt initialize CF MikroElektronika 260 mikroPascal PRO for PIC32 Cf Detect Prototype Checks for presence of CF card by reading the chip detect pin 1 if CF card was detected 0 otherwise The corresponding MCU ports must be appropriately initialized for CF card See C Init Wait until CF card is inserted while Cf Detect 0 do nop PIC32 family MCU and CF card voltage levels are different The user must ensure that MCU s pin connected to CD line can read CF card Logical One correctly Cf_Enable Prototype procedure Cf Enable Description Enables the device Routine needs to be called only if you have disabled the device by means of the Cf Disable routine These two routines in conjunction allow you to free occupy data line when working with multiple devices Nothing The corresponding MCU ports must be appropriately initialized for CF card See Cf Init enable compact flash Cf Enable None Cf Disable Prototype procedure Cf Disable Description Routine disables the device and frees the data lines for other devices To enable the device again call Cf_Enable These two routines in conjunction allow you to free occupy data line when working with multiple devices P Nothing The corresponding MCU ports must be appropriately initialized for CF card See Cf Init disable compact flash Cf Disable None 261 MikroElektronika mik
355. inters All function prototypes and function pointers have to be built using the same optimizer because of different calling conventions in different optimizers In SSA function parameters are passed via working registers and without SSA they end up on the function frame This means that you cannot have a function implementation which is optimized using SSA optimizer and to call this function via function pointer in another module which is optimized using NON SSA When using pointers to functions compiler must know exactly how to pass function parameters and how to execute function call 163 MikroElektronika mikoPascal PRO for PIC32 Asm code and SSA optimization If converting code from an earlier version of the compiler which consists of mixed asm code with the Pascal code keep in mind that the generated code can substantially differ when SSA optimization option is enabled or disabled This is due to the fact that SSA optimization uses certain working registers to store routine parameters W10 W13 rather than storing them onto the function frame Because of this user must be very careful when writing asm code as existing values in the working registers used by SSA optimization can be overwritten To avoid this it is recommended that user includes desired asm code in a separate routine Debugging Notes SSA also influences the code debugging in such a way that the local variables will be available in the Watch Window
356. irection of the TFT Data Port x external sfr at TRISE var TFT_WR sbit sfr external Write signal F sbit at LATD13 bit var TFT RD sbit sfr external Read signal F sbit at LATD12 bit var TFT CS sbit sfr external Chip Select signal ET Sbit at LATC3 bit var TFT RS sbit sfr external on eem Select FT sbit at LATB15 bit FT RST sbit sfr external Reset signal FT RST sbit at LATC1 bit TE Direction sbit sfr A FT WR Direction Direction of the Write pin x pd external Dt n TET R Direction of the Register Select FT RS Direction external pin SB13 bit var TFT RST Direction Direction of the Reset pin var TFT RST Direction external pin TRISCI bit TFT R ti NE i FT_RD Di ti Lem Direction of the Read pin een on external dut TF ti Direction of the Chip Select FT CS Direction external pi it 923 MikroElektronika mikoPascal PRO for PIC32 Library Routines TFT_Init TFT_Set_Index TFT_Write_Command TFT_Write_Data TFT_Set_Active TFT_Set_Font TFT_Write_Char TFT_Write_Text TFT_Fill_Screen TFT_Set_Pen TFT_Set_Brush TFT_Dot TFT_Line TFT_H_Line TFT_V_Line TFT_Rectangle TFT_Rectangle_Round_Edges TFT_Circle TFT_Image TFT_Partiallmage TFT_Image_Jpeg TFT RGBToColor16bit TFT Color16bitTORGB MikroElektronika 524 mikroPascal PRO for PIC32 T
357. is modified to set the bit WRITE LATB is written with the new data The Modify value output driver for RB1 turns on and the output driver for RBO remains turned on Write modified value Charging T capacitor When to use LATx instead of PORTx Depending on your hardware one may experience unpredictable behavior when using PORTx bits for driving output Displays GLCD LCD chip select pins in SPI interfaces and other cases when you need fast and reliable output LATx should be used instead of PORTx 115 MikroElektronika mikoPascal PRO for PIC32 CHAPTER amp mikroPascal PRO for PIC32 Language Reference Lexical Elements Whitespace Comments Tokens Literals Keywords Identifiers Punctuators Program Organization Program Organization Scope and Visibility Units Variables Constants Labels Functions and Procedures Functions Procedures Types Simple Types Arrays Strings Pointers MikroElektronika 116 mikroPascal PRO for PIC32 Introduction to Pointers Function Pointers Pointer Arithmetic Records Types Conversions Implicit Conversion Explicit Conversion Operators Introduction to Operators Operators Precedence and Associativity Arithmetic Operators Relational Operators Bitwise Operators Boolean Operators Expressions Expressions Statements Introduction to Statements As
358. is optimized for working with 32 bit types Also it performs hardware multiplication and division on the integer level so the floating multiplication and division is slower and consumes more memory comparing it to the integer The PIC32 supports 64 bit data types but they are less efficient They provide higher precision but lack the code size and the execution Nested Calls Limitations There are no Nested Calls Limitations except by RAM size A Nested call represents a function call within the function body either to itself recursive calls or to another function Recursive calls as a form of cross calling are supported by mikroPascal PRO for PIC32 but they should be used very carefully Also calling functions from interrupt is allowed Calling function from both interrupt and main thread is allowed Be careful because this programming technique may cause unpredictable results if common resources are used in both main and interrupt Variable constant and routine alignment Simple type variables whose size exceeds 2 byte int long float double long double and those exceeding 4 bytes are always set to alignment 4 Routines are always set to aligment 4 Boot Start up Initialization Upon reset MCU positions at the address OXBFCO00000 on which the Boot StartUp function is located BootStartUp function configures CPO coprocessor registers SFR registers associated with the interrupt Stack pointer R29 and global poin
359. is way if Zero bit changes its position in the register you are sure that the appropriate bit will be affected But if Zero bit is not located in the designated register you may get errors Another way of accesing bits is by using the direct member selector with a variable followed by a primary expression Primary expression can be variable constant function call or an expression enclosed by parentheses For individual bit access there are predefined global constants BO Bi B31 0r0 1 31 with 31 being the most significant bit predefined globals as bit designators Clear bit 0 in STATUS register SR BO 0 literal constant as bit designator Set bit 5 in STATUS register SR 5 1 expression as bit designator Set bit 6 in STATUS register i 5 SR 1 1 1 In this way if the target bit changes its position in the register you cannot be sure that you are invoking the appropriate bit When using literal constants as bit designators instead of predefined ones make sure not to exceed the appropriate type size This kind of selective access is an intrinsic feature of mikroPascal PRO for PIC32 and can be used anywhere in the code Identifiers BO B31 are not case sensitive and have a specific namespace You may override them with your own members B0 B31 within any given structure Also you can access the desired bit by using its alias name in this case Z bit Set Zero Bit 5 bit i 1 In th
360. is way if the Zero bit changes its register or position in the register you are sure that the appropriate bit will be affected See Predefined Globals and Constants for more information on register bit names 135 MikroElektronika mikoPascal PRO for PIC32 sbit type The mikroPascal PRO for PIC32 compiler has sbit data type which provides access to bit addressable SFRs You can declare a sbit varible in a unit in such way that it points to a specific bit in SFR register unit MyUnit var Abit sbit sfr external Abit is precisely defined in some external file for xample in the main program unit implementation end In the main program you have to specify to which register this sbit points to for example program MyProgram var Abit sbit at PORTB 0 this is where Abit is fully defined begin end In this way the variable Abit will actually point to PORTB O Please note that we used the keyword sfr for declaration of Abit because we are pointing it to PORTB which is defined as a sfr variable In case we want to declare a bit over a variable which is not defined as sfr then the keyword sfr is not necessary for example unit MyUnit var AnotherBit sbit external Abit is precisely defined in some external file for xample in the main program unit implementation end program MyProgram var MyVar byte var Abit sbit at MyVar 0 this is where Abit is fully defined begin end Mikro
361. it at TRISFO bit CD command data signal direction var T6963C ctrlrst Direction sbit at TRISF4 bit RST reset signal direction Signals not used by library they are set in main function var T6963C ctrlce sbit at LATF3 bit CE signal var T6963C ctrlfs sbit at LATF6 bit FS signal var T6963C ctrimd sbit at LATF5 bit MD signal var T6963C ctrice Direction sbit at TRISE3 bit CE signal direction var T6963C ctrlfs Direction sbit at TRISF6 bit FS signal direction var T6963C ctrlmd Direction sbit at TRISF5 bit MD signal direction End T6963C module connections init display for 240 pixel width 128 pixel height and 8 bits character width T6963C init 240 128 T6963C writeData Prototype procedure 7T6963C writeData mydata byte Writes data to T6963C controller mydata data to be written Rems Noting SSCS Dame 76963 writenataaoarn OOOO oes None OOS MikroElektronika 502 mikroPascal PRO for PIC32 T6963C writeCommand Prototype pProcedure 76963C writeCommand mydata byte Writes command to T6963C controller mydata command to be written Toshiba Glcd module needs to be initialized See the T6963C init routine TEM ET T6963C_writeCommand T6963C_CURSOR_POINTE T6963C_setPtr ee procedure T6963C_ setPtr p word byte Sets the memory pointer for command p Parameters address where command should be written c command
362. itialized Global variables Mmc Chip Select Chip Select line Mmc Chip Select Direction Direction of the Chip Select pin must be defined before using this function MMC module connections var Mmc Chip Select sbit at LATFO bit var Mme Chip Select Direction sbit at TRISFO bit MMC module connections Initialize the SPI module SPI1 Init Advanced SPI MASTER SPI 8 BIT SPI PRESCALE SEC 1 SPI PRESCALE PRI 64 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 Loop until MMC is initialized while Mmc Init Reinitialize the SPI module at higher speed change primary prescaler SPI1 Init Advanced SPI MASTER SPI 8 BIT SPI PRESCALE SEC 1 SPI PRESCALE PRI 4 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 MikroElektronika 328 mikroPascal PRO for PIC32 Mmc Read Sector Prototype function Mmc Read Sector sector dword var dbuff array 512 of byte word The function reads one sector 512 bytes from MMC card Parameters sector MMC SD card sector to be read dbuf f buffer of minimum 512 bytes in length for data storage 0 if reading was successful 1 ifan error occurred MMC SD card must be initialized See Mmc Init read sector 510 of the MMC SD card var error word sectorNo dword dataBuffer array 512 of byte sectorNo 510 error Mmc Read Sector sectorNo dataBuffer
363. iveY Up pin DriveY Down Direction Direction of DriveY Down pin must be defined before using this function Touch Panel module connections var DriveX Left sbit at LATB13 bit var DriveX Right sbit at LATB11 bit var DriveY Up sbit at LATB12 bit var DriveY Down sbit at LATB10 bit var DriveX Left Direction sbit at TRISB13 bit var DriveX Right Direction sbit at TRISB11 bit var DriveY Up Direction sbit at TRISB12 bit var DriveY Down Direction sbit at TRISB10 bit End Touch Panel module connections if TP TFT Press Detect lt gt 0 then begin MikroElektronika 548 mikroPascal PRO for PIC32 TP_TFT_Get_Coordinates Prototype function TP TFT Get Coordinates x coordinate word y coordinate word byte Get touch panel coordinates and store them in x coordinate and y coordinate parameters Parameters x coordinate x coordinate of the place of touch y coordinate y coordinate of the place of touch 1 ifreading is within display dimension range 0 if reading is out of display dimension range if TP TFT Get Coordinates 8x coord Qy coord TP TFT Calibrate Min example re mer Calibrate Min 77 Calibration of Pottom left comer Noes noe OOS TP_TFT_Calibrate_Max eum Nothing Example TP TFT Calibrate Max Calibration of upper right corner eee cm RET DR 549 MikroElektronika mikoPascal PRO for PIC32 TP TFT Get Calibratio
364. ize pointer to the fetched memory WantedSize size in bytes of the dynamic variable to allocate Returns a pointer to the fetched memory of WantedSize bytes in P if success Otherwise 0 no free blocks of memory are large enough GetMem ptr 20 sizeof PBuffer ptr will point to a memory block where PBuffer is allocated Nes Ne OOS MikroElektronika 324 mikroPascal PRO for PIC32 FreeMem Prototype procedure FreeMem var P dword ActualSize word FreeMem destroys the variable referenced by P and returns its memory to the heap Parameters P variable of any pointer type previously assigned by the Getmem procedure ActualSize specifies the size in bytes of the dynamic variable to dispose of and should be the same as the one used to Getmem FreeMem ptr 20 sizeof PBuffer ptr will point to a memory block where PBuffer is allocated MM_LargestFreeMemBlock Prototype This function is used to determine largest available free memory block for the Heap Returns after defragmentation of the freelist the size in bytes of the largest free block of contiguous memory on the heap var block word begin block MM LargestFreeMemBlock MM TotalFreeMemSize Retums Retums the size Gn byes ofthe total fee memory ontheheap var total word begin total MM TotalFreeMemSize 329 MikroElektronika mikoPascal PRO for PIC32 Multi Media Card Library
365. ject Manager Recompile the project If you wish to use this library for all MCUs then you should go to Tools Options Output settings and check Build all files as library box This will build libraries in a common form which will work with all MCUs If this box is not checked then library will be built for selected MCU Bear in mind that compiler will report an error if a library built for specific MCU is used for another one 5 Compiled file Lib Example emcl should appear in mikroPascal PRO for PIC32 Uses folder 6 Open the definition file for the MCU that you want to use This file is placed in the compiler s Defs folder DriveName Program Files Mikroelektronika mikroPascal PRO for PIC32 Defs and it is named MCU NAME mlk for example P32MX460F512L mlk 7 Add the the following segment of code to lt LIBRARIES gt node of the definition file definition file is in XML format lt LIB gt lt ALIAS gt Example Library lt ALIAS gt FILE Lib Example lt FILE gt lt TYPE gt REGULAR lt TYPE gt lt LIB gt 8 Add Library to mlk file for each MCU that you want to use with your library 9 Click Refresh button in Library Manager 10 Example Library should appear in the Library manager window Multiple Library Versions Library Alias represents unique name that is linked to corresponding Library emcl file For example UART library for PIC32MX460F512L is different from UART library for PIC32MX675F512
366. ked in 203 ms 141 Project LCD mpp32 completed 375 ms Finished successFully 01 Feb 2011 08 37 28 LCD mpp32 8 1 9 0 0 0 0 0 0 0 0 0 Double click the message line in the Message Window to highlight the line where the error was encountered MikroElektronika 70 mikroPascal PRO for PIC32 Quick Converter Quick Converter enables the user to easily transform numbers from one base to another Quick Converter Size Sign DECIMAL HEXADECIMAL BINARY CHARACTER p Bus unsigned 77 0000004D 00000000 00000000 00000000 01001101 M Its O32bts O Signed FLOAT DECIMAL 136 893 Format OBin FLOAT 32 bit IEEE FLOAT 32 bit MICROCHIP RADIX 1 15 Hex 43 08 E4 ac 8608E49C The user can convert integers of various sizes 8 16 or 32 bits signed and unsigned using different representation decimal hexadecimal binary and character Also Quick Converter features float point numbers conversion from to Float Decimal Float 32bit IEEE Float 32bit Microchip and Radix 1 15 for PIC32 family of MCUs Macro Editor A macro is a series of keystrokes that have been recorded in the order performed A macro allows you to record a series of keystrokes and then playback or repeat the recorded keystrokes n MikroElektronika mikoPascal PRO for PIC32 The Macro offers the following commands Starts recording keystrokes for later playback Stops capturing keystroke
367. kets will be processed normaly during this time SPI Ethernet sendUDP Prototype function SPI Ethernet sendUDP var destIP array 4 of byte sourcePort destPort word pkt byte pktLen word byte This is UDP module routine It sends an UDP packet on the network Parameters dest IP remote host IP address sourcePort local UDP source port number destPort destination UDP port number pkt packet to transmit pktLen length in bytes of packet to transmit 1 UDP packet was sent successfully 0 otherwise Ethernet module has to be initialized See SPI Ethernet Init IpAddr array 4 of byte remote IP address IpAddr IpAddr IpAddr IpAddr 192 168 1 1 0 0 0 0 SPI Ethernet sendUDP IpAddr 10001 10001 Hello 5 send Hello to the above IP address from UDP port 10001 to UDP port 10001 MikroElektronika 416 mikroPascal PRO for PIC32 SPI Ethernet dnsResolve Prototype function SPI Ethernet dnsResolve var host string tmax byte word Description This is DNS module routine It sends an DNS request for given host name and waits for DNS reply If the requested host name was resolved it s IP address is stored in library global variable and a pointer containing this address is returned by the routine UDP port 53 is used as DNS port Parameters host host name to be resolved tmax time in seconds to wait for an reply pointer to the location h
368. kroElektronika mikoPascal PRO for PIC32 Copy Code To Clipboard const CANSPI RX FILTER BITS byte 07 Use this to access filter bits CANSPI RX FILTER 1 byte 00 CANSPI RX FILTER 2 byte 01 CANSPI RX FILTER 3 byte 02 CANSPI RX FILTER 4 byte 03 CANSPI RX FILTER 5 byte 04 CANSPI RX FILTER 6 byte 05 _CANSPI_RX_OVERFLOW byte 08 Set if Overflowed else cleared CANSPI RX INVALID MSG byte 10 Set if invalid else cleared CANSPI RX XTD FRAME byte 20 Set if XTD message else cleared CANSPI RX RTR FRAME byte 40 Set if RTR message else cleared CANSPI RX DBL BUFFERED byte 80 Set if this message was hardware double buffered You may use bitwise AND and to adjust the appropriate flags For example Copy Code To Clipboard if MsgFlag and CANSPI RX OVERFLOW begin 0 then Receiver overflow has occurred We have lost our previous message end CANSPI_MASK Constants The CANSPI_ MASK constants define mask codes Function CANSPISetMask expects one of these as it s argument Copy Code To Clipboard const CANSPI MASK B1 CANSPI MASK B2 byte byte CANSPI FILTER Constants The CANSPI FILTER constants define argument filter codes Functions CANSPISetFilter expects one of these as it s Copy Code To Clipboard const CANSPI FILTER B1 F1 byt
369. kroElektronika 486 mikroPascal PRO for PIC32 SPI_T6963C_setBit Prototype procedure SPI T6963C setBit b byte Description Sets control port bit s Parameters b bit mask The function will set bit x on control port if bit x in bit mask is set to 1 Nothing Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine set bits 0 and 1 on control port SPI T6963C setBit 0x03 None SPI T6963C negBit Prototype procedure SPI T6963C negBit b byte Description Negates control port bit s Parameters b bit mask The function will negate bit x on control port if bit x in bit mask is set to 1 negate bits 0 and 1 on control port SPI T6963C negBit 0x03 SPI T6963C displayGrPanel Rems Nothing SSS Toshiba Glcd module needs to be initialized See SPI T6963C Config routine display graphic panel 1 SPI_T6963C_displayGrPanel 1 487 MikroElektronika mikoPascal PRO for PIC32 SPI T6963C displayTxtPanel Remum WM SSS Toshiba Glcd module needs to be initialized See SPI T6963C Config routine display text panel 1 SPI T6963C displayTxtPanel 1 SPI T6963C setGrPanel Description Compute start address for selected graphic panel and set appropriate internal pointers All subsequent graphic operations will be preformed at this graphic panel n graphic panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See SPI
370. l sbit at LATB1 bit sbit sfx Address pin 0 var CF sbit at LATBO bit var CF RDY direction s var CF_RDY direction sbit at TR R a a Direction of the Ready pin d S H external bie Direction of the Output Enable pin external bits Direction of the Chip Detect pin external bit Direction of the Chip Enable pin external eee ee bit Direction of the Address 2 pin external brit Direction of the Address 1 pin external bit Direction of the Address 0 pin external bits var CF CD1 direction sbit at var CF CE1 direction sbit at var CF A2 direction var CF Al direction sbit at var CF A0 direction sbit at MikroElektronika 298 mikroPascal PRO for PIC32 Library Routines Cf Init Cf Detect Cf Enable Cf Disable Cf Read Init Cf Read Byte Cf Write Init Cf Write Byte Cf Read Sector Cf Write Sector Routines for file handling Cf Fat Init Cf Fat QuickFormat Cf Fat Assign Cf Fat Reset Cf Fat Read Cf Fat Rewrite Cf Fat Append Cf Fat Delete Cf Fat Write Cf Fat Set File Date Cf Fat Get File Date Cf Fat Get File Date Modified Cf Fat Get File Size Cf Fat Get Swap File The following routine is for the internal use by compiler only Cf Issue ID Command 259 MikroElektronika mikoPascal PRO for PIC32 Cf Init eums Wm Requires Global variables CF Data
371. l PRO for PIC32 each project consists of a single project file and one or more unit files Project file with extension mpp32 contains information about the project while unit files with extension mpas contain the actual Source code Units allow you to break large programs into encapsulated parts that can be edited separately create libraries that can be used in different projects distribute libraries to other developers without disclosing the source code Each unit is stored in its own file and compiled separately Compiled units are linked to create an application In order to build a project the compiler needs either a source file or a compiled unit file emc1 file for each unit Uses Clause mikroPascal PRO for PIC32 includes units by means of the uses clause It consists of the reserved word uses followed by one or more comma delimited unit names followed by a semicolon Extension of the file should not be included There can be at most one uses clause in each source file and it must appear immediately after the program or unit name Here s an example uses utils strings Unit2 MyUnit For the given unit name the compiler will check for the presence of emc1 and mpas files in order specified by the search paths If both mpas and emc1 files are found the compiler will check their dates and include the newer one in the project If the pas file is newer than emc1 a new library will be written over the
372. lbar Starting the Software Simulator makes more options available Step Into Step Over Step Out Run to Cursor etc Line that is to be executed is color highlighted blue by default Note The Software Simulator simulates the program flow and execution of instruction lines but it cannot fully emulate PIC32 device behavior i e it doesn t update timers interrupt flags etc Related topics Software Simulator Debug Windows Software Simulator Debugger Options MikroElektronika 126 mikroPascal PRO for PIC32 Software Simulator Debug Windows Debug Windows This section provides an overview of available Debug Windows in mikroPascal PRO for PIC32 Breakpoints Window Watch Values Window RAM Window Stopwatch Window EEPROM Watch Window Code Watch Window Breakpoints Window The Breakpoints window manages the list of currently set breakpoints in the project Doubleclicking the desired breakpoint will cause cursor to navigate to the corresponding location in source code In situations when multiple breakpoints are used within the code it is sometimes handy to enable disable certain breakpoints To do this just check uncheck the desired breakpoint using the checkbox in front of the breakpoint s name Breakpoints Enable Line File Name Watch Values Window Watch Values Window is the main Debugger window which allows you to monitor program execution To show the Watch Values Window select Debug Windows
373. le Opening existing file and appending data to it writing from end of file Opening a file and reading data from it sending it to USART terminal Creating and modifying several files at once Reading file contents Deleting file s Creating the swap file see Help for details Copy Code To Clipboard program CF Fatl6 Test set compact flash pinout var Cf Data Port byte at PORTE CF RDY sbit at RD7 bit CF WE sbit at LATD6 bit CF OE sbit at LATDS bit CF CD1 sbit at RD4 bit CF CEl sbit at LATD3 bit CF A2 sbit at LATD2 bit CF A1 sbit at LATD1 bit CF A0 sbit at LATDO bit CF RDY direction CF WE direction CF OE direction CF CDI direction CF CE1 direction CF A2 direction CF A1 direction CF A0 direction sbit at sbit at sbit at sbit at sbit at sbit at sbit at sbit at TRISD7 bit TRISD6 bit TRISDS bit TRISD4 bit TRISD3 bit TRISD2 bit TRISD1 bit TRISDO bit end of compact flash pinout const LINE LEN 39 var err txt string 20 file contents string LINE LEN filename string 14 File names character byte loop loop2 byte i size longint Buffer array 512 of byte UART write text and new line procedure UART1 Write Line var uart text carriage return line string feed MikroElektronika 212 mikroPascal PRO for PIC32 begin UART1 Write Text uart text UART1 Write 13 UART1 Write 10
374. le you want to use To select the desired SPI module simply change the letter x in the routine prototype for a number from 1 to 3 Number of SPI modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library SPIx Write Requires Routine requires at least one SPI module Used SPI module must be initialized before using this function See the SPIx Init and SPlx Init Advanced routines write a byte to the SPI bus var buffer byte SPI1 Write buffer SPI library routines require you to specify the module you want to use To select the desired SPI module simply change the letter x in the routine prototype for a number from 1 to 3 Number of SPI modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 399 MikroElektronika mikoPascal PRO for PIC32 SPI_Set_Active Prototype procedure SPI Set Active read ptr TSPI Rd Ptr write ptr TSPI Wr Ptr Sets the active SPI module which will be used by the SPIx Read and SPIx Write routines Parameters Parameters read ptr SPI1 Read handler write ptr SPI1 Write handler Requires Routine is available only for MCUs with multiple SPI modules Used SPI module must be initialized before using this function See the SPIx Init and SPIx Init Advanced routines Example SPI Set Active 8SPI1 Read 6SPI1 Write Sets the SPI1 module active Number of SPI m
375. library example destPort word UDP request handler at the bottom of this page reqLength word for code implementation var flags TEthj600PktFlags 429 MikroElektronika mikoPascal PRO for PIC32 Library Routines SPI Ethernet 24j600 Init SPI Ethernet 24j600 Enable SPI Ethernet 24j600 Disable SPI Ethernet 24j600 doPacket SPI Ethernet 24j600 putByte SPI Ethernet 24j600 putBytes SPI Ethernet 24j600 putString SPI Ethernet 24j600 putConstString SPI Ethernet 24j600 putConstBytes SPI Ethernet 24j600 getByte SPI Ethernet 24j600 getBytes SPI Ethernet 24j600 UserTCP SPI Ethernet 24j600 UserUDP SPI Ethernet 24j600 getlpAddress SPI Ethernet 24j600 getGwlpAddress SPI Ethernet 24j600 getDnslpAddress SPI Ethernet 24j600 getlpMask SPI Ethernet 24j600 confNetwork SPI Ethernet 24j600 arpResolve SPI Ethernet 24j600 sendUDP SPI Ethernet 24j600 dnsResolve SPI Ethernet 24j600 initDHCP SPI Ethernet 24j600 doDHCPLeaseTime SPI Ethernet 24j600 renewDHCP MikroElektronika 430 mikroPascal PRO for PIC32 SPI Ethernet 24j600 Init Prototype procedure SPI Ethernet 24600 Init mac byte ip byte fullDuplex configuration Description This is MAC module routine It initializes ENC2 47600 controller This function is internaly splited into 2 parts to help linker when coming short of memory ENC24J600 controller settings parameters not mentioned he
376. ll this function after TP Init threshold custom ADC threshold value TP Init has to be called before l this routine TP Set ADC Threshold 3900 Set touch panel ADC threshold Me Nw MikroElektronika 542 mikroPascal PRO for PIC32 TP Press Detect ID Detects if the touch panel has been pressed 1 if touch panel is pressed 0 otherwise Requires Global variables DriveA DriveA DriveB DriveB DriveA Direction Direction of DriveA pin DriveB Direction Direction of DriveB pin must be defined before using this function Touch Panel module connections var DriveA sbit at LATC13 bit DriveB sbit at LATC14 bit DriveA Direction sbit at TRISC13 bit DriveB Direction sbit at TRISC14 bit End Touch Panel module connections if TP Press Detect 0 then begin 543 MikroElektronika mikoPascal PRO for PIC32 TP_Get_Coordinates Prototype function TP Get Coordinates x coordinate word y coordinate word byte Get touch panel coordinates and store them in x coordinate and y coordinate parameters Parameters x coordinate x coordinate of the place of touch y coordinate y coordinate of the place of touch 1 if reading is within display dimension range 0 if reading is out of display dimension range if TP Get Coordinates 8x coord Qy coord 0 then begin end TP Calibrate Bottom Left PRewums Ng CTO Example 7e _
377. lower A returns 0 MikroElektronika 910 mikroPascal PRO for PIC32 ispunct Prototype function ispunct character byte word Description Function returns OxFF if the character is a punctuation decimal 32 47 58 63 91 96 123 126 otherwise returns zero s islower 0 returns OxFF islower A returns 0 isspace Prototype function isspace character byte word Description Function returns OxFF if the character is a white space space tab CR HT VT NL FF otherwise returns zero isspace returns OxFF 2 ad returns 0 isupper Prototype function isupper character byte word Function returns OxFF if the character is an uppercase letter A Z otherwise returns zero res isupper A returns OxFF res isupper a returns 0 isxdigit prone es function isxdigit character byte word Function returns OxFF if the character is a hex digit 0 9 A F a f otherwise returns zero isxdigit A returns OxFF isxdigit f f returns 0 toupper Prototype function toupper character byte byte Description If the character is a lowercase letter a z the function returns an uppercase letter Otherwise the function returns an unchanged input parameter toupper a returns A toupper B returns B tolower Prototype function tolower character byte byte Description If the character is an uppercase
378. lp there Do you have some discount on your compilers development systems for students professors Since large percentage of our customers are schools laboratories and students our prices are already scaled for these kinds of users If you plan ordering more than one of our products see special offers page on our website Also you can contact our Sales Department and see if you are eligible for some additional discount have a question about your compilers which is not listed here Where can find an answer Firstly look for it in your compiler s Help If you don t find an answer there please create a support ticket on our website 617 MikroElektronika W0D SOJ4IW Sd JJO je SN JOLJUOD 0j ejejiseu jou op sjesodoud sseursnd JO sjueuiuioo suonsenb Aue ney nof Ji po dis wov Soiu MMM S ye 1exon INOA eoejd se jd uoneuuojul jeuohippe pasu TENE sponpoud ano Jo hue YIM Suie qoid E eu toned olZ noA j e C WOP G0JXIUIMWWM Je 91ISq9 JNO YSA sionpoid m De QOL uee oj flem nof ji Mouser Electronics Authorized Distributor Click to View Pricing Inventory Delivery amp Lifecycle Information MikroElektronika MIKROE 748
379. lpAdadress fetch DNS IP address SPI Ethernet getlpMask fetch IP subnet mask UDP port 68 is used as DHCP client port and UDP port 67 is used as DHCP server port tmax time in seconds to wait for an reply 1 network parameters were obtained successfully 0 otherwise Ethernet module has to be initialized See SPI Ethernet Init SPI Ethernet initDHCP 5 get network configuration from DHCP server wait 5 sec for the response The Ethernet services are not stopped while this routine waits for DNS reply The incoming packets will be processed normaly during this time When DHCP module is used global library variable SPI Ethernet userTimerSec is used to keep track of time It is user responsibility to increment this variable each second in it s code SPI Ethernet doDHCPLeaseTime Prototype function SPI Ethernet doDHCPLeaseTime byte Description This is DHCP module routine It takes care of IP address lease time by decrementing the global lease time library counter When this time expires it s time to contact DHCP server and renew the lease 0 lease time has not expired yet 1 lease time has expired it s time to renew it Ethernet module has to be initialized See SPI Ethernet Init while true do if SPI Ethernet doDHCPLeaseTime 0 then begin it s time to renew the IP address lease MikroElektronika 418 mikroPascal PRO for PIC32 SPI Ethernet renewDHCP
380. lue Parameters SJW as defined in MCU s datasheet CAN Module BRP as defined in MCU s datasheet CAN Module PHSEG1 as defined in MCU s datasheet CAN Module PHSEG2 as defined in MCU s datasheet CAN Module PROPSEG as defined in MCU s datasheet CAN Module CANSPI CONFIG FLAGS is formed from predefined constants See CANSPI CONFIG FLAGS constants Nothing 243 MikroElektronika mikoPascal PRO for PIC32 Requires Global variables CanSpi CS Chip Select line CanSpi Rst Reset line CanSpi CS Direction Direction of the Chip Select pin CanSpi Rst Direction Direction of the Reset pin must be defined before using this function The CANSPI routines are supported only by MCUs with the SPI module The SPI module needs to be initialized See the SPIx Init and SPIx Init Advanced routines MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page CANSPI module connections var CanSpi CS sbit at LATFO bit CanSpi CS Direction Sbit at TRISFO bit CanSpi Rst sbit at LATF1 bit CanSpi Rst Direction sbit at TRISF1 bit End CANSPI module connections var CANSPI Init Flags word CANSPI Init Flags CANSPI CONFIG SAMPLE THRICE and CANSPI CONFIG PHSEG2 PRG ON and CANSPI CONFIG STD MSG and CANSPI CONFIG DBL BUFFER ON and CANSPI CONFIG VALID XTD MSG and CANSPI CONFIG LINE FILTER OFF
381. lue 5 to variable j is at the address 0x003A ptrl i ptrl is a pointer to byte pointing to i ptr2 Qj ptr2 is a pointer pointing to j x t ptr2 ptrl result is equal to the distance between the two pointed ad dresses x 1 1 byte x teUpLrl ptr2 result is equal to the difference of the values pointed to x 5 end 209 MikroElektronika mikoPascal PRO for PIC32 Records A record analogous to a structure in some languages represents a heterogeneous set of elements Each element is called a field The declaration of the record type specifies a name and type for each field The syntax of a record type declaration is type recordTypeName record fieldListl typel fieldListn typen end where recordTypeName is a valid identifier each type denotes a type and each fieldList is a valid identifier or a comma delimited list of identifiers The scope of a field identifier is limited to the record in which it occurs so you don t have to worry about naming conflicts between field identifiers and other variables Note In mikroPascal PRO for PIC32 you cannot use the record construction directly in variable declarations i e without t ype For example the following declaration creates a record type called TDot type TDot record x y i veal end Each TDot contains two fields x and y coordinates Memory is allocated when you declare the record like this var m n TDot This variable
382. lues a ADPCFG OxFFFF m 4 E Gi GS 0 amp oo op m fu E Lcd Init a Add Remove Properties i Add All Remove All r Lcd Cmd LCD CLEAR Select variable from list Lcd Cmd LCD CURSOR OFF text bd B 30 Search for variable by assembly name 9 for i 1 i lt 17 i _text Cip d Lcd Chr i i text i i1 4 Peripherals Freeze Saati E Name Value Address text um 0x0800 PC Q0x000284 0 00 us 117 MikroElektronika mikoPascal PRO for PIC32 ES EP NO A 0 0 00 0 Step Into F7 Step Over F8 and Step Out Ctrl F8 are mikrolCD debugger functions that are used in stepping mode There is also a Real Time mode supported by the mikrolCD Functions that are used in the Real Time mode are Run Pause Debugger F6 and Run to cursor F4 Pressing F4 executes the code until the program reaches the cursor position line ELE 47 begin ADPCFG OxFFFF e text mikroElektronika 50 Led Init 9 Lcd Cmd LCD CLEAR EB 53 d E for i 1 to 17 do begin Lcd Chr 1 i text i 1 9 i end e end Watch Values Eh Bi 5h 0 08 ot amp FE fu a Add 3 Remove Properties yg AddAll A Remove All Select variable from list text X Search for variable by assembly name _text EY Peripherals Freeze Mame Value text i PC 0x0002DA 65 55 ms Run Pause Debugger F6 and Toggle Breakpoints F5 are mikrolCD debugger functions that are
383. ly add its common typos by entering original typo for example 5t ye to the Original box and replacement byte to the Replacement box and just click Add button Next time when the typo occurs it will be automatically corrected Auto Complete Code Templates Auto Complete option saves lots of keystrokes for commonly used phrases by automatically completing user s typing Options Editor Settings V Enable Auto Complete LV Key word dow Editor Colors e Auto Correct do while Description do while For no Auto Complete for statement i function header template int Func declaration Style if iF no 9 ife if no begin end else no beginfend ifes if else ifs if statement proc void Func declaration ptemplate header comment for a project switch switch statement do while mikoPascal PRO for PIC32 The user can insert the Code Template by typing the name of the template for instance dow then press Ctrl J and the Code Editor will automatically generate a code do L Auto Complete dow do while You can add your own templates to the list by entering the desired keyword description and code of your template in appropriate boxes Autocomplete macros can retreive system and project information DATE current system date TIMES current system time SDEVICES device MCU name as spec
384. m the extended ASCII character set enclosed with apostrophes Character literal can be assigned to variables of the byte and char type variable of byte will be assigned the ASCII value of the character Also you can assign character literal to a string variable Note Quotes have no special meaning in mikroPascal PRO for PIC32 String Literals String literal is a sequence of characters from the extended ASCII character set written in one line and enclosed with apostrophes Whitespace is preserved in string literals i e parser does not go into strings but treats them as single tokens Length of string literal is a number of characters it consists of String is stored internally as the given sequence of characters plus a final null character This null character is introduced to terminate the string it does not count against the string s total length String literal with nothing in between the apostrophes null string is stored as a single null character You can assign string literal to a string variable or to an array of char Here are several string literals Hello world message 12 chars long Temperature is stable message 21 chars long 1 t two spaces 2 chars long nes letter 1 char long null string 0 chars long The apostrophe itself cannot be a part of the string literal i e there is no escape sequence You can use the built in function Chr to print an apostrophe Chr 39 Also see String S
385. ment value end DAC Output value Send value to DAC chip Delay ms 1 Slow down key repeat pac end end MikroElektronika 386 mikroPascal PRO for PIC32 Software UART Library The mikroPascal PRO for PIC32 provides routines for implementing Software UART communication These routines are hardware independent and can be used with any MCU The Software UART Library provides easy communication with other devices via the RS232 protocol Important The Software UART library implements time based activities so interrupts need to be disabled when using it Library Routines Soft UART Init Soft UART Read Soft UART Write Soft UART Break Soft UART Init Prototype function Soft UART Init var port word rx tx word baud rate dword inverted word byte Description Configures and initializes the software UART module Software UART routines use Delay Cyc routine If requested baud rate is too low then calculated parameter for calling Delay Cyc exceeds Delay Cyc argument range If requested baud rate is too high then rounding error of Delay Cyc argument corrupts Software UART timings Parameters port software UART port address rx receiver pin tx transmiter pin baud rate requested baudrate Maximum baud rate depends on the MCU s clock and working conditions inverted if set to non zero value indicates inverted logic on output 2 error requested baud rate is too low 1 error req
386. mikoPascal PRO for PIC32 With Statement The With statement is a convenient method for referencing elements of a complex variable such as a record It simplifies the code by removing the need to prefix each referenced element with the complex variable name i e accessing all of the record s fields with only one reference Example program With Test type Circle Parameters Record x center integer y center integer radius integer end var Circle Circle Parameters begin With Circle do begin x center 50 y center 60 radius 10 end end Directives Directives are words of special significance which provide additional functionality regarding compilation and output The following directives are at your disposal Compiler directives for conditional compilation Linker directives for object distribution in memory Compiler Directives mikroPascal PRO for PIC32 treats comments beginning with a 5 immediately following an opening brace as a compiler directive for example 5 ELS E The compiler directives are not case sensitive You can use a conditional compilation to select particular sections of code to compile while excluding other sections All compiler directives must be completed in the source file in which they have begun MikroElektronika 230 mikroPascal PRO for PIC32 Directives DEFINE and UNDEFINE Use directive SDEFINE to define a condi
387. mikroPascal PRO for PIC32 Metacharacters Predefined classes Ww an alphanumeric character including NW a nonalphanumeric character Xd a numeric character XD a non numeric character Xs any space same as t n r f S anon space You may use w dand s within custom character classes Example routi de matches strings like routile routi6e and so on but not routine routime and so on Metacharacters Word boundaries A word boundary X5 is a spot between two characters that has an alphanumeric character Vw on one side and a nonalphanumeric character NW on the other side in either order counting the imaginary characters off the beginning and end of the string as matching a Ww b match a word boundary XB match a non word boundary Metacharacters Iterators Any item of a regular expression may be followed by another type of metacharacters iterators Using this metacharacters you can specify number of occurences of previous character metacharacter or subexpression zero or more greedy similar to 0 one or more greedy similar to 1 zero or one greedy similar to 0 1 n exactly n times greedy n atleast n times greedy n m atleast n but not more than m times greedy Zero or more non greedy similar to 0 one or more non greedy similar to 1 zero or on
388. mily of MCUs be aware of their voltage incompatibility with certain number of T6963C based Glcd modules So additional external power supply for these modules may be required ChipEnable CE FontSelect FS and Reverse MD have to be set to appropriate levels by the user outside of the T6963C_lInit function See the Library Example code at the bottom of this page Glcd size based initialization routines can be found in setup library files located in the Uses folder The user must make sure that used MCU has appropriate ports and pins If this is not the case the user should adjust initialization routines Some mikroElektronika s adapter boards have pinout different from T6369C datasheets Appropriate relations between these labels are given in the table below Adapter Board T6369C datasheet RD Library Dependency Tree Te963c Trigonometry MikroElektronika 498 mikroPascal PRO for PIC32 External dependencies of T6963C Graphic Lcd Library The following variables must be defined in all projects using T6963C Description Graphic Lcd library var T6963C_dataPort word sfr T6963C Data Port var T6963C dataPort word at external PORTB var T6963C ctrlwr sbit sfr Write sianal var T6963C ctrlwr sbit at external ibid LATF2 bit var T6963C ctrlrd sbit sfr Read sianal var T6963C ctrlrd sbit at external gnat LATF1 bit var T6963C ctrhod i sbit sfr 5 var T6963C ctrlcd 1 sbit at
389. module exists external to the CPU logic and prioritizes the interrupt events before presenting them to the CPU The PIC32MX Interrupts module includes the following features Up to 96 interrupt sources Up to 64 interrupt vectors Single and Multi Vector mode operations Five external interrupts with edge polarity control Interrupt proximity timer Module freeze in Debug mode Seven user selectable priority levels for each vector Four user selectable subpriority levels within each priority User configurable shadow set based on priority level this feature is not available on all devices refer to the specific device data sheet for availability Software can generate any interrupt User configurable interrupt vector table location ISRs are organized in IVT ISR is defined as a standard function but with the iv directive afterwards which connects the function with specific interrupt vector For more information on IVT refer to the PIC32 Family Reference Manual Configuring Interrupts The PIC32MX interrupt controller can be configured to operate in one of two modes Single Vector mode all interrupt requests will be serviced at one vector address mode out of reset Multi Vector mode interrupt requests will be serviced at the calculated vector address Single Vector Mode In this mode the CPU always vectors to the same address This means that only one ISR can be defined The Single Vector mode addres
390. month outstr UART1 Write Text outstr WordToStr day outstr MikroElektronika 342 mikroPascal PRO for PIC32 UART1 Write Text outstr WordToStr hour outstr UART1 Write Text outstr WordToStr minute outstr UART1 Write Text outstr file has been found get its modified date UART1 Write Text modified WordToStr year outstr UART1 Write Text outstr ByteToStr month outstr UART1 Write Text outstr WordToStr day outstr UART1 Write Text outstr WordToStr hour outstr UART1 Write Text outstr WordToStr minute outstr UART1 Write Text outstr get file size fsize Mmc Fat Get File Size LongWordToStr longint fsize outstr UART Write Line outstr end else begin file was not found signal it UART1 Write 0x55 Delay ms 1000 UART1 Write 0x55 Mmc Fat Get File Date Modified year month day hour minute end end jgeeutexeee cue Tries to create a swap file whose size will be at least 100 es sectors see Help for details procedure M Create Swap File var i word begin for i 0 to 511 do Buffer i i size Mmc Fat Get Swap File 5000 mikroE txt 0x20 see help on this function for details if size 0 then begin LongIntToStr size err txt UART Write Line err txt for i 0 to 4999 do begin Mmc Write Sector size Buffer I
391. mp Chip Select 1 Deselect end begin CHECON 0x32 ADIPCFG OxFFFF td InitMain Perform main value 2048 When program e the output InitMain Perform main value 2048 When program td the output while TRUE do Endless loop begin if RBO bit and value lt 4095 then Inc value else begin if RBl bit and value gt 0 then Dec value end DAC Output value Delay ms 1 end end increment value If RAl button is pressed decrement value Send value to DAC chip Slow down key repeat pac 401 MikroElektronika mikoPascal PRO for PIC32 HW Connection CN10 DAC CONNECTOR OSCILLATOR SPI HW connection MikroElektronika 402 mikroPascal PRO for PIC32 SPI Ethernet Library The ENC28J60 is a stand alone Ethernet controller with an industry standard Serial Peripheral Interface SPI It is designed to serve as an Ethernet network interface for any controller equipped with SPI The ENC28460 meets all of the IEEE 802 3 specifications It incorporates a number of packet filtering schemes to limit incoming packets It also provides an internal DMA module for fast data throughput and hardware assisted IP checksum calculations Communication with the host controller is implemented via two interrupt pins and the SPI with data rates of up to 10 Mb s Two dedicated pins are used for LED link and network
392. must be defined DescHatioiE in all projects using RS 485 Library P var RS485 rxtx pin sbit sfr Control RS 485 Transmit Receive var RS485 rxtx pin sbit at RF2 external operation mode bit var RS485 rxtx pin direction Direction of the RS 485 Transmit var RS485 rxtx pin direction sbit sbit sfr external Receive pin at TRISF2 bit 36 MikroElektronika mikoPascal PRO for PIC32 Library Routines RS485Master_Init RS485Master_Receive RS485Master_Send RS485Slave Init RS485Slave Receive RS485Slave Send RS485Master Init Reums Noi Requires Global variables RS485 rxtx pin this pin is connected to RE DE input of RS 485 transceiver see schematic at the bottom of this page RE DE signal controls RS 485 transceiver operation mode RS485 rxtx pin direction direction of the RS 485 Transmit Receive pin must be defined before using this routine UART HW module needs to be initialized See UARTx Init RS485 module pinout var RS485 rxtx pin sbit at RF2 bit var RS485 rxtx pin direction sbit at TRISF2 bit End of RS485 module pinout UART1 Init 9600 initialize UART1 module RS485Master Init intialize MCU as a Master for RS 485 communication MikroElektronika 368 mikroPascal PRO for PIC32 RS485Master_Receive aaa Parameters Requires procedure RS485Master Receive var data array 10 of byte Receives messages from Slaves Message
393. n SPI Led Out CP Herel SPI Lcd Chr Prototype procedure SPI Lcd Chr Row Column Out Char byte Prints character on Lcd at specified position Both variables and literals can be passed as character Parameters Row writing position row number Column Writing position column number Out Char character to be written Lcd needs to be initialized for SPI communication see SPI Lcd Config routine Write character i at row 2 column 3 SPE ked Chr 2 3 arie SPI Lcd Chr Cp ee procedure SPI Lcd Chr CP Out Char byte Prints character on Lcd at current cursor position Both variables and literals can be passed as character Out Char character to be written Lcd needs to be initialized for SPI communication see SPI Lcd Config routine Write character e at current cursor position SPI Lcd Chr Cp e MikroElektronika 464 mikroPascal PRO for PIC32 SPI Lcd Cmd Prototype procedure SPI Lcd Cmd out char byte Description Sends command to Lcd Parameters out char command to be sent Nothing Requires Lcd needs to be initialized for SPI communication see SPI Lcd Config routine Clear Lcd display SPI Lcd Cmd LCD CLEAR Predefined constants can be passed to the routine see Available SPI Lcd Commands Available SPI Lcd Commands Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected
394. n and therefore without side effects The result of the operation will be the size of the type of the expression s result Sizeof Applied to Type If applied to a type identifier sizeof returns the size of the specified type The unit for type size is sizeof byte which is equivalent to one byte Thus sizeof byte returns 1 sizeof integer returns 2 sizeof dword returns 4 sizeof real returns 4 When the operand is a non parameter of array type the result is the total number of bytes in the array in other words an array name is not converted to a pointer type var i j integer samples array 10 of integer j sizeof samples 1 j sizeof integer 2 i sizeof samples i 10 sizeof integer 20 If the operand is a parameter declared as array type or function type sizeof gives the size of the pointer When applied to records sizeof gives the total number of bytes including any padding The operator sizeof cannot be applied to a function MikroElektronika 220 mikroPascal PRO for PIC32 Expressions An expression is a sequence of operators operands and punctuators that returns a value The primary expressions include literals constants variables and function calls More complex expressions can be created from primary expressions by using operators Formally expressions are defined recursively subexpressions can be nested up to the limits of memory Expressions are ev
395. n see SPI Lcd8 Config routine Write text Here at current cursor position SPI Leds Out Cp Herel l SPI Lcd8 Chr Prototype procedure SPI Lcd8 Chr row column out char byte Prints character on Lcd at specified position Both variables and literals can be passed as character Parameters row writing position row number column Writing position column number out char character to be written Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routine Write character i at row 2 column 3 SPI Lod8 Chr 2 3 Je MikroElektronika A10 mikroPascal PRO for PIC32 SPI Lcd8 Chr Cp Prototype procedure SPI Lcd8 Chr CP out char byte Description Prints character on Lcd at current cursor position Both variables and literals can be passed as character Parameters out char character to be written Nothing Requires Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routine Print e at current cursor position M s AE Write character e at current cursor position SPI Lcd8 Chr Cp e SPI Lcd8 Cmd Prototype procedure SPI Lcd8 Cmd out char byte Description Sends command to Lcd Parameters out char command to be sent Nothing Requires Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routine Clear Lcd display SPI Lcd8 Cmd LCD CLEAR Predefined constants can be passed to the ro
396. n Consts Prototype procedure TP TFT Get Calibration Consts x min word x max word y min word y max word Description Gets calibration constants after calibration is done and stores them in x min x max y min and y max parameters Parameters x min x coordinate of the bottom left corner of the working area x max X coordinate of the upper right corner of the working area y min y coordinate of the bottom left corner of the working area y max y coordinate of the upper right corner of the working area TP TFT Get Calibration Consts 8x min y min 8x max y max calibration constants TP TFT Set Calibration Consts Prototype procedure TP TFT Set Calibration Consts x min word x max word y min word y max word Sets calibration constants Parameters x min x coordinate of the bottom left corner of the working area x max X coordinate of the upper right corner of the working area y min y coordinate of the bottom left corner of the working area y max y coordinate of the upper right corner of the working area TP TFT Set Calibration Consts 173 776 75 760 Set calibration constants MikroElektronika 550 mikroPascal PRO for PIC32 HW Connection TFT 320x240 display MI0283QT2 Touch Panel TFT HW connection 991 MikroElektronika mikoPascal PRO for PIC32 UART Library The UART hardware module is available with a number of PIC32 MCUs Th
397. n your compilers in commercial purposes Are there some limitations Regarding your code there are no limitations Your application is your own property and you can do whatever you like with it If you want to include some of code we provide with our compilers or on our site you may include them in your project however you are not allowed to charge your users for these Why does an example provided with your compilers doesn t work All of the examples provided with our compilers are tested and work fine You need to read commented header of the example and be sure that you have used the same MCU example is written for and that you have hardware connections DIP switches jumpers etc set as described Your example works if use the same MCU you did but how to make it work for another MCU You should read your MCU s datasheet Different MCUs can have different pin assignments and may require different settings If you need help regarding this you can find free online books on our website and recommend you starting there You can also ask for help on our forum MikroElektronika 616 mikroPascal PRO for PIC32 need this project finished can you help me We currently do not do custom projects however we can give you some directions when you start working on your project and come to a problem Also our forum is very active community and as you can find there experts in different fields we encourage you to look for he
398. na 17 tmp l1 dyna 18 tmp 2 dyna 19 tmp 3 dyna 20 tmp 4 dyna 21 WordToStr destPort tmp dyna 22 tmp 0 dyna 23 tmp 1 dyna 24 tmp 2 dyna 25 tmp 3 dyna 26 tmp 4 dyna 27 dyna 28 0 the total length of the request is the length of the dynamic string plus the text of the request result 28 reqLength puts the dynamic string into the transmit buffer SPI Ethernet _putBytes dyna 28 then puts the request string converted into upper char into the transmit buffer while regLength lt gt 0 do begin SPI Ethernet putByte SPI Ethernet getByte reqLength reqLength 1 end back to the library with the length of the UDP reply end begin CHECON 0x32 ADIPCFG OxFFFC all digital but RB1 AN1 and RBO ANO PORTB 0 TRISB OxFFFF set PORTB as input for buttons and adc PORTD 0 TRISD 0 set PORTD as output ADC1 Init httpCounter 0 set mac address myMacAddr 0 0x00 myMacAddr 1 0x14 myMacAddr 2 0xA5 myMacAddr 3 0x76 myMacAddr 4 0x19 myMacAddr 5 Ox3F 425 MikroElektronika mikoPascal PRO for PIC32 set IP address mylpAddr 0 192 mylpAddr 1 168 mylpAddr 2 20 mylpAddr 3 60 set gateway address gwlpAddr 0 192 gwIpAddr 1 168 gwlpAddr 2 20 gwlIpAddr 3 6 set dns address dansIpAddr 0 192 dnsIpAdd
399. nc size UART1 Write end end end 343 MikroElektronika mikoPascal PRO for PIC32 f Main Uncomment the function s to test the desired operation s begin SDEFINE COMPLETE EXAMPLE comment this line to get smaller example err txt FAT16 not found file contents XX MMC SD FAT16 library by Anton Rieckert file contents 41 10 newline filename MIKROOOxTXT CHECON 0x32 ADIPCFG OxFFFF initialize AN pins as digital Initialize UART1 module UART1 Init 56000 Delay ms 10 UART Write Line MCU Started MCU present report set up SPI for the file read SPI2 Ini t Advanced SPI MASTER SPI 8 BIT 64 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 IDLE Delay ms 10 use fati6 quick format instead of init routine if a formatting is needed if Mmc Fat Init 0 then begin reinitialize spi at higher speed SPI2 Init Advanced SPI MASTER SPI 8 BIT 8 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 IDLE Test start UART Write Line Test Start Test routines Uncomment them one by one to test certain features M Create New File SIFDEF COMPLETE EXAMPLE M Create New File M Create Multiple Files M Open File Rewrite M Open File Append M Open File Read M Delete File M Test File Exist M Create Swap File
400. nce overwriting the end of a string will cause an unpredictable behavior String Concatenating mikroPascal PRO for PIC32 allows you to concatenate strings by means of plus operator This kind of concatenation is applicable to string variables literals character variables literals For control characters use the non quoted hash sign and a numeral e g 13 for CR 203 MikroElektronika mikoPascal PRO for PIC32 var msg string 20 res txt string 5 res channel word begin jd siis Get result of ADC res Adc Read channel Create string out of numeric result WordToStr res res txt Prepare message for output msg Result is Text Result is res txt E Result of ADC jd AEn Notes In current version plus operator for concatenating strings will accept at most two operands mikroPascal PRO for PIC32 includes a String Library which automatizes string related tasks Pointers A pointer is a data type which holds a memory address While a variable accesses that memory address directly a pointer can be thought of as a reference to that memory address To declare a pointer data type add a carat prefix before type For example in order to create a pointer to an integer Write integer In order to access data at the pointer s memory location add a carat after the variable name For example let s declare variable p which points to a word and then assign value 5 to the pointed
401. nclusive asin 0 5 res 5 235987e 1 MikroElektronika 596 mikroPascal PRO for PIC32 atan Prototype function atan arg real real atan 1 0 res 7 853982e 1 Description Function computes the arc tangent of parameter f that is the value whose tangent is The return value is in radians between I1 2 and 1 2 inclusive atan2 Prototype function atan2 y real x real real Description This is the two argument arc tangent function It is similar to computing the arc tangent of y x except that the signs of both arguments are used to determine the quadrant of the result and x is permitted to be zero The return value is in radians between M and M inclusive gt J tes 4 636475e 1 MAL function ceil real real Function returns value of alls x rounded up to the next whole number ceil 0 5 res 1 000000 das it function cos arg real real Function returns the cosine of f in radians The return value is from 1 to 1 es cos PI 3 res 0 500008 real real eXt e 2 If the value of x ces 1 600286 eval_poly Prototype function eval poly x real var d array 10 of real n byte real Function Calculates polynom for number x with coefficients stored in for degree n 597 MikroElektronika mikoPascal PRO for PIC32 exp Prototype function exp x real real Function returns the value of e the ba
402. ncorporates a number of packet filtering schemes to limit incoming packets It also provides an internal 16 bit wide DMA module for fast data throughput and hardware assisted IP checksum calculations Communication with the host controller is implemented via two interrupt pins and the SPI with data rates of 10 100 Mb s Two dedicated pins are used for LED link and network activity indication This library is designed to simplify handling of the underlying hardware ENC24J600 It works with any PIC32 with integrated SPI and more than 4 Kb ROM memory 38 to 40 MHz clock is recommended to get from 8 to 10 Mhz SPI clock otherwise PIC32 should be clocked by ENC24J600 clock output due to its silicon bug in SPI hardware If you try lower PIC32 clock speed there might be board hang or miss some requests SPI Ethernet ENC24J600 library supports IPv4 protocol ARP requests ICMP echo requests UDP requests TCP requests no stack no packet reconstruction ARP client with cache DNS client UDP client DHCP client packet fragmentation is NOT supported Important Global library variable SPI Ethernet 243600 userTimerSec is used to keep track of time for all client implementations ARP DNS UDP and DHCP It is user responsibility to increment this variable each second in it s code if any of the clients is used For advanced users there is EcnEnc243600Private mpas unit in Uses folder of the compiler with de
403. nd the upper 2 GB are divided into KSEGO KSEG1 KSEG2 and KSEG3 Virtual vs Physical Addresses The PIC32MX s CPU uses virtual addresses to address the peripherals which means that to access the PIC32MX s peripherals we and the CPU must be operating within the virtual boundaries of KSEG1 The PIC32MX s CPU also uses virtual addressing to fetch and execute program memory instructions If you look closely you ll see that the physical address region between the INTERNAL RAM at physical address 0x00000000 and the INTERNAL BOOT FLASH beginning at physical address 0x1FC00000 is matched up with the virtual memory schemes of KSEGO and KSEG1 The PIC32MX CPU maps the virtual areas of KSEGO and KSEG1 against the same physical memory area beginning at physical address 0x00000000 Because both the KSEGO and KSEG1 virtual segments point to the same physical memory area the PIC32MX CPU can execute instructions from either the KSEGO or KSEG1 virtual memory segment depending on the cacheable status of the application KSEGO and USEG KSEG are cacheable while KSEG1 is not cacheable Related topics Accessing individual bits SFRs Memory type specifiers MikroElektronika 170 mikroPascal PRO for PIC32 Memory Type Specifiers The mikroPascal PRO for PIC32 supports usage of all memory areas Each variable may be explicitly assigned to a specific memory space by including a memory type specifier in the declaration or implicitly assigned Th
404. ng transmission software UART is incapable of receiving data data transfer protocol must be set in such a way to prevent loss of information var some byte byte some byte SOA Write a byte via Soft UART Soft UART Write some byte The Software UART library implements time based activities so interrupts need to be disabled when using it MikroElektronika 388 mikroPascal PRO for PIC32 Soft UART Break Prototype procedure Soft UART Break Description Soft UART Read is blocking routine and it can block the program flow Calling Soft UART Break routine from the interrupt will unblock the program execution This mechanism is similar to WDT var datal error counter byte procedure TimeriInt org IVT ADDR TIINTERRUPT begin counter 0 if counter gt 20 then begin Soft UART Break counter 0 reset counter end else Inc counter increment counter TIIF bit 35 07 Clear Timerl overflow interrupt flag end begin if Soft UART IDIb5 PORTE 2 3 14400 0 0 Soft UART Write 0x55 try Soft UART Read with blocking prevention mechanism TECO IPCO or 0x1000 Interrupt priority level 1 TITE pit 2 17 Enable Timerl interrupts TICON 0x8030 Timerl ON internal clock FCY prescaler 2256 datal Soft UART Read amp error TITE bit s 0 Disable Timerl interrupts end The Software UART library implements time based activities
405. nitialized See the TFT Init routine mes TFT Line 0 239 127 535 MikroElektronika mikoPascal PRO for PIC32 TFT_H Line Prototype procedure TFT H Line x start x_end y pos integer Description Draws a horizontal line on TFT Parameters x start x coordinate of the line start x end x coordinate of the line end y pos y coordinate of horizontal line TFT module needs to be initialized See the TFT Init routine Draw a horizontal line between dots 10 20 and 50 20 TET H Line 10 50 20 TFT V Line Prototype procedure TFT V Line y start y end x pos integer Description Draws a vertical line on TFT Parameters y start y coordinate of the line start y end y coordinate of the line end x pos X coordinate of vertical line TFT module needs to be initialized See the TFT Init routine Draw a vertical line between dots 10 5 and 10 25 TFT V Line 5 25 10 TFT Rectangle Prototype procedure TFT Rectangle x upper left y upper left x bottom right y bottom right integer Description Draws a rectangle on TFT Parameters x upper left x coordinate of the upper left rectangle corner y upper left y coordinate of the upper left rectangle corner x bottom right x coordinate of the lower right rectangle corner y bottom right y coordinate of the lower right rectangle corner TFT module needs to be initialized See the TFT Init routine seme i TFT
406. not found a message is displayed Search for Replace Text Dialog box for searching for a text string in file and replacing it with another text string Search for mikroElektronika Replace with mikroE MikroElektronika 40 mikroPascal PRO for PIC32 Find In Files Dialog box for searching for a text string in current file all opened files or in files on a disk The string to search for is specified in the Text to find field If Search in directories option is selected The files to search are specified in the Files mask and Path fields DICIS NNNM oK cancel Go To Line Dialog box that allows the user to specify the line number at which the cursor should be positioned Regular expressions option By checking this box you will be able to advance your search through Regular expressions Search for unsigned x20int o He RI lt Related topics Keyboard shortcuts Edit Toolbar Advanced Edit Toolbar a MikroElektronika mikoPascal PRO for PIC32 View View Menu Options View Menu contains commands for controlling the on screen display of the current project Debug Windows gt Toolbars Bookmarks Code Explorer Library Manager Macro Editor Messages Project Manager Shift Ctrl F11 Project Settings Routine List Ctri L Quick Converter Ctri Q View Image Preview a Assembly Listing Statistics Windo
407. nverts each dot Nothing Requires Glcd needs to be initialized see Glcd Init routine Draw a vertical line between dots 10 5 and 10 25 Glcd V Line 5 25 10 1 None Glcd H Line Prototype procedure Glcd H Line x start x end y pos color byte Description Draws a horizontal line on Glcd Parameters x start x coordinate of the line start Valid values 0 127 x end X coordinate of the line end Valid values 0 127 y pos y coordinate of horizontal line Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the line color 0 white 1 black and 2 inverts each dot Nothing Requires Glcd needs to be initialized see Glcd Init routine Draw a horizontal line between dots 10 20 and 50 20 Glcd H Line 10 50 20 1 None 301 MikroElektronika mikoPascal PRO for PIC32 Glcd_Rectangle Prototype procedure Glcd Rectangle x upper left y upper left x bottom right y bottom right color byte Draws a rectangle on Glcd Parameters x upper left x coordinate of the upper left rectangle corner Valid values 0 127 y upper left y coordinate of the upper left rectangle corner Valid values 0 63 x bottom right x coordinate of the lower right rectangle corner Valid values 0 127 y bottom right y coordinate of the lower right rectangle corner Valid values 0 63 color color parameter Valid values 0 2 The parameter color
408. oPascal PRO for PIC32 Cf_Read_Init procedure Cf Read Init address dword sectcnt byte Initializes CF card for reading Parameters address the first sector to be prepared for reading operation sector count number of sectors to be prepared for reading operation The corresponding MCU ports must be appropriately initialized for CF card See Cf Init initialize compact flash for reading from sector 590 Cf Read Init 590 1 Nos Nm S Cf Read Byte Prototype Description Reads one byte from eror Flash sector buffer location currently pointed to by internal read pointers These pointers will be autoicremented upon reading Returns Returns a byte read from Compact Flash sector buffer Requires The corresponding MCU ports must be appropriately initialized for CF card See Cf Init CF card must be initialized for reading operation See Cf Read Init Read a byte from compact flash var data as byte data 7 Cf Read Byte Notes Higher byte of the unsigned return value is cleared Cf Write Init ene procedure Cf Write Init address dword sectcnt word Initializes CF card for writing Parameters address the first sector to be prepared for writing operation sectcnt number of sectors to be prepared for writing operation The corresponding MCU ports must be appropriately initialized for CF card See Cf Init initialize compact flash for writing to sector 590 Cr Writ
409. oPascal PRO for PIC32 also allows you to use the automatically created local variable result to assign the return value of a function if you find function name to be too ponderous If the return value of a function is not defined the compiler will report an error Function calls are considered to be primary expressions and can be used in situations where expression is expected A function call can also be a self contained statement and in that case the return value is discarded Example Here s a simple function which calculates x based on input parameters x and n n gt 0 function power x n byte longint var i byte begin i 0 result 1 if n gt 0 then for i 1 to n do result result x end 197 MikroElektronika mikoPascal PRO for PIC32 Now we could call it to calculate say 312 tmp power 3 12 Procedures Procedure is declared like this procedure procedure name parameter list local declarations begin procedure body end procedure name represents a procedure s name and can be any valid identifier Within parentheses parameter list is a formal parameter list very similar to variable declaration In Pascal parameters are always passed to a procedure by the value to pass an argument by address add the keyword var ahead of identifier Local declarations are optional declaration of variables and or constants local for the given procedure Procedure body is a sequence
410. ode folding symbols and t appear automatically Use the folding symbols to hide unhide the code subsections PORTA 0 PORTB 0 Led_Init LCD_Out 1 1 txt 0 LCD_Out 2 1 txt 1 delay_ms 1000 Led_Cmd 1 LCD_Out 1 1 txt 1 LCD Out 2 4 txt 2 delay ms 500 end s begin E 51 MikroElektronika mikoPascal PRO for PIC32 Another way of folding unfolding code subsections is by using Alt and Alt If you place a mouse cursor over the tooltip box the collapsed text will be shown in a tooltip style box begin m begin PORTA 0 PORTB 0 Lcd Init LCD Out 1 1 txt 0 LCD Out 2 1 txt 1 delay ms 1000 Lcd Cmd 1 LCD Out i1 1 txt 1 LCD Outi 2 4 txt 2 delay ms 500 Code Assistant If you type the first few letters of a word and then press Ctrl Space all valid identifiers matching the letters you have typed will be prompted in a floating panel see the image below Now you can keep typing to narrow the choice or you can select one from the list using the keyboard arrows and Enter E variable sfr SPrbyte 000000000 variable sfr SPDR byte variable sfr SPSR byte variable sfr SPCR byte Parameter Assistant The Parameter Assistant will be automatically invoked when you open parenthesis or press Shift Ctrl Space If the name of a valid function precedes the parenthesis then the expected parameters will be displayed in a floatin
411. odules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library I2Cx Is Idle 1 if C bus is not free Requires MCU with at least one I C module Used lC module must be initialized before using this function See I2Cx Init routine var data byte if I2CLl Is Idle I2Cl Write data FC library routines require you to specify the module you want to use To select the desired C module simply change the letter x in the routine prototype for a number from 1 to 5 Number of IPC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 310 mikroPascal PRO for PIC32 I2Cx_Read Prototype function I2Cx Read ack word byte Reads a byte from the lC bus Parameters ack acknowledge signal parameter If the ack 0 acknowledge signal will be sent after reading otherwise the not acknowledge signal will be sent Retums Received data Requires MCU with at least one I C module Used I C module must be initialized before using this function See I2Cx Init routine Also START signal needs to be issued in order to use this function See I2Cx Start var take byte Read data and send the not acknowledge signal take I2Cl Read 1 u PC library routines require you to specify the module you want to use To select the desired C module simply change the letter x in the r
412. odules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Library Example The code demonstrates how to use SPI library functions for communication between SPI2 module of the MCU and MCP4921 DAC chip Copy Code To Clipboard program SPI DAC module connections var Chip Select sbit at LATFO bit Chip Select Direction sbit at TRISFO bit End DAC module connections var value word procedure InitMain begin TRISBO bit 1 Set RBO pin as input TRISB1 bit 1 Set RB1 pin as input Chip Select 1 Deselect DAC Chip Select Direction 0 Set CSf pin as Output SPI2 Init Initialize SPI2 module end DAC increments 0 4095 output voltage 0 Vref procedure DAC Output valueDAC word var temp byte begin Chip Select 0 Select DAC chip MikroElektronika A00 mikroPascal PRO for PIC32 Store valueDAC 11 8 to temp 3 0 Define DAC setting see MCP4921 datasheet Send high byte via SPI Store valueDAC 7 0 to temp 7 0 Send low byte via SPI DAC chip Configure AN pins as digital initialization starts DAC gives in the mid range initialization starts DAC gives in the mid range If RAO button is pressed Send High Byte temp word valueDAC shr 8 and 0x0F temp temp or 0x30 Fi SPI2 Write temp Send Low Byte temp valueDAC SPI2 Write te
413. of CANSPI Library 243 Library Routines 244 CANSPISetOperationMode 244 CANSPIGetOperationMode 245 CANSPIInit 245 CANSPISetBaudRate 247 CANSPISetMask 248 CANSPISetFilter 249 CANSPIRead 250 CANSPIWrite 251 CANSPI Constants 251 CANSPI OP MODE Constants 251 CANSPI CONFIG FLAGS Constants 252 CANSPI TX MSG FLAGS Constants 253 CANSPI RX MSG FLAGS Constants 253 CANSPI MASK Constants 254 CANSPI FILTER Constants 254 Library Example 255 HW Connection 258 Compact Flash Library 259 Library Dependency Tree 259 External dependencies of Compact Flash Library 260 Library Routines 261 Cf Init 262 Cf Detect 263 Cf Enable 263 MikroElektronika Ti mikoPascal PRO for PIC32 Cf_Disable 263 Cf Read Init 264 Cf Read Byte 264 Cf Write Init 264 Cf Write Byte 265 Cf Read Sector 265 Cf Write Sector 265 Cf Fat Init 266 Cf Fat QuickFormat 266 Cf Fat Assign 267 Cf Fat Reset 268 Cf Fat Read 268 Cf Fat Rewrite 269 Cf Fat Append 269 Cf Fat Delete 269 Cf Fat Write 270 Cf Fat Set File Date 270 Cf Fat Get File Date 271 Cf Fat Get File Date Modified 271 Cf Fat Get File Size 272 Cf Fat Get Swap File 272 Library Example 274 HW Connection 279 Epson S1D13700 Graphic Lcd Library 280 External dependencies of the Epson S1D13700 Graphic Lcd Library 280 Library Routines 281 S1D13700 Init 282 S1D13700 Write Command 283 S1D13700 Write Parameter 284 S1D13700 Read Parameter 284 S1D13700 Fill 284 S1D13700 GrFill 285 S1D13700 TxtFill 285 S1D13700 Displ
414. oftSpi SDI Direction sbit at TRISD2 bit SoftSpi SDO Direction sbit at TRISD3 bit End DAC module connections 385 MikroElektronika mikoPascal PRO for PIC32 var value word procedure InitMain begin TRISBO bit 1 Set RBO pin as input TRISB1 bit 1 Set RB1 pin as input Chip Select 1 Deselect DAC Chip Select Direction 0 Set CS pin as Output Soft Spi Init Initialize Soft SPI end DAC increments 0 4095 output voltage 0 Vref procedure DAC Output valueDAC word var temp byte volatile begin Chip Select 0 Select DAC chip Send High Byte temp word valueDAC shr 8 and O0x0F Store valueDAC 11 8 to temp 3 0 temp temp or 0x30 Define DAC setting see MCP4921 datasheet Soft SPI Write temp Send high byte via Soft SPI Send Low Byte temp valueDAC Store valueDAC 7 0 to temp 7 0 Soft SPI Write temp Send low byte via Soft SPI Chip Select 1 Deselect DAC chip end begin CHECON 0x32 ADIPCFG OxFFFF Configure AN pins as digital InitMain Perform main initialization value 2048 When program starts DAC gives a4 the output in the mid range while TRUE do Endless loop begin if RBO bit and value 4095 then If RBO button is pressed Inc value increment value else begin if RB1 bit and value gt 0 then If RB1 button is pressed Dec value ra decre
415. old one If only mpas file is found the compiler will create the emc1 file and include it in the project If only emc1 file is present i e no source code is available the compiler will include it as it is found If none found the compiler will issue a File not found warning Main Unit Every project in mikroPascal PRO for PIC32 requires a single main unit file The main unit file is identified by the keyword program at the beginning it instructs the compiler where to start After you have successfully created an empty project with the Project Wizard the Code Editor will display a new main unit It contains the bare bones of the Pascal program program MyProject main procedure begin Place program code here end 191 MikroElektronika mikoPascal PRO for PIC32 Nothing should precede the keyword program except comments After the program name you can optionally place the uses clause Place all global declarations constants variables types labels routines before the keyword begin Other Units Units other than main start with the keyword unit Newly created blank unit contains the bare bones unit MyUnit implementation end Other than comments nothing should precede the keyword unit After the unit name you can optionally place the uses Clause Interface Section Part of the unit above the keyword implementation is referred to as interface section Here you can place global d
416. olding the IP address the requested host name was resolved 0 otherwise Ethernet module has to be initialized See SPI Ethernet Init The Ethernet services are not stopped while this routine waits for DNS reply The incoming packets will be processed normaly during this time User should always copy the IP address from the RAM location returned by this routine into it s own resolved host IP address buffer These locations should not be altered by the user in any case var remoteHostIpAddr array 4 of byte user host IP address buffer SNTP server Zurich Switzerland Integrated Systems Lab Swiss Fed Inst Technology 129 132 2 21 swisstime ethz ch Service Area Switzerland and Europe memcpy remoteHostIpAddr SPI Ethernet _dnsResolve swisstime ethz ch 5 4 417 MikroElektronika mikoPascal PRO for PIC32 SPI_Ethernet_initDHCP Prototype function SPI Ethernet initDHCP tmax byte byte Description This is DHCP module routine It sends an DHCP request for network parameters IP gateway DNS addresses and IP subnet mask and waits for DHCP reply If the requested parameters were obtained successfully their values are stored into the library global variables These parameters can be fetched by using appropriate library IP get routines SPI Ethernet getlpAddress fetch IP address SPI Ethernet getGwlpAddress fetch gateway IP address SPI Ethernet getDns
417. olumn Spi Lcd Chr CP Append Spi Lcd Out 2 1 text Print text to LCD 2nd row lst column Spi Lcd Out 3 1 mikroE For LCD with more than two rows Spi Lcd Out 4 15 mikroE For LCD with more than two rows Delay ms 2000 Moving text for counter begin Spi Lcd Cmd LCD SHIFT RIGHT 0 to 3 do Move Delay end Move text to the right 4 times MikroElektronika 466 mikroPascal PRO for PIC32 while TRUE do Endless loop begin for counter 0 to 6 do Move text to the left 7 times begin Spi Lcd Cmd LCD SHIFT LEFT Move Delay end for counter 0 to 6 do Move text to the right 7 times begin Spi Lcd Cmd LCD SHIFT RIGHT Move Delay end end end gvcc3s DODD OOO OOO OOUR UO OOOO OOOO ij g 8 OSCILLATOR PIC32MX460F512L et woos JUL L zx c Contrast Adjustment TTT t ver F Fri cH 5 vecs i g g d 5K ovCC3 VCC3 Lcd HW connection by default initialization using SPI Lcd Init 467 MikroElektronika mikoPascal PRO for PIC32 SPI Lcd8 8 bit interface Library The mikroPascal PRO for PIC32 provides a library for communication with Lcd with HD44780 compliant controllers in 8 bit mode via SPI interface For creating a custom set of Lcd characters use Lcd Custom Character Tool Important
418. on is declared like this function function name parameter list return type local declarations begin function body end function name represents a function s name and can be any valid identifier return type is a type of return value and can be any simple type or complex type Within parentheses parameter list is a formal parameter list very similar to variable declaration In Pascal parameters are always passed to a function by the value To pass an argument by address add the keyword var ahead of identifier Local declarations are optional declarations of variables and or constants local for the given function Function body is a sequence of statements to be executed upon calling the function Calling a function Afunction is called by its name with actual arguments placed in the same sequence as their matching formal parameters The compiler is able to coerce mismatching arguments to the proper type according to implicit conversion rules Upon a function call all formal parameters are created as local objects initialized by values of actual arguments Upon return from a function a temporary object is created in the place of the call and it is initialized by the value of the function result This means that function call as an operand in complex expression is treated as the function result In standard Pascal a unction name is automatically created local variable that can be used for returning a value of a function mikr
419. onika mikoPascal PRO for PIC32 CHAPTER 1 INTRODUCTION The mikroPascal PRO for PIC32 is a powerful feature rich development tool for PIC32 microcontrollers It is designed to provide the programmer with the easiest possible solution to developing applications for embedded systems without compromising performance or control 8 amp ee amp Jat Me boa Ae Wr ANT r E O S REM WR NY YN v m mae eee ee ee ee oom ADADA omm 9 y PU mnm OEC 2 ya ame m mm hee Mn aw Moi m D sga 7 pi isa sis eu BAN e mara inen 4 Ocom oan ee B o han u m o cio e an P f M t ctn n ee lt LL eS a EI T det Omne iU Omm me f ee vum T hri imt ms t mn mad mta Ft te ege eam n or ist nmt tme M ae mm d deli doe C t v a cer ae P a X a iane 5 int me Ae uan re t oe we c ma LJ oes vn tam ts i eee X as Dm e D af p my e oa m 8 e es N ering n e uate fm dm A d ee ee e nim ba bend a V u c LJ em Tee v mmt enm gt ores 2 to ne of e onae A D 9 O i De E e C n RR LJ M m m mI t ro om gt 00 ne RS CELE TLETT na e gt oe Gime dw eti sU eT adum M i am Ll mikroPascal PRO for PIC32 IDE MikroElektronika 28 mikroPascal PRO
420. ons Project Toolbar Build Toolbar Add Remove Files from Project 59 MikroElektronika mikoPascal PRO for PIC32 Project Settings The following options are available in the Project Settings window Device select the appropriate device from the device drop down list MCU Clock enter the clock frequency value Build Debugger Type choose debugger type Project Settings Elgg Device Name P32MX460F512L 4G MCU Clock Frequency 80 000000 E Build Debugger T Build Type 9 Release ICD Debug Debugger Software O mikroICD Related topics Edit Project Customizing Projects Project Manager MikroElektronika 60 mikroPascal PRO for PIC32 Library Manager Library Manager enables simple handling libraries being used in a project Library Manager window lists all libraries extension emc1 which are instantly stored in the compiler Uses folder The desirable library is added to the project by selecting check box next to the library name In order to have all library functions accessible simply press the button Check All t and all libraries will be selected In case none library is needed in a project press the button Clear AII E and all libraries will be cleared from the project Only the selected libraries will be linked Library Manager ZS WOO mikroE E ADC C BitReverseComplex C Button CO can C can_spr o Conversions C_Type C EEPROM L FFT E Fi
421. or PIC32 PIC32MX Memory Layout The PIC32MX microcontrollers implement two address spaces virtual and physical All hardware resources such as program memory data memory and peripherals are located at their respective physical addresses Peripherals such as DMA and Flash controllers use physical addresses and access memory independently of the CPU Virtual addresses are exclusively used by the CPU to fetch and execute instructions Virtual address space can be thought as CPU s logical view and use of its physical resources A graphical representation of the PIC32MX virtual and physical memory is shown in picture below Virtual Memory Map Physical Memory Map OxFFFFFFFF OxFFFFFFFF NOT USED 0xC0000000 SS OxBF000000 MW BMXDUDBA OxBD000000 Ox4FFFFFFF KSEG2 KSEG3 OxBFC00000 WW UOO Y 0xBF 800000 KWAY 0xBD000000 OxAFFFFFFF SS 4 0x40000000 0xA0000000 Wwinw wi w g d ESSO RESERVED V KSEGO KSEG1 0X80000000 Ox7F000000 Ox1D000000 OxOFFFFFFF Noo SSSSSSSSSSSSSS S PIC32 Memory Map 0x7D000000 BMXPUPBA OxOFFFFFFF BMXDUDBA USEG KUSEG 9 axanananan axnononona 169 MikroElektronika mikoPascal PRO for PIC32 As it can be seem the entire 4 GB virtual address space is divided into two primary regions User and Kernel space The lower 2 GB of space called USEG KUSEG a
422. or PIC32 SPI T6963C config Prototype procedure SPI T6963C config width height fntW word DeviceAddress byte wr rd cd rst byte Description Initializes T6963C Graphic Lcd controller Display RAM organization The library cuts RAM into panels a complete panel is one graphics panel followed by a text panel see schematic below Parameters width width of the Glcd panel height height of the Glcd panel ntW font width DeviceAddress SPI expander hardware address see schematic at the bottom of this page wr write signal pin on Glcd control port rd read signal pin on Glcd control port cd command data signal pin on Glcd control port rst reset signal pin on Glcd control port Returns Nothing Requires Global variables SPExpanderCs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before using this function The SPI module needs to be initialized See the SPIx Init and SPIx Init Advanced routines ATI MikroElektronika mikoPascal PRO for PIC32 Port Expander module connections SPExpanderRST sbit at LATFO bit SPExpanderCS sbit at LATFI1 bit SPExpanderRST Direction sbit at TRISFO bit SPExpanderCS Direction sbit at TRISF1 bit End Port Expander module connections Initialize
423. or PIC32 will generate output files in the project folder folder which contains the project file mpp32 Output files are summarized in the table below Intel HEX Intel style hex records Use this file to program MCU hex Binary Extended mikro Compiled Library Binary distribution of application that can be included in other projects List File Overview of MCU memory allotment instruction 1st addresses registers routines and labels Assembler File Human readable assembly with symbolic names asm extracted from the List File Assembly View After compiling the program in mikroPascal PRO for PIC32 you can click the View Assembly icon al or select Project View Assembly from the drop down menu to review the generated assembly code asm file ina new tab window Assembly is human readable with symbolic names Related topics Build Menu Build Toolbar Messages Window Project Manager Project Settings 613 MikroElektronika mikoPascal PRO for PIC32 Creating New Library mikroPascal PRO for PIC32 allows you to create your own libraries In order to create a library in mikroPascal PRO for PIC32 follow the steps bellow 1 Create a new source file see Managing Source Files 2 Save the file in one of the subfolders of the compiler s Uses folder DriveName Program Files Mikroelektronika mikroPascal PRO for PIC32 Uses 3 Write a code for your library and save it 4 Add Lib Example file in some project see Pro
424. or electronically transmit or receive Software media or documentation You acknowledge that Software in the source code form remains a confidential trade secret of mikroElektronika Associates and therefore you agree not to modify Software or attempt to reverse engineer decompile or disassemble it except and only to the extent that such activity is expressly permitted by applicable law notwithstanding this limitation If you have purchased an upgrade version of Software it constitutes a single product with the mikroElektronika Associates software that you upgraded You may use the upgrade version of Software only in accordance with the License Agreement LIMITED WARRANTY Respectfully excepting the Redistributables which are provided as is without warranty of any kind mikroElektronika Associates warrants that Software once updated and properly used will perform substantially in accordance with the accompanying documentation and Software media will be free from defects in materials and workmanship for a period of ninety 90 days from the date of receipt Any implied warranties on Software are limited to ninety 90 days mikroElektronika Associates and its suppliers entire liability and your exclusive remedy shall be at mikroElektronika Associates option either a return of the price paid or b repair or replacement of Software that does not meet mikroElektronika Associates Limited Warranty and which is returned to mikroElektronika
425. ore using this function The SPI module needs to be initialized See SPIx Init and SPIx Init Advanced routines Port Expander module connections var SPExpanderRST sbit at LATFO bit var SPExpanderCS gt sbit at LATF1 bit var SPExpanderRST Direction sbit at TRISFO bit var SPExpanderCS Direction sbit at TRISF1 bit End Port Expander module connections If Port Expander Library uses SPI1 module SPII Inzt Initialize SPI module used with PortExpander SPI Lcd Config 0 initialize Lcd over SPI interface SPI Lcd Out Prototype procedure SPI Lcd Out row column byte var text string Prints text on the Lcd starting from specified position Both string variables and literals can be passed as a text Parameters row starting position row number column starting position column number text text to be written Lcd needs to be initialized for SPI communication see SPI Lcd Config routine Write text Hello on Lcd starting from row 1 column 3 SPI Led Out l 3 Hellot 463 MikroElektronika mikoPascal PRO for PIC32 SPI Lcd Out Cp diana procedure SPI Lcd Out CP var text string write text at current pos Prints text on the Lcd at current cursor position Both string variables and literals can be passed as a text text text to be written Lcd needs to be initialized for SPI communication see SPI Lcd Config routine Write text Here at current cursor positio
426. ort byte at PORTB var keypadPort Direction byte at TRISB End of keypad module connections Keypad Init Notes The Keypad library uses lower byte bits lt 7 0 gt of keypadPort MikroElektronika 314 mikroPascal PRO for PIC32 Keypad Key Press Reads the key from keypad when key gets pressed The code of a pressed key 1 16 If no key is pressed returns 0 Port needs to be initialized for working with the Keypad library see Keypad Init Keypad Key Click Description Call to Keypad Key Click is a blocking call the function waits until some key is pressed and released When released the function returns 1 to 16 depending on the key If more than one key is pressed simultaneously the function will wait until all pressed keys are released After that the function will return the code of the first pressed key Parameters None The code of a clicked key 1 16 If no key is clicked returns O Port needs to be initialized for working with the Keypad library see Keypad Init kp Keypad Key Click 319 MikroElektronika mikoPascal PRO for PIC32 Library Example The following code can be used for testing the keypad It is written for keypad 4x3 or 4x4 The code returned by the keypad functions 1 16 is transformed into ASCII codes 0 9 A F and then sent via UART1 Copy Code To Clipboard program Keypad Test var kp oldstate byte txt array 6 of char Key
427. ortant When using this library with PIC32 family MCUs be aware of their voltage incompatibility with certain number of Samsung KS0108 based Glcd modules So additional external power supply for these modules may be required Library uses the SPI module for communication The user must initialize the appropriate SPI module before using the SPI Glcd Library For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by using the SPI Set Active routine See the SPI Library functions This Library is designed to work with the mikroElektronika s Serial Lcd Glcd Adapter Board pinout see schematic at the bottom of this page for details Library Dependency Tree gt Port Expander SPI Graphic Lcd 1 i Gicd Fonts External dependencies of SPI Lcd Library The implementation of SPI Lcd Library routines is based on Port Expander Library routines External dependencies are the same as Port Expander Library external dependencies Library Routines Basic routines SPI Glcd Init SPI Glcd Set Side SPI Glcd Set Page SPI Glcd Set X SPI Glcd Read Data SPI Glcd Write Data Advanced routines SPI Glcd Fill SPI Glcd Dot SPI Glcd Line SPI Glcd V Line SPI Glcd H Line MikroElektronika 446 mikroPascal PRO for PIC32 SPI_Glcd_Rectangle SPI Gled Rectangle Round Edges SPI Gled Rectangle Round Edges Fill SPI Glcd Box SPI Glced Circl
428. ot Nothing Requires Glcd needs to be initialized see Glcd Init routine Draw a box between dots 5 15 and 20 40 Glod Box 5 15 20 40 1 None 303 MikroElektronika mikoPascal PRO for PIC32 Glcd Circle Prototype procedure Gled Circle x center y center radius integer color byte Description Draws a circle on Glcd Parameters x center x coordinate of the circle center Valid values 0 127 y center y coordinate of the circle center Valid values 0 63 radius radius size color color parameter Valid values 0 2 The parameter co1or determines the color of the circle line O white 1 black and 2 inverts each dot Glcd needs to be initialized see Glcd Init routine Draw a circle with center in 50 50 and radius 10 Glod Crrcle 50 50 10 1 7 Glcd Circle Fill Prototype procedure Glcd Circle ESPERE center integer y center integer radius integer color byte Draws a filled circle on Glcd Parameters x center x coordinate of the circle center Valid values 0 127 y center y coordinate of the circle center Valid values 0 63 radius radius size color color parameter Valid values 0 2 Glcd needs to be initialized see Glcd Init routine Draws a filled circle with center in 50 50 and radius 10 Gled Circle Fill 50 90 10 1 MikroElektronika 304 mikroPascal PRO for PIC32 Glcd Set Font Prototype procedure Glcd Set
429. ototype procedure Glcd Write Char character x pos page num color byte Description Prints character on the Glcd Parameters character character to be written x pos character starting position on x axis Valid values 0 127 FontWidth page num the number of the page on which character will be written Valid values 0 7 color color parameter Valid values 0 2 The parameter color determines the color of the character 0 white 1 black and 2 inverts each dot Nothing Requires Glcd needs to be initialized see Glcd Init routine Use Glcd Set Fontto specify the font for display if no font is specified then default Font Gicd System5x7 font supplied with the library will be used Write character C on the position 10 inside the page 2 Gled Write Chan Cy 10 2 l1 For x axis and page layout explanation see schematic at the bottom of this page Glcd Write Text Prototype procedure Gled Write Text var text string x pos page num color byte Description Prints text on Glcd Parameters text text to be written x pos text starting position on x axis page num the number of the page on which text will be written Valid values 0 7 color color parameter Valid values 0 2 The parameter color determines the color of the text 0 white 1 black and 2 inverts each dot Nothing Requires Glcd needs to be initialized see Glcd Init routine Use Glcd Set Fontto specify the font for display
430. ould be properly cofigured by the means of SPI Ethernet Init routine 407 MikroElektronika mikoPascal PRO for PIC32 SPI Ethernet Disable Prototype procedure SPI Ethernet Disable disFlt byte Description This is MAC module routine This routine disables appropriate network traffic on the ENC28J60 module by the means of it s receive filters unicast multicast broadcast crc Specific type of network traffic will be disabled if a corresponding bit of this routine s input parameter is set Therefore more than one type of network traffic can be disabled at the same time For this purpose predefined library constants see the table below can be ORed to form appropriate input value Parameters disFlt network traffic receive filter flags Each bit corresponds to the appropriate network traffic receive filter MAC Broadcast traffic receive filter flag When set SPI Ethernet MAC broadcast traffic will be disabled BROADCAST i et MAC Multicast traffic receive filter flag When set MAC SPI Ethern multicast traffic will be disabled MULTICAST not used none CRC check flag When set CRC check will be disabled zo and packets with invalid CRC field will be accepted d uid eMe E O oljoljo ea D XxXxX X X HOO o e ojoj N H i X i e mtd nome MAC Unicast traffic receive filter flag When set MAC SPI Ethernet unicast traffic will be disabled UNICAST not used none X Co e
431. outine prototype for a number from 1 to 5 Number of IC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library I2Cx Write Prototype function I2Cx Write data byte word Sends data byte via the IC bus data data to be sent 0 if there were no errors 1 if write collision was detected on the l C bus Requires MCU with at least one lC module Used I C module must be initialized before using this function See I2Cx Init routine Also START signal needs to be issued in order to use this function See I2Cx Start var data byte error word error 12Cl Write data error I2Cl Write 0xA3 module simply change the letter x in the routine prototype for a number from 1 to 5 Number of IC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library u PC library routines require you to specify the module you want to use To select the desired C 311 MikroElektronika mikoPascal PRO for PIC32 I2Cx_Stop Rets Noting Requires MCU with at least one I C module Used I C module must be initialized before using this function See I2Cx Init routine Issue STOP signal I2Cl Stop C library routines require you to specify the module you want to use To select the desired C module simply change the letter x in the routine prototype for a number from 1 to 5 Number of
432. owing manner data buffer 0 2 message content data buffer 3 number of message bytes received 1 3 data buffer 4 is set to 255 when message is received data buffer 5 is setto 255 if error has occurred The routine automatically adjusts data 4 and data 5 upon every received message These flags need to be cleared by software MCU must be initialized as a Slave for RS 485 communication See RS485Slave Init var msg array 8 of byte RS485Slave _Read msg RS485Slave_Send Prototype procedure RS485Slave Send var data array 20 of byte datalen byte Sends message to Master Message format can be found at the bottom of this page Parameters data _ buffer data to be sent datalen number of bytes for transmition Valid values 0 3 Nothing Requires MCU must be initialized as a Slave for RS 485 communication See RS485Slave_Init It is the user s responsibility to ensure by protocol that only one device sends data via 485 bus at a time var msg array 8 of byte send 2 bytes of data to the Master RS485Slave Send msg 2 371 MikroElektronika mikoPascal PRO for PIC32 Library Example The example demonstrates working with the PIC32 as a Master node in RS 485 communication Master sends message to Slave with address 160 and waits for a response After the response is received the first byte of received data is incremented and sent back to the Slave The received data is displayed on
433. p of MCU s RAM with recently changed items colored red The user can edit and change the values in the RAM window mikrolCD Specific RAM window content will be written to the MCU before the next instruction execution Lcd4bit mikroE ikroElektronikz EasydsPIC4 lt Stopwatch Window The Software Simulator Stopwatch Window is available from the drop down menu View Debug Windows Stopwatch The Stopwatch Window displays a Current Count of cycles time since the last Software Simulator action Stopwatch measures the execution time number of cycles from the moment Software Simulator has started and can be reset at any time Delta represents the number of cycles between the lines where Software Simulator action has started and ended Watch Clock Cycles Time Current Count 2 103 943 273 105 205 Delta 80 881 413 4044 07 ms Stopwatch 2 103 943 273 105197 16 ms Reset To Zero sClock MikroElektronika 122 mikroPascal PRO for PIC32 Notes The user can change the clock in the Stopwatch Window which will recalculate values for the latest specified frequency Changing the clock in the Stopwatch Window does not affect actual project settings it only provides a simulation Stopwatch is available only when Software Simulator is selected as a debugger EEPROM Watch Window Note EEPROM Watch Window is available only when mikrolCD is selected as a debugger To show
434. pad module connections var keypadPort dword at PORTD var keypadPort Direction dword at TRISD End Keypad module connections begin oldstate 0 ADIPCFG OxFFFF CHECON 0x32 UART1 Init 19200 Initialize UART module at 9600 bps Delay ms 10 Keypad Init Initialize Keypad UART1 Write Text Press any key on your keypad UART1 Write 10 UART1 Write 13 while TRUE do begin kp 0 Reset key code variable Wait for key to be pressed and released while kp 0 do kp Keypad Key Click Store key code in kp variable LATB kp Prepare value for output transform key to it s ASCII value case kp of case 10 kp 42 fe t Uncomment this block for keypad4x3 case 11 kp 48 pg case 12 kp 35 ME default kp 48 1 kp 49 1 Uncomment this block for keypad4x4 2t kp s 50 S72 3 kp s 51 3 4s kp i265 f A 5i kp i 52 4 6r kp os 537 77 5 7 kp 54 6 8s kp 2 667 B 9 kp 55 7 10 kp 56 7 8 Lis kp i 57 Z8 12 kp 67 C MikroElektronika 316 mikroPascal PRO for PIC32 l3 kp i 42 WU l kp s 48 7 0 I5 kp 353 Za 16 kp 68 D end UART1 Write Text Key pressed UART1 Write kp Send value of pressed button to UART UART1 Write 10 UART1 Write 13 end end HW Connection OSCILLATOR 4x4 Keypad connection scheme
435. pboard init CANSPI CONFIG SAMPLE THRICE and CANSPI CONFIG PHSEG2 PRG ON and CANSPI CONFIG STD MSG and CANSPI CONFIG DBL BUFFER ON and CANSPI CONFIG VALID XTD MSG and CANSPI CONFIG LINE FILTER OFF CANSPLingt 1 1 3 9 l imito initialize CANSPI CANSPI TX MSG FLAGS Constants CANSPI TX MSG FLAGS are flags related to transmission of a CANSPI message Copy Code To Clipboard const CANSPI TX PRIORITY BITS byte 03 CANSPI TX PRIORITY O0 byte SFC XXXXXX00 CANSPI TX PRIORITY 1 byte FD XXXXXX01 CANSPI TX PRIORITY 2 byte SFE XXXXXX10 CANSPI TX PRIORITY 3 byte SEF XXXXXX11 CANSPI TX FRAME BIT byte 08 CANSPI TX STD FRAME byte SFF XXXXX1XX CANSPI TX XTD FRAME byte SET XXXXX0XX CANSPI TX RTR BIT byte 40 CANSPI TX NO RTR FRAME byte SFF X1XXXXXX CANSPI TX RTR FRAME byte SBF XOXXXXXX You may use bitwise AND and to adjust the appropriate flags For example Copy Code To Clipboard form value to be used as sending message flag send config CANSPI TX PRIORITY 0 and CANSPI TX XTD FRAME and CANSPI TX NO RTR FRAME CANSPIWrite id data 1 send config CANSPI RX MSG FLAGS Constants CANSPI RX MSG FLAGS are flags related to reception of CANSPI message If a particular bit is set then corresponding meaning is TRUE or else it will be FALSE 291 Mi
436. pe for each variable is mandatory Syntax for variable declaration is var identifier list type Here identifier list is a comma delimited list of valid identifiers and type can be any data type For more details refer to Types and Types Conversions For more information on variables scope refer to the chapter Scope and Visibility Pascal allows shortened syntax with only one keyword var followed by multiple variable declarations For example var i j k byte counter temp word samples array 100 of word External Modifier Use the external modifier to indicate that the actual place and initial value of the variable function or procedure body is defined in a separate source code unit For example lets create a project which will calculate circle area and will have function and procedure definition in two different units and a call to these routines in the third separate unit So the project will be consisted of the main unit Main Unit mpas and First Unit mpas and Second Unit mpas Uuhits In the Main Unit we will define routine called r squared calculates radius squared Also both units must be included in the Main Unit program Main Unit uses First Unit Second Unit Include both used units function r squared r real real Definition of the r squared routine begin result r r end begin CircleArea CircleArea routine call end 193 MikroElektronika mikoPascal PRO for PIC32
437. per tolower isalnum Prototype function isalnum character byte word Function returns OxFF if the character is alohanumeric A Z a z 0 9 otherwise returns zero i 26alnum oe y returns OxFF isalnum r returns 0 569 MikroElektronika mikoPascal PRO for PIC32 isalpha Prototype function isalpha character byte word Function returns OxFF if the character is alphabetic A Z a z otherwise returns zero res isalpha A returns OxFF res t amp salpha 1 returns 0 iscntrl Prototype function iscntrl character byte word Description Function returns OxFF if the character is a control or delete character decimal 0 31 and 127 otherwise returns zero res iscntrl r returns OxFF res isontkrl o returns 0 isdigit Prototype function isdigit character byte word Function returns OxFF if the character is a digit 0 9 otherwise returns zero E isdigit o returns OxFF isdigit 1 7 returns 0 isgraph ITE Description Function returns OxFF if the character is a printable excluding the space decimal 32 otherwise returns zero res isgraph o returns OxFF res isgraph returns 0 islower Prototype function islower character byte word Function returns OxFF if the character is a lowercase letter a z otherwise returns zero gt islower 0 returns OxFF is
438. per left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner round radius radius of the rounded edge pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C rectangle round edges 20 20 219 107 12 SPI T6963C WHITE SPI T6963C rectangle round edges fill Prototype d SPI 769630 rectangle round edges_fill x0 inene y0 integer integer integer radius integer pcolor byte Draws a filled unde edge rectangle on Glcd Parameters x0 x coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner round radius radius of the rounded edge BOSE color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C rectangle round edges fi11 20 20 219 3107 12 SPI T69563C WHITE 483 MikroElektronika mikoPascal PRO for PIC32 SPI_T6963C_box Prototype procedure SPI T6963C box x0 y0 xl yl integer pcolor byte Draws a box on the Glcd Parameters x0 x coordinate of the upper left box corner y0 y coordinate of
439. perators Unary Operators Unary Arithmetic Operator Unary Bitwise Operator Address and Indirection Operator Sizeof Operator Sizeof Applied to Expression Sizeof Applied to Type Expressions Expression Evaluation General Rule Left side exception Conditional expressions Explicit Typecasting Statements Assignment Statements Compound Statements Blocks Conditional Statements If Statement Nested if statements Case Statement Nested Case statement Iteration Statements For Statement Endless Loop While Statement Repeat Statement Jump Statements asm Statement Accessing variables Asm code and SSA optimization With Statement Directives Compiler Directives Directives DEFINE and UNDEFINE Directives IFDEF IFNDEF ELSE and ENDIF 218 219 219 219 220 220 220 221 221 221 221 221 222 222 222 223 223 223 223 224 224 224 225 225 225 226 226 227 227 228 228 228 229 229 230 230 230 231 232 232 232 233 233 MikroElektronika 10 mikroPascal PRO for PIC32 Include Directive I 234 Linker Directives 234 Directive absolute 234 Directive org 235 Directive orgall 235 CHAPTER 9 236 mikroPascal PRO for PIC32 Libraries 236 Hardware Libraries 237 Miscellaneous Libraries Zor Hardware Libraries 238 ADC Library 239 Library Routines 239 ADC1_Init 239 ADC1_Init_Advanced 240 ADC1_Get_Sample 240 ADC1 Read 241 Library Example 242 CANSPI Library 243 Library Dependency Tree 243 External dependencies
440. pin mapping var adc value word ada pain ADC1 Get Sample 10 read analog value from ADC module channel 10 MikroElektronika 238 mikroPascal PRO for PIC32 ADC1 Read enone function ADC1 Read channel word word The function initializes enables ADC module and reads the specified analog channel input channel represents the channel from which the analog value is to be acquired Retums 10 bit unsigned value from the specified channel Requires The MCU with built in ADC module Before using the function be sure to configure the appropriate TRISx bits to designate pins as inputs var adc value word adc value ADC1 Read 10 read analog value from ADC module channel 10 The function sets the appropriate bit in the ADPCFG registers to enable analog function of the chosen pin Refer to the appropriate Datasheet for channel to pin mapping ul This is a standalone routine so there is no need for a previous initialization of ADC module 239 MikroElektronika mikoPascal PRO for PIC32 Library Example This code snippet reads analog value from the channel 1 and sends readings as a text over UART1 Copy Code To Clipboard program Temperature Sensor LCD module connections var LCD RS sbit at LATB2 bit var LCD EN sbit at LATB3 bit var LCD D4 sbit at LATB4 bit var LCD D5 sbit at LATB5 bit var LCD D6 sbit at LATB6 bit var LCD D7 sbit at LATB7 bit var LCD RS Direc
441. play dimension Glcd module needs to be initialized See the S1D13700 Init routine Example 81013700 meses T 291 MikroElektronika mikoPascal PRO for PIC32 S1D13700 Partiallmage Prototype procedure 1D13700 Partiallmage x left y top width height picture width picture height word const image byte Nothing Description Displays a partial area of the image on a desired location Parameters x left x coordinate of the desired location upper left coordinate y top y coordinate of the desired location upper left coordinate width desired image width height desired image height picture width width of the original image picture height height of the original image image image to be displayed Bitmap array is located in code memory Note Image dimension must match the display dimension Glcd module needs to be initialized See the S1D13700 Init routine Draws a 10x15 part of the image starting from the upper left corner on the coordinate 10 12 Original image size is 16x32 SIDI3700 PartialImage 10 12 10 15 16 32 image Flash Memory Library This library provides routines for accessing microcontroller s internal Flash memory The program Flash array for the PIC32MX device is built up of a series of rows A row contains 128 32 bit instruction words or 512 bytes A group of 8 rows compose a page which therefore contains 8 1512 4096 bytes or 1024 instruction
442. plicing MikroElektronika 182 mikroPascal PRO for PIC32 Keywords Keywords are words reserved for special purposes and must not be used as normal identifier names Beside standard Pascal keywords all relevant SFRs are defined as global variables and represent reserved words that cannot be redefined for example WO TMR1 T1CON etc Probe the Code Assistant for specific letters Ctrl Space in Editor or refer to Predefined Globals and Constants Here is the alphabetical listing of keywords in mikroPascal PRO for PIC32 absolute abstract and array ds asm assembler at automated bdata begin brit case cdecl Glass code compact const constructor contains data default deprecated destructor dispid dispinterface div dma do downto dynamic end except export exports external far file final finalization finally POL forward goto helper idata if ilevel implementation implements in index inherited initialization inline interface io 1S label library message mod name near nil nodefault not object of on operator or org out overload override package packed pascal pdata platform private procedure program property protected public published raise read readonly record register reintroduce repeat requires rx safecall SHIL sealed set sfr shi shr
443. pointed to by ptrl is greater to the value pointed to by ptr2 end Note Comparing pointers pointing to different objects arrays can be performed at programmer s own responsibility a precise overview of data s physical storage is required Pointer Addition You can use Inc to add an integral value to a pointer The result of addition is defined only if the pointer points to an element of an array and if the result is a pointer pointing to the same array or one element beyond it If a pointer is declared to point to type adding an integral value n to the pointer increments the pointer value by n sizeof type as long as the pointer remains within the legal range first element to one beyond the last element If type has a size of 10 bytes then adding 5 to a pointer to type advances the pointer 50 bytes in memory For example var a array 10 of byte array a containing 10 elements of type byte ptr s byte pointer to byte begin ptr Ga 0 ptr is pointer to byte pointing to a 0 ptr ptr 3 ptr 3 is a pointer pointing to a 3 pir r G a 3 now equals 6 Inc ptr ptr now points to the next element of array a a 4 end Also you may sum values pointed to by pointers For example var i j x byte variables ptrl byte pointers to byte ptr2 byte begin i 10 assign value 10 to variable i is at the address 0x0038 MikroElektronika 208 mikroPascal PRO for PIC32
444. pply users with routines necessary for sound signalization in their applications Sound generation needs additional hardware such as piezo speaker example of piezo speaker interface is given on the schematic at the bottom of this page Library Routines Sound Init Sound Play Sound Init diss procedure Sound Init var snd port snd pin word Configures the appropriate MCU pin for sound generation Parameters snd port sound output port address snd pin sound output pin Initialize the pin RD3 for playing sound Sound Init PORTD 3 Sound Play dick procedure Sound Play freq in hz duration ms word Generates the square wave signal on the appropriate pin Parameters freq in hz signal frequency in Hertz Hz duration ms signal duration in miliseconds ms Requires In order to hear the sound you need a piezo speaker or other hardware on designated port Also you must call Sound Init to prepare hardware for output before using this function Play sound of 1KHz in duration of 100ms Sound Play 1000 100 391 MikroElektronika mikoPascal PRO for PIC32 Library Example The example is a simple demonstration of how to use the Sound Library for playing tones on a piezo speaker Copy Code To Clipboard program Sound procedure begin Sound_ end procedure begin Sound_ end procedure begin Sound_ end Tonel Play 659 Tone2 Play 698 Tone3
445. predefined name and size on the MMC SD media If a file with specified name already exists on the media search for consecutive sectors will ignore sectors occupied by this file Therefore it is recommended to erase such file if it already exists before calling this function If it is not erased and there is still enough space for a new swap file this function will delete it after allocating new memory space for a new swap file The purpose of the swap file is to make reading and writing to MMC SD media as fast as possible by using the Mmc Read Sector and Mmc Write Sector functions directly without potentially damaging the FAT system The swap file can be considered as a window on the media where the user can freely write read data It s main purpose in this library is to be used for fast data acquisition when the time critical acquisition has finished the data can be re written into a normal file and formatted in the most suitable way sectors cnt number of consecutive sectors that user wants the swap file to have filename name ofthe file that should be assigned for file operations File name should be in DOS 8 3 flle name extension format The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does no have to take care of that The file name and extension are case insensitive The library will convert th
446. pson S1D13700 controller The S1D13700 Glcd is capable of displaying both text and graphics on an LCD panel The S1D13700 Glcd allows layered text and graphics scrolling of the display in any direction and partitioning of the display into multiple screens It includes 32K bytes of embedded SRAM display memory which is used to store text character codes and bit mapped graphics The S1D13700 Glcd handles display controller functions including Transferring data from the controlling microprocessor to the buffer memory Reading memory data converting data to display pixels Generating timing signals for the LCD panel The S1D13700 Glcd is designed with an internal character generator which supports 160 5x7 pixel characters in internal mask ROM CGROM and 64 8x8 pixel characters incharacter generator RAM CGRAM When the CGROM is not used up to 256 8x16 pixel characters are supported in CGRAM External dependencies of the Epson S1D13700 Graphic Lcd Library byte fr iod iuri System data bus var S1D13700 DATA at PORTD sbit sfr var S1D13700 WR sbit at Write signal piti sbit sfr var S1D13700 RD Read signal but sbit sfr a var 5S1D13700 A0 System Address pin i buts sbit sfr var S1D13700 RES Reset signal bit sbit sfr var S 1D13700 CS sbit at LATC4 Chip select i bit Direction of the system data bus var S1D13700 DATA Direction sbit at pins PORTD 1D13700 WR Direction D13700 WR Direction
447. quest is made so license requested from one computer won t work on another computer You can find on our site manual and video describing in detail how to get your license If you previously had an older version of our compiler and have working license key for it but it doesn t work with new compiler you have to repeat registration procedure from the new compiler and you will get a new license 615 MikroElektronika mikoPascal PRO for PIC32 have bought license for the older version do have to pay license for the new version of the compiler No once you pay for the license key you get a lifetime license When we release a new major release of the compiler you might need to repeat registration procedure from your new compiler and you will get new license free of charge Do your compilers work on Windows Vista Windows 7 Yes What does this function procedure routine do Please see your compiler s Help where all of the functions are explained in detail try to compile one of the provided examples and nothing happens what is the problem You need to open project not file When you want to open an example go to Project Open Project then browse through projects and choose project file Now you will be able to compile and program with success Can get your library sources need to provide all sources with my project It is our company s policy not to share our source code Can use code developed i
448. r t2 time and date structure the second comparison parameter Parameters None Returns Time difference in seconds as a signed long var tsl ts2 TimeStruct diff 2 longint how many seconds between these two dates contained in tsl and ts2 buffers diff Time dateDiff tsl ts2 Library Example Demonstration of Time library routines usage for time calculations in UNIX time format Copy Code To Clipboard program Time Demo i simple time structure d type TimeStruct record ss t byte seconds mn byte minutes MikroElektronika 594 mikroPascal PRO for PIC32 hh byte hours md byte day in month from 1 to 31 wd byte day in week monday 0 tuesday 1 sunday 6 mo byte month number from 1 to 12 and not from 0 to 11 as with unix C time yY word year Y2K compliant from 1892 to 2038 end var tsl ts2 TimeStruct buf array 256 of byte epoch diff longint begin tsl ss 0 tsl mn i 7 tsl hh 9 17 tsl md 23 tsl mo 5 3 tsl yy 2006 i what is the epoch of the date in ts epoch Time dateToEpoch Gtsl epoch 1148404020 what date is epoch 1234567890 j epoch 1234567890 Time epochToDate epoch ts2 If ts2vss 2 30 ts2 mn 31 ts2 hh s 23 3 ff tsE md 13 ts2 wd 4 ts2 mo 2 ff ts2 yy 2 2009 p how much seconds between this two dates
449. r 1 168 dnsIpAddr 2 20 dnsIpAddr 3 1 set subnet mask ipMask 0 255 ipMask 1 255 ipMask 2 z 255 ipMask 3 0 starts ENC28J60 with reset bit on PORTC BO CS bit on PORTC BI my MAC amp IP address full duplex SPI2 Init Advanced SPI MASTER SPI 8 BIT 16 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE LOW SPI IDLE 2 ACTIVE SPI Ethernet Init myMacAddr mylpAddr SPI Ethernet FULLDUPLEX ff init ethernet module SPI Ethernet setUserHandlers 8SPI Ethernet UserTCP SPI Ethernet UserUDP set user handlers dhcp will not be used here so use preconfigured addresses SPI Ethernet confNetwork ipMask gwIpAddr dnsIpAddr while true do do forever begin SPI Ethernet doPacket process incoming Ethernet packets add your stuff here if needed SPI Ethernet doPacket must be called as often as possible otherwise packets could be lost j end end MikroElektronika 426 mikroPascal PRO for PIC32 HW Connection 421 MikroElektronika mikoPascal PRO for PIC32 SPI Ethernet ENC24J600 Library The ENC24J600 is a stand alone Ethernet controller with an industry standard Serial Peripheral Interface SPI It is designed to serve as an Ethernet network interface for any controller equipped with SPI The ENC24J600 meets all of the IEEE 802 3 specifications applicable to 10Base T and 100Base TX Ethernet It i
450. r PIC32 Expander Init Advanced Prototype procedure Expander Init Advanced var rstPort byte rstPin byte haen byte Initializes Port Expander using SPI communication Parameters rst Port Port Expander s reset port rst Pin Port Expander s reset pin haen Port Expander s hardware address Requires SPExpanderCs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before using this function SPI module needs to be initialized See SPIx Init and SPIx Init Advanced routines Port Expander module connections sbit SPExpanderRST at RFO bit sbit SPExpanderCS at RF1 bit sbit SPExpanderRST Direction at TRISFO bit sbit SPExpanderCS Direction at TRISF1 bit End Port Expander module connections If Port Expander Library uses SPI module SPIL Init Initialize SPI1 module used with PortExpander Expander Init Advanced amp PORTB 0 0 Initialize Port Expander 349 MikroElektronika mikoPascal PRO for PIC32 Expander_Read_Byte Prototype function Expander Read Byte ModuleAddress RegAddress byte byte The function reads byte from Port Expander Parameters ModulecAddress Port Expander hardware address see schematic at the bottom of this page RegAddress Port Expander s internal register address Port Expander must be initialized
451. r PIC32 recycles local variable memory space local variables declared in different functions and procedures share the same memory space if possible There is no need to declare SFRs explicitly as mikroPascal PRO for PIC32 automatically declares relevant registers as global variables of volatile word see SFR for details MikroElektronika 194 mikroPascal PRO for PIC32 Constants Constant is a data whose value cannot be changed during the runtime Using a constant in a program consumes no RAM memory Constants can be used in any expression but cannot be assigned a new value Constants are declared in the declaration part of a program or routine You can declare any number of constants after the keyword const const constant name type value Every constant is declared under unique constant name which must be a valid identifier It is a tradition to write constant names in uppercase Constant requires you to specify value which is a literal appropriate for the given type type is optional and in the absence of t ype the compiler assumes the smallest of all types that can accommodate value Note You cannot omit t ype when declaring a constant array Pascal allows shorthand syntax with only one keyword const followed by multiple constant declarations Here s an example const MAX longint 10000 MIN 1000 compiler will assume word type SWITCH n compiler will assume char type MSG Hello compiler
452. r blink 1 Library Example The following drawing demo tests advanced routines of the T6963C Glcd library Hardware configurations in this example are made for the LV 32MX v6 board and PIC32MX460F512L Copy Code To Clipboard program T6963C 240x128 uses Lib T6963C Consts T6963C module connections var T6963C dataPort byte at PORTD DATA port var T6963C cntlPort byte at PORTE DATA port var T6963C ctrlwr sbit at LATE2 bit WR write signal var T6963C ctrlrd sbit at LATE1 bit RD read signal var T6963C ctrlcd sbit at LATEO bit CD command data signal var T6963C ctrlrst sbit at LATE4 bit RST reset signal var T6963C ctrlwr Direction sbit at TRISE2 bit WR write signal direction var T6963C ctrlrd Direction sbit at TRISE1 bit RD read signal direction var T6963C ctrlcd Direction sbit at TRISEO bit CD command data signal direction var T6963C ctrlrst Direction sbit at TRISE4 bit RST reset signal direction Signals not used by library they are set in main function var T6963C ctrlce sbit at LATE3 bit CE signal var T6963C ctrlfs sbit at LATE6 bit FS signal var T6963C ctrlmd sbit at LATE5 bit MD signal var T6963C ctrlce Direction sbit at TRISE3 bit CE signal direction var T6963C ctrlfs Direction sbit at TRISE6 bit FS signal direction var T6963C ctrlmd Direction sbit at TRISES bit
453. r of 512 bytes in length Nothing Requires The corresponding MCU ports must be appropriately initialized for CF card See Cf Init write to sector 22 var data array 512 of byte Cf Write Sector 22 data 263 MikroElektronika mikoPascal PRO for PIC32 Cf Fat Init Prototype Initializes CF card reads CF FAT16 boot sector and extracts necessary data needed by the library 0 if CF card was detected and successfully initialized 1 if FAT16 boot sector was not found 255 if card was not detected init the FAT library if Cf Fat Init 0 then Cf Fat QuickFormat Prototype function Cf Fat QuickFormat var cf fat label string 11 word Formats to FAT 16 and initializes CF card Parameters cf fat label volume label 11 characters in length If less than 11 characters are provided the label will be padded with spaces If null string is passed the volume will not be labeled 0 if CF card was detected successfully formated and initialized 1 if FAT16 format was unsuccessful 255 if card was not detected format and initialize the FAT library if Cf Fat_QuickFormat mikroE 0 then begin end This routine can be used instead or in conjunction with Cf Fat Init routine If CF card already contains a valid boot sector it will remain unchanged except volume label field and only FAT and ROOT tables will be erased Also the new volume label will be set
454. rRadix E FlasH CO Glcd L Gled Fonts L rc C tirRadix C Keypad4x4 Lcd Lcd Constants Manchester C Matrices Mme Mmc FAT16 C One Wire C Port Expander PS2 a PwM len Deseription S E Refresh Library by scanning files in Uses folder Useful when new libraries are added by copying files to EI E E E a 6 8 EH EE EH m E ED E E E E ED ED Uses folder EJ ETTITT NN 61 MikroElektronika mikoPascal PRO for PIC32 Managing libraries using Package Manager The Package Manager is a tool which enables users to easily install their own libraries in the mikroIDE Libraries are distributed in the form of a package which is an archive composed of one or more files containing libraries For more information on Package Manager visit our website Upon package installation a new node with the package name will be created in the Library Manager For example C sPI Ethernet O sPr Glcd O sPL Lcd CO spt_teds E spt_tese3c O sprint E Sprinti C sprintl v res63c E Time C TeuchPanel amp V Trigonometry w rwr O uaRT f Conversions EI E E0 E E E EH ED il ByteToBinaryStr WordToBinaryStr LongWordToBinaryStr BinaryToGray GrayToBinary ivi From the Library Manager the user can also uninstall the desired package by right clicking the the appropriate node and from the drop down menu choose Uninstall package
455. raction byte short word integer byte short word integer longint dword real longint dword real multiplication byte short word integer word integer longint longint dword real dword real division floating point byte short word integer real longint dword real modulus returnsthe remainder hort word integer byte short word of integer division cannot be Longint dword integer longint dword used with floating points division rounds down to byte short word integer byte short word nearest integer longint dword integer longint dword Division by Zero If O zero is used explicitly as the second operand i e x div 0 the compiler will report an error and will not generate code But in case of implicit division by zero x div y where y is O zero the result will be the maximum integer i e 255 if the result is byte type 65536 if the result is word type etc 215 MikroElektronika mikoPascal PRO for PIC32 Unary Arithmetic Operators Operator can be used as a prefix unary operator to change sign of a signed value Unary prefix operator can be used but it doesn t affect data For example b t Relational Operators Use relational operators to test equality or inequality of expressions All relational operators return TRUE or FALSE All relational operators associate from left to right Relational Operators Overview foa CS Rela
456. ram asm example var myvar word absolute 0x2678 const msg Hello org 0x3678 var myvarl dword procedure proc org 0x1234 begin asm nop end end begin myvar 5 myvarl OxABCD1234 asm MOV myvar w0 move myvar to WO nop MOV 6 WO move literal 6 to WO MOV WO _myvar move contents of WO to myvar MOV flo addr myvar wl retrieve low address word of myvar and move it to W1 0x2678 W1 MOV hi_addr _myvar W1 retrieve high address word of myvar and move it to W1 0x0000 W1 MOV 1o addr proc WO retrieve hi address byte of routine proc and move it to WO 0x0001 W1 MOV flo addr msg WO retrieve low address word of constant msg and move it to WO 0x3652 gt W1 MOV _myvarl 2 w0 accessing hi word of myvarl variable and move it to W1 OxABCD gt W1 end end Asm code and SSA optimization If asm code is mixed with the Pascal code keep in mind that the generated code can substantially differ when SSA optimization option is enabled or disabled This is due to the fact that SSA optimization uses certain working registers to store routine parameters W10 W13 rather than storing them onto the function frame Because of this user must be very careful when writing asm code as existing values in the working registers used by SSA optimization can be overwritten To avoid this it is recommended that user includes desired asm code in a separate routine 229 MikroElektronika
457. ram line then halts If the executed Step Into program line calls another routine the debugger steps into the F7 DO routine and halts after executing the first instruction within it Executes the current program line then halts If the executed program line calls another routine the debugger will not step into it The whole routine will be executed and the debugger halts at the first instruction following the call Step dut Executes all remaining program lines within the subroutine The F8 o9 debugger halts immediately upon exiting the subroutine mnl Run To Cursor Executes the program until reaching the cursor position Ctrl F8 zm Vad ke meudieddiuk Toggle breakpoints option sets new breakpoints or removes those a already set at the current cursor position Step Over Related topics Run Menu Debug Toolbar MikroElektronika 132 mikroPascal PRO for PIC32 CHAPTER 6 mikroPascal PRO for PIC32 Specifics The following topics cover the specifics of mikroPascal PRO for PIC32 compiler ANSI Standard Issues Predefined Globals and Constants Accessing Individual Bits Interrupts Linker Directives Built in Routines Code Optimization 133 MikroElektronika mikoPascal PRO for PIC32 Predefined Globals and Constants To facilitate PIC32 programming the mikroPascal PRO for PIC32 implements a number of predefined globals and constants All PIC32 SFRs are implicitly declared as global varia
458. rameters used in the example MSF Short Message Format used for internal purposes by IDE DBG Generate debug info p32MX460F512L MCU PIC32MX460F512L selected Y Dynamic link for string literals enabled DL All files built as libraries 011111114 Miscellaneous output options f080 Set oscillator frequency in MHz N C NLcdNLcd mpp32 SP C Program Files Mikroelektronika mikroPascal PRO for PIC32 Defs Output files generated to file path specified by filename SP C Program Files Mikroelektronika mikroPascal PRO for PIC32 Defs Add directory to the search path list SP C Program Files Mikroelektronika mikroPascal PRO for PIC32 Uses Add directory to the search path list SP C Led Add directory to the search path list Lcd mpas Lib Math emcl Lib MathDouble emcl Lib System emcl Lib Delays emcl Lib LcdConsts emcl Lib Lcd emcl Specify input files MikroElektronika 112 mikroPascal PRO for PIC32 CHAPTER 4 Introduction The mikrolCD is a highly effective tool for a Real Time debugging on hardware level The mikrolCD debugger enables you to execute the mikroPascal PRO for PIC32 program on a host PIC32 microcontroller and view variable values Special Function Registers SFR RAM CODE and EEPROM memory along with the mikroICD code execution on hardware 113 MikroElektronika mikoPascal PRO for PIC32 Se 1 7 7ZZ77 27 If you hav
459. ration Consts MikroElektronika 546 mikroPascal PRO for PIC32 TP TFT Init Prototype procedure TP TFT Init display width word display height word readX ChNo byte readY ChNo byte Initialize TFT touch panel display Default touch panel ADC threshold value is set to 900 Parameters display width set display width display height set display height readX ChNo read X coordinate from desired ADC channel readY ChNo read Y coordinate from desired ADC channel Before calling this function initialize ADC module ADC1 Init Initalize ADC module TP TFT Init 320 240 13 12 Initialize touch panel TP TFT Set ADC Threshold pees procedure TP TFT Set ADC Threshold threshold word Set custom ADC threshold value call this function after TP_TFT_Init threshold custom ADC threshold value TP TFT Init has to be called before using this routine Example TP TFT Set ADC Threshold 900 Set touch panel ADC threshold 547 MikroElektronika mikoPascal PRO for PIC32 TP_TFT_Press_Detect TTE Detects if the touch panel has been pressed 1 if touch panel is pressed 0 otherwise Requires Global variables DriveX Left DriveX Left pin DriveX Right DriveX Right pin DriveY Up DriveY Up pin DriveY Down DriveY Down pin DriveX Left Direction Direction of DriveX Left pin DriveX Right Direction Direction of DriveX Right pin DriveY Up Direction Direction of Dr
460. re Expander Set PullUpsPortA ModuleAddress Data byte The function sets Port Expander s PortA pull up down resistors Parameters ModulcAddress Port Expander hardware address see schematic at the bottom of this page Data data for choosing pull up down resistors configuration Each bit corresponds to the appropriate pin of the PortA register Set bit enables pull up for corresponding pin Port Expander must be initialized See Expander Init Set Port Expander s PORTA pull up resistors Expander Set PullUpsPortA 0 SFF MikroElektronika 354 mikroPascal PRO for PIC32 Expander Set PullUpsPortB Prototype procedure Expander Set PullUpsPortB ModuleAddress Data byte The function sets Port Expander s PortB pull up down resistors Parameters ModulcAddress Port Expander hardware address see schematic at the bottom of this page Data data for choosing pull up down resistors configuration Each bit corresponds to the appropriate pin of the PortB register Set bit enables pull up for corresponding pin Port Expander must be initialized See Expander Init Set Port Expander s PORTB pull up resistors Expander Set PullUpsPortB 0 OxFF Expander Set PullUpsPortAB Prototype procedure Expander Set PullUpsPortB ModuleAddress Data byte The function sets Port Expander s PortA and PortB pull up down resistors Parameters ModuleAddress Port Expander hardware address see schematic at t
461. re are set to default receive buffer start address 0x0000 receive buffer end address 0x19AD transmit buffer start address 0x19AE transmit buffer end address Ox1FFF RAM buffer read write pointers in auto increment mode receive filters set to default CRC MAC Unicast MAC Broadcast in OR mode flow control with TX and RX pause frames in full duplex mode frames are padded to 60 bytes CRC maximum packet size is set to 1518 Back to Back Inter Packet Gap 0x15 in full duplex mode 0x12 in half duplex mode Non Back to Back Inter Packet Gap 0x0012 in full duplex mode 0x0C12 in half duplex mode Collision window is set to 63 in half duplex mode to accomodate some ENC24 600 revisions silicon bugs CLKOUT output is disabled to reduce EMI generation half duplex loopback disabled LED configuration default LEDA link status LEDB link activity Parameters mac RAM buffer containing valid MAC address ip RAM buffer containing valid IP address configuration ethernet negotiation duplex and speed mode settings For this purpose predefined library constants see the list below can be combined using logical AND to form appropriate value Ethernet 24j TO NEGOTIATION ote It is advisable to use only the Auto negotiation setting If manual negotiation is used then duplex and Speed mode setting must be set also Duplex and speed mode may be set only when using
462. reakpoints Window Watch Values Window RAM Window Stopwatch Window EEPROM Watch Window Code Watch Window Breakpoints Window The Breakpoints window manages the list of currently set breakpoints in the project Doubleclicking the desired breakpoint will cause cursor to navigate to the corresponding location in source code In situations when multiple breakpoints are used within the code it is sometimes handy to enable disable certain breakpoints To do this just check uncheck the desired breakpoint using the checkbox in front of the breakpoint s name Breakpoints Enable Line File Name Watch Values Window Watch Values Window is the main Debugger window which allows you to monitor program execution To show the Watch Values Window select Debug Windows Watch from the View drop down menu The Watch Values Window displays variables and registers of the MCU with their addresses and values Values are updated along with the code execution Recently changed items are coloured red There are two ways to add variable register into the watch list by its real name variable s name in program code Just select wanted variable register from Select variable from list drop down menu and click the ox Add button by its name ID assembly variable name Simply type name ID of the variable register you want to display into Search for variable by assemby name box and click the x add button MikroElektronika 120 mikroP
463. rection of the Data pin 3 D4 Direction Direction of the Data pin 4 1 D5_Direction Direction of the Data pin 5 D6 Direction Direction of the Data pin 6 D7 Direction Direction of the Data pin 7 LCD CS1 Direction Direction of the Chip select 1 pin LCD CS2 Direction Direction of the Chip select 2 pin LCD RS Direction Direction of the Register select signal pin LCD RW Direction Direction of the Read Write signal pin LCD EN Direction Direction of the Enable signal pin LCD RST Direction Direction of the Reset signal pin must be defined before using this function Glcd module connections var GLCD D7 sbit at RD3 bit GLCD D6 sbit at RD2 bit GLCD D5 sbit at RDI bit GLCD D4 sbit at RDO bit GLCD D3 sbit at RB3 bit GLCD D2 sbit at RB2 bit GLCD DI sbit at RBI bit GLCD DO sbit at RBO_ DIE GLCD D7 idisperion sbit at TRISD3 bit GLCD D6 Direction sbit at TRISD2 bit GLCD D5 Direction sbit at TRISD1 bit GLCD D4 Direction sbit at TRISDO bit GLCD D3 Direction sbit at TRISB3 bit GLCD_ D Direction sbit at TRISB2 bit GLCD DI Direction sbit at TRISB1 bit GLCD DO Direction sbit at TRISBO bit GLCD CS2 sbit at LATBS bit GLCD RS gt sbit at LATFO bit GLCD RW sbit at LATF1 bit GLCD EN sbit at LATF4 bit GLCD ROT sbit at LATFS bit GLCD CS1 Direction sbit at TRISB4 bit GLCD CS2 Direction sbit at TRISB5 bit GLCD RS Direction sbit at TRISFO bit GLCD RW Direction sbit at TR
464. ri o Recent Files gt Save Ctr S Save As Close Ctri F4 Close All Shift Ctrl F4 Print Preview S25 Print Ctrl P Exit AIL X File Z4 Description O Related topics Keyboard shortcuts File Toolbar Managing Source Files MikroElektronika 38 mikroPascal PRO for PIC32 Edit Edit Menu Options The Edit Menu contains commands for editing the contents of the current document Undo Ctr z Redo Shift Ctrl z My Cut Ctrlex Copy Ctrl C Paste Ctrl V Delete Select All Ctrl Find Ctrl F Find Next F3 Find Previous Shift F3 Replace Ctrl R Find In Files Alt F3 Goto Line Ctri G Advanced Edt Bescipin O 39 MikroElektronika mikoPascal PRO for PIC32 Advanced Description Comment selected code or put single line comment if there is no selection Uncomment selected code or remove single line comment if there is no selection Indent shift ctr I Indent selected code Outdent shift ctr U f Outdent selected code Changes selected text case to lowercase Changes selected text case to uppercase Changes selected text case to titlercase Find Text Dialog box for searching the document for the specified text The search is performed in the direction specified If the string is
465. rite ID 1st RxTx Data 1 Can Send Flags send incremented data back end end end Code for the second CANSPI node Copy Code To Clipboard program Can Spi 2nd const ID 1st longint 12111 const ID 2nd longint 3 var Can Init Flags Can Send Flags Can Rcv Flags word can flags Rx Data Len word xeceived data length in bytes RxTx Data array 8 of byte can rx tx data buffer Msg Rcvd byte reception flag Tx ID Rx ID dword can rx and tx ID CANSPI module connections var CanSpi CS sbit at LATFO bit CanSpi CS Direction sbit at TRISFO bit CanSpi Rst sbit at LATFl bit CanSpi Rst Direction sbit at TRISF1 bit End CANSPI module connections begin CHECON 0x32 ADIPCFG OxFFFF configure AN pins as digital I O MikroElektronika 254 mikroPascal PRO for PIC32 PORTB 0 clear PORTB TRISB 0 set PORTB as output Can Init Flags 0 Can Send Flags 0 clear flags Can Rev Flags 0 id Can Send Flags CANSPI TX PRIORITY 0 and form value to be used CANSPI TX XTD FRAME and with CANSPIWrite CANSPI TX NO RTR FRAME PI CONFIG SAMPLE THRICE and form value to be used PI CONFIG PHSEG2 PRG ON and with CANSPIInit PI CONFIG XTD MSG and PI CONFIG DBL BUFFER ON and PI CONFIG VALID XTD MSG and PI CONFIG LINE FILTER OFF Can Init Flags CAN
466. rnally called by the library and should not be called by the user s code The function source code is provided with appropriate example projects The code should be adjusted by the user to achieve desired reply MikroElektronika 412 mikroPascal PRO for PIC32 SPI Ethernet UserUDP Prototype function SPI Ethernet UserUDP var remoteHost array 4 of byte remotePort destPort reqLength word var flags TEthPktFlags word Description This is UDP module routine It is internally called by the library The user accesses to the UDP request by using some of the SPI Ethernet get routines The user puts data in the transmit buffer by using some of the SPI Ethernet put routines The function must return the length in bytes of the UDP reply or 0 if nothing to transmit If you don t need to reply to the UDP requests just define this function with a return 0 as single statement Parameters remoteHost client s IP address remotePort client s port localPort port to which the request is sent reqLength UDP request data field length flags structure consisted of two bit fields Copy Code To Clipboard type TEthPktFlags record canCloseTCP boolean flag which closes socket not relevant to UDP isBroadcast boolean flag which denotes that the IP package has been received via subnet broadcast address end 0 there should not be a reply to the request Length of UDP reply data field oth
467. rnet 24j600 putString Prototype function SPI Ethernet 245 600 putString ptr byte word Description This is MAC module routine It stores whole string excluding null termination into ENC247600 RAM starting from current ENC247600 write pointer EWRPT location Parameters ptr string to be written into ENC247600 RAM Number of bytes written into ENC247600 RAM Requires Ethernet module has to be initialized See SPI Ethernet 24j600 Init var buffer string 16 buffer mikroElektronika SPI Ethernet 243600 putString buffer put a RAM string into ENC24J600 buffer SPI Ethernet 24j600 putConstString Prototype function SPI Ethernet 247600 putConstString const ptr byte word Description This is MAC module routine It stores whole const string excluding null termination into ENC247600 RAM starting from current ENC24600 write pointer EWRPT location Parameters ptr const string to be written into ENC247600 RAM Number of bytes written into ENC247600 RAM Requires Ethernet module has to be initialized See SPI Ethernet 24j600 Init const buffer string 16 buffer mikroElektronika SPI Ethernet 243600 putConstString buffer put a const string into ENC24J600 buffer SPI Ethernet 24j600 getByte Prototype function SPI Ethernet 24 600 getByte byte Description This is MAC module routine It fetches a byte f
468. rom address pointed to by current ENC247600 read pointer ERDPT Byte read from ENC243600 RAM Requires Ethernet module has to be initialized See SPI Ethernet 24j600 Init var buffer byte buffer SPI Ethernet 243600 getByte read a byte from ENC24J600 buffer 437 MikroElektronika mikoPascal PRO for PIC32 SPI_Ethernet_24j600_getBytes Prototype procedure SPI Ethernet 243600 getBytes ptr byte addr word Description This is MAC module routine It fetches equested number of bytes from ENC2 47600 RAM starting from given address If value of OxFFFF is passed as the address parameter the reading will start from current ENC24J600 read pointer ERDPT location Parameters ptr buffer for storing bytes read from ENC247600 RAM addr ENC243600 RAM start address Valid values 0 8192 n number of bytes to be read Ethernet module has to be initialized See SPI Ethernet 24j600 Init var buffer array 16 of byte SPI Ethernet 24 600 getBytes buffer 0x100 16 read 16 bytes starting from address 0x100 SPI Ethernet 24j600 UserTCP Prototype function SPI Ethernet 243600 UserTCP var remoteHost array 4 of byte remotePort localPort reqLength word var flags TEthj600PktFlags word Description This is TCP module routine It is internally called by the library The user accesses to the TCP request by using some of the SPI Ethernet 24j600 get
469. rough S1D13700 Write Command routine S1D13700 Write Command S1D13700 CSRW set cursor address S1D13700 Write Parameter Lo start send lower byte of cursor address S1D13700 Write Parameter Hi start send higher byte cursor address S1D13700 Read Parameter Rems Nothing Example rarameter 51013700 Read Parameter S1D13700 Fill Prototype pm 1D13700 Fill d byte start word len word Description Fills Glcd memory block with given byte Parameters d byte to be written start starting address of the memory block Len length of the memory block in bytes Glcd module needs to be initialized See the S1D13700 Init routine from the starting address of 0x3000 fill the memory block size of Ox7FFF with 0x20 S51D13700 Fill 0x20 0x3000 Ox7FFF MikroElektronika 282 mikroPascal PRO for PIC32 1D13700_GrFill Prototype procedure S1D13700 GrFill d byte Description Fill graphic layer with appropriate value 0 to clear Parameters d value to fill graphic layer with Glcd module needs to be initialized See the S1D13700 Init routine clear current graphic panel S1D13700 GrFill 0 S1D13700 TxtFill Prototype procedure 1D13700 TxtFill d byte Description Fill current text panel with appropriate value 0 to clear Parameters d this value will be used to fill text panel Glcd module needs to be initialized See the S1D13700 Init
470. routine clear current text panel SIDISTOO Txtr311 0 4 S1D13700 Display GrLayer Prototype procedure S 1D13700 Display GrLayer mode byte Description Display selected graphic layer Parameters mode graphic layer mode Valid values Glcd module needs to be initialized See the S1D13700 Init routine Turn on graphic layer S1D13700 Display GrLayer S1D13700 LAY 283 MikroElektronika mikoPascal PRO for PIC32 S1D13700 Display TxtLayer Prototype procedure S 1D13700 Display TxtLayer mode byte Description Display selected text layer Parameters mode text layer mode Valid values Glcd module needs to be initialized See the S1D13700 Init routine Display on text layer S1D13700 Display TxtLayer S1D13700 LAYER ON S1D13700 Set Cursor Prototype procedure 1D13700 Set Cursor width byte height byte mode byt Description Sets cursor properties Parameters width in pixels 1 must be less than or equal to the horizontal char size height in lines 1 must be less than or equal to the vertical char size mode cursor mode Valid values S1D13700 CURSOR UNDERSCORE Set cursor shape underscore S1D13700 CURSOR BLOCK Set cursor shape block Glcd module needs to be initialized See the S1D13700 Init routine set cursor with the following properties width 5px height 10px cursor shape block S1D13700 Set Cursor 5 X 1D13700 CURSOR BLO
471. ruction cycle clock conversion clock 32 Tcy auto sample time 31TAD Rems Nothing Example A0C1 imit 0 Initiaiize ADC nodule with default settings etes None OOS 231 MikroElektronika mikoPascal PRO for PIC32 ADC1_Init_Advanced Prototype procedure ADC1 Init Advanced Reference word This routine configures the internal ADC module to work with user defined settings Parameters Reference voltage reference used in ADC process The MCU with built in ADC module Example ADC1_ Init Advanced ADC INTERNAL RE set internal reference used i Not all MCUs support advanced configuration Please read the appropriate datasheet before utilizing this library ADC1_Get_Sample Ceap function ADC1 Get Sample channel word word The function enables ADC module and reads the specified analog channel input channel represents the channel from which the analog value is to be acquired Returns 10 bit unsigned value from the specified channel Requires The MCU with built in ADC module Prior to using this routine ADC module needs to be initialized See ADCx_Init and ADCx_Init_ Advanced Before using the function be sure to configure the appropriate TRISx bits to designate pins as inputs The function sets the appropriate bit in the AD1PCFG registers to enable analog function of the chosen pin Refer to the appropriate Datasheet for channel to
472. s Data byte The function writes byte to Port Expander s PortA Parameters ModulecAddress Port Expander hardware address see schematic at the bottom of this page bata data to be written Requires Nothing Port Expander must be initialized See Expander Init Port Expander s PortA should be configured as output See Expander Set DirectionPortA and Expander Set DirectionPortAB routines Write a byte to Port Expander s PORTA Expander Set DirectionPortA 0 00 set expander s porta to be output Expander Write PortA 0 AA Expander Write PortB Prototype procedure Expander Write PortB ModuleAddress Data byte The function writes byte to Port Expander s PortB Parameters ModulecAddress Port Expander hardware address see schematic at the bottom of this page bata data to be written Requires Port Expander must be initialized See Expander Init Port Expander s PortB should be configured as output See Expander Set DirectionPortB and Expander Set DirectionPortAB routines Write a byte to Port Expander s PORTB Expander Set _DirectionPortB 0 00 set expander s portb to be output Expander Write PortB 0 55 MikroElektronika 392 mikroPascal PRO for PIC32 Expander Write PortAB Prototype Description Parameters Requires procedure Expander Write PortAB ModuleAddress byte Data word The function writes word to Port Expander s ports
473. s Software breakpoints are much slower than hardware breakpoints These differences between hardware and software breakpoints are not visible in the mikroICD software but their different timings are quite notable That s why it is important to know that there are two types of breakpoints The picture below demonstrates step by step execution of the code used in above mentioned examples Common Errors Trying to program the MCU while the mikrolCD is active Trying to debug Release build version of the program with the mikrolCD debugger Trying to debug program code which has been changed but has not been compiled and programmed into the MCU Trying to select line that is empty for Run to cursor F4 and Toggle Breakpoints F5 functions Trying to debug MCU with mikrolCD while Watch Dog Timer is enabled Trying to debug MCU with mikroICD while Power Up Timer is enabled Trying to Step Into F7 the mikroPascal PRO for PIC32 Library routines Use Step Over F8 command for these routines It is not possible to force Code Protect while trying to debug MCU with mikroICD Trying to debug MCU with mikroICD with pull up resistors set to ON on RB6 and RB7 Related topics mikrolCD Debugger mikrolCD Debug Windows mikroICD Debugger Options 119 MikroElektronika mikoPascal PRO for PIC32 mikroICD Debugger Windows Debug Windows This section provides an overview of available Debug Windows in mikroPascal PRO for PIC32 B
474. s F12 Related topics Keyboard shortcuts Tools Toolbar 4l MikroElektronika mikoPascal PRO for PIC32 Help Help Menu Options Help Fi Migration Document Check For Updates tmikroElektronika Support Forums mikroElektronika Web Page A How To Register About mp a Related topics Keyboard shortcuts Help Toolbar MikroElektronika 48 mikroPascal PRO for PIC32 mikroPascal PRO for PIC32 IDE IDE Overview The mikroPascal PRO for PIC32 is an user friendly and intuitive environment For a detailed information on a certain part of IDE simply click on it hovering a mouse cursor above a desired IDE part will pop up its name OUR mem font bat bo ba ow Oe eee sm aad st PY NR ES D ME AAR ST ooo Aan ee ET C EET a Cole Cote ases 8 O wrap 0 vae wies we Vect d You ce Change the meriag speed bere l SAS Seer s UA wie be Bas x ne per alan ten vti hb eret ADIRCG ce OnrrrTs afigute AM pine oe digital 2 M ee k p ved ge UDINE vea Gand ge iomat a tut 15 energie i m se aspen m oe m A 0 at hoe Los Cmt _LCD_CLEAD 1 one ley e Lo Omd LC _CRRSCR_ COT C tostis ovome eaonooee LER Out 1 5 txt3 rite LCb Ow 1 6 txt4 7 Delay meo 1000 Led Omd LCB CLEAN 1 Ld 0 ADOOC Cory iFa PIC GI
475. s are multi byte so this routine must be called for each byte received data buffer 7 byte buffer for storing received data Data will be stored in the following manner data buffer 0 2 message content data buffer 3 number of message bytes received 1 3 data buffer 4 is setto 255 when message is received data buffer 5 is setto 255 if error has occurred 6 J 13 J data buffer 6 address of the Slave which sent the message The routine automatically adjusts data 4 and data 5 upon every received message These flags need to be cleared by software Nothing MCU must be initialized as a Master for RS 485 communication See RS485Master Init var msg array 8 of byte RS485Master Receive msg RS485Master Send Prototype Description Parameters Requires procedure RS485Master Send var buffer array 20 of byte datalen byte slave address byte Sends message to Slave s Message format can be found at the bottom of this page data buffer data to be sent datalen number of bytes for transmition Valid values O 3 slave address Slave s address Nothing MCU must be initialized as a Master for RS 485 communication See RS485Master Init It is the user s responsibility to ensure by protocol that only one device sends data via 485 bus at a time var msg array 8 of byte send 3 bytes of data to Slave with address 0x12 RS485Master Send msg 3 0x12 MikroElektronika
476. s copy the IP address from the RAM location returned by this routine into it s own DNS IP address buffer These locations should not be altered by the user in any case MikroElektronika mikroPascal PRO for PIC32 SPI Ethernet getlpMask Prototype Prototype function SPI Ethernet getIpMask This routine should be used when DHCP server is present on the network to fetch assigned IP subnet mask Retums Pointer to the global variable holding IP subnet mask Ethernet module has to be initialized See SPI Ethernet Init va IpMask array 4 of byte user IP subnet mask buffer memcpy IpMask SPI Ethernet getIpMask 4 fetch IP subnet mask User should always copy the IP address from the RAM Tem returned by this routine into it s own IP subnet mask buffer These locations should not be altered by the user in any case SPI Ethernet confNetwork Prototype Wiring SPI Ethernet confNetwork var ipMask gwIpAddr dnsIpAddr array of byte cem network TUNER IP subnet mask gateway IP address DNS IP address when DHCP is not used Parameters ipMask IP subnet mask gwIpAddr gateway IP address dnsIpAddr DNS IP address Ethernet module has to be initialized See SPI Ethernet Init ipMask array 4 of byte network mask for example 255 255 295 0 gwlIpAddr array 4 of byte gateway router IP address dnsIpAddr array 4 of byte DNS server IP address gwipAddr 0 1923
477. s is calculated by using the Exception Base EBase address its address default is OX9FCO01000E The exact formula for Single Vector mode is as follows Single Vector Address EBase 0x200 Multi Vector Mode In this mode the CPU vectors to the unique address for each vector number Each vector is located at a specific offset with respect to a base address specified by the EBase register in the CPU The individual vector address offset is determined by the following equation EBase Vector_Number x Vector_Space 0x200 By default the compiler configures interrupts in the Multi Vector mode with the EBase address set to 0x9FC01000 and vector spacing of 32 Configuring the Interrupt operating mode is performed in the Edit Project window MikroElektronika 138 mikroPascal PRO for PIC32 Interrupt Priorities In the Multi Vector Mode the user is able to assign a group priority and group subpriority level to each of the interrupt vectors The user selectable priority levels range from 1 the lowest priority to 7 the highest If an interrupt priority is set to zero the interrupt vector is disabled for both interrupt and wake up purposes Interrupt vectors with a higher priority level preempt lower priority interrupts The subpriority will cause that when two interrupts with the same priority are pending the interrupt with the highest subpriority will be handled first The user selectable subpriority levels range from O the lo
478. s of the FLASH memory block etes None 293 MikroElektronika mikoPascal PRO for PIC32 Graphic Lcd Library mikroPascal PRO for PIC32 provides a library for operating Graphic Lcd 128x64 with commonly used Samsung KS108 KS107 controller For creating a custom set of Glcd images use Glcd Bitmap Editor Tool Library Dependency Tree Glcd 9 Glcd Fonts MikroElektronika 294 mikroPascal PRO for PIC32 External dependencies of Graphic Lcd Library The following variables must be defined in all projects using Graphic Lcd Library var GLCD DO sbit sfr external Data 0 line var GLCD D1 sbit sfr external Data 1 line var GLCD D2 sbit sfr external Data 2 line Data 3 line var GLCD D4 sbit sfr external Data 4 line var GLCD D6 sbit sfr external LCD D7 sbit sfr external var GLCD CS1 sbit sfr external var GLCD RW sbit sfr external LCD EN sbit sfr external LCD RST sbit sfr external GLCD DO Di ti i Sbit Sfr kie ree 225 Direction of the Data 0 pin external bit fr A TS Direction of the Data 1 pin var GLCD D3 sbit sfr external var G var G var G var GLCD Dl Direction external var GLCD D2 Direction sfr external Sbit Direction of the Data 2 pin Sfr var GLCD D3 Direction sbit Pern Direction of the Data 3 pin var GLCD_D4 Direction estaria Direction of the Data 4 pin var
479. s that was started when the Start Recording command was selected Allows a macro that has been recorded to be replayed Related topics Code Editor Code Templates Image Preview There are a lot of occassions in which the user besides the code must look at the appropriate schematics in order to succesfully write the desired program The mikroPascal PRO for PIC32 provides this possibility through the Image Preview Window To add an image to the Image Preview Window right click the Image Files node in the Project Manager Project Manager 1 1 R5485 Master Example mpp32 40 Hss eaga g RB RS485_Master_Example mpp32 S Sources sj R5485 Master Example mpas Binaries Project Level Defines ig EEPROM File Active Comm S E Output Files B Add Project E Rs485 N 5 gt Other Files Close Project Ctrl K T Add File To Project Remove File From Project Build Ctrl F9 Ter mE Programmer Fill MikroElektronika D mikroPascal PRO for PIC32 Now navigate to the desired image file and simply add it E Project Manager 1 1 R5485 Master Example mpp32 40 js 3S SE Gat we B RS485_Master_Example mpp32 B Sources R5485 Master Example mpas m Binaries Project Level Defines S C Image Files EEPROM Files Active Comments Files S Cj Output Files RS485 Master Example hex C3 Other Files Next right
480. scription of all routines and global variables relevant to the user implemented in the SPI Ethernet ENC24J600 Library The appropriate hardware SPI module must be initialized before using any of the SPI Ethernet ENC24J600 library routines Refer to SPI Library For MCUs with multiple SPI modules it is possible to initialize them and then switch by using the SPI Set Active routine Library Dependency Tree SPI Ethernet i String l MikroElektronika 428 mikroPascal PRO for PIC32 External dependencies of SPI Ethernet ENC24J600 Library The following variables must be defined in all projects using SPI Ethernet Description ENC24J600 Library var SPI Ethernet 245600 CS var SPI Ethernet 245600 CS sbit at sbit sfr external ENC24J600 chip select pin LATF1 bit var SPI Ethernet 245600 CS Direction of the ENC24J600 chip var SPI Ethernet 243600 CS Direction Direction sbit sfr external select pin sbit at TRISF1 bit The following routines must be defined in all project using SPI Ethernet Geecantion ENC24J600 Library p function SPI Ethernet _24 600 UserTCP var remoteHost array 4 of byte remotePort word Refer to the library example localPort word TCP request handler at the bottom of this page reqLength word for code implementation var flags TEthj600PktFlags function SPI Ethernet 245j600 UserUDP var remoteHost array 4 of byte remotePort word Refertothe
481. se of natural logarithms raised to the power x i e e Example res exp 0 5 ves 1 648721 fabs Prototype function fabs d real real Function returns the absolute i e Lais value of d Example res fabs 1 3 res 153 floor Prototype function floor x real real Function returns the value of an x rounded down to the nearest integer Example res floor 15 258 res 15 000000 frexp Prototype function frexp value real var eptr integer real Description The function splits a floating point value value into a normalized fraction and an integral power of 2 The return value is a normalized fraction and the integer exponent is stored in the object pointed to by eptr Idexp ne function ldexp valu newexp integer real Function a the result of Te the floating point number num by 2 raised to the power n i e ETT x xgh 2 5 res PIORODIBe function log x real real Function returns the natural logarithm of x i e Loge x log 10 res 2 302585E log10 Eee function log10 x real real Function returns the base 10 logarithm of x i e Log 9 x log10 100 res 2 000000 MikroElektronika 598 mikroPascal PRO for PIC32 modf xb ius function modf val real var iptr real real Returns argument val split to the fractional part function return val and integer part in number iptr modf 6 25 iptr
482. sent on the network to fetch assigned IP address Pointer to the global variable holding IP address Ethernet module has to be initialized See SPI Ethernet 24j600 Init var ipAddr array 4 of byte user IP address buffer memcpy ipAddr SPI Ethernet 245600 getIpAddress 4 address User should always copy the IP address from the RAM location returned by this routine into it s own IP address buffer These locations should not be altered by the user in any case 439 MikroElektronika mikoPascal PRO for PIC32 SPI Ethernet 24j600 getGwlpAddress Prototype Prototype function SPI Ethernet 245 600 getGwIpAddress This routine should be used when DHCP server is present on the network to fetch assigned gateway IP address Returns Pointer to the global variable holding gateway IP address Ethernet module has to be initialized See SPI_Ethernet_24j600_Init v gwipAddr array 4 of byte user gateway IP address buffer memcpy gwIpAddr SPI Ethernet 243600 getGwIpAddress 4 fetch gateway IP address User should always copy the IP address from the RAM location returned by this routine into it s own gateway IP address buffer These locations should not be altered by the user in any case SPI Ethernet 24j600 getDnslpAddress Pratotyaa J Prototype function SPI Ethernet 243600 getDnsIpAddress This routine should be used when DHCP server is present on the network to fetch assigned DNS I
483. signment Statements Compound Statements Blocks Conditional Statements If Statement Case Statement Iteration Statements Loops For Statement While Statement Repeat Statement Jump Statements Break and Continue Statements Exit Statement Goto Statement asm Statement Directives Compiler Directives Linker Directives TII MikroElektronika mikoPascal PRO for PIC32 Lexical Elements Overview The following topics provide a formal definition of the mikroPascal PRO for PIC32 lexical elements They describe different categories of word like units tokens recognized by the language In the tokenizing phase of compilation the source code file is parsed i e broken down into tokens and whitespace The tokens in mikroPascal PRO for PIC32 are derived from a series of operations performed on your programs by the compiler Whitespace Whitespace is a collective name given to spaces blanks horizontal and vertical tabs newline characters and comments Whitespace can serve to indicate where tokens start and end but beyond this function any surplus whitespace is discarded For example the two sequences var i char J word and var i T char J word are lexically equivalent and parse identically to give nine tokens var x char word Newline Character Newline character CR LF is nota whitespace in BASIC and serves as a statement terminator separator In mikroPasc
484. specifies the starting address in RAM for a variable If the variable is multi byte higher bytes will be stored at the consecutive locations Directive absolute is appended to declaration of a variable Variable x will occupy 1 word 16 bits at address 0xA0000000 var x word absolute 0xA0000000 Variable y will occupy 2 words at addresses 0xA0000000 and 0xA0000002 var y longint absolute 0xA0000000 Be careful when using the absolute directive as you may overlap two variables by accident For example Variable i will occupy 1 word at address 0xA0000002 var i word absolute 0xA0000002 Variable will occupy 2 words at 0xA0000000 and 0xA0000002 thus changing i changes jj at the same time and vice versa var jj longint absolute 0xA0000000 Directive org Directive org specifies the starting address of a constant or a routine in ROM It is appended to the constant or a routine declaration To place a constant array in Flash memory write the following Constant array MONTHS will be placed starting from the address 0x9D000000 const MONTHS array 1 12 of byte 31 28 31 30 31 30 31 31 30 31 30 31 org 0x800 If you want to place simple type constant into Flash memory instead of following declaration const SimpleConstant byte OxAA org 0x9D000000 use an array consisting of single element const SimpleConstant array 1 of byte 0xAA org 0x9D000000 MikroElektronika 112 mikroP
485. st interested in Copyright c 2002 2010 mikroElektronika All rights reserved What do you think about this topic Send us feedback 29 MikroElektronika mikoPascal PRO for PIC32 Software License Agreement mikroElektronika Associates License Statement and Limited Warranty IMPORTANT READ CAREFULLY This license statement and limited warranty constitute a legal agreement License Agreement between you either as an individual or a single entity and mikroElektronika mikroElektronika Associates for software product Software identified above including any software media and accompanying on line or printed documentation BY INSTALLING COPYING OR OTHERWISE USING SOFTWARE YOU AGREE TO BE BOUND BY ALL TERMS AND CONDITIONS OF THE LICENSE AGREEMENT Upon your acceptance of the terms and conditions of the License Agreement mikroElektronika Associates grants you the right to use Software in a way provided below This Software is owned by mikroElektronika Associates and is protected by copyright law and international copyright treaty Therefore you must treat this Software like any other copyright material e g a book You may transfer Software and documentation on a permanent basis provided You retain no copies and the recipient agrees to the terms of the License Agreement Except as provided in the License Agreement you may not transfer rent lease lend copy modify translate sublicense time share
486. t 8 bits character width data bus on MCP23S17 portB control bus on MCP23S17 portA WR RD ICD bit 4 is RST pose ox db Ce 36 Ea ee chip enabl y reverse on 8x8 font internaly set in library If Port Expander Library uses SPI2 module Initialize SPI module used with PortExpander SPI2 Init Advanced SPI MASTER SPI 8 BIT 4 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE LOW SPI ACTIVE 2 IDLE Die 2 19 bit 1 is bit 0 is ow 3E ROO de ode ue GO init display for 240 pixel width and 128 pixel height 8 bits character width data bus on MCP23S17 portB control bus on MCP23S17 portA WR RD ICD bit 4 is RST chip enable reverse on 8x8 font internaly set in library Initialize SPI Toshiba 240x128 SPI T6963C Config 240 128 8 0 2 1 0 4 Delay ms 1000 Uncomment to demonstrate line drawing routines Uncomment to demonstrate fill routines Uncomment to demonstrate partial image routine MikroElektronika 492 mikroPascal PRO for PIC32 i Enable both graphics and text display at the same time a SPI T6963C graphics 1 SPI T6963C text 1 panel 0 i 0 curs 0 cposx 0 cposy 0 i Text messages ia SPI T6963C write text txt 0 0 SPI T6963C ROM MODE XOR SPI T6963C write text txtl 0 15 SPI T6963C ROM MODE XOR i1 Cursor ur SPI T6963C cursor height 8 8 pixel height SPI T6963C
487. t broadcast crc Specific type of network traffic will be enabled if a corresponding bit of this routine s input parameter is set Therefore more than one type of network traffic can be enabled at the same time For this purpose predefined library constants see the table below can be ORed to form appropriate input value Advanced filtering available in the NC243600 module such as Pattern Match Magic Packet and Hash Table can not be enabled by this routine Additionaly all filters except CRC enabled with this routine will work in OR mode which means that packet will be received if any of the enabled filters accepts it This routine will change receive filter configuration on the fly It will not in any way mess with enabling disabling receive transmit logic or any other part of the ENC24J600 module The ENC247600 module should be properly cofigured by the means of SPI Ethernet 243600 Init routine 1 0x02 MAC Multicast traffic receive filter flag When set MAC SPI Ethernet 243600 multicast traffic will be enabled MULTICAST 5 0x20 CRC check flag When set packets with invalid CRC field SPI Ethernet 244600 CRC will be discarded T Es ep mumd o 7 loxao MAC Unicast traffic receive filter flag When set MAC SPI Ethernet 24 600 unicast traffic will be enabled UNICAST Ethernet module has to be initialized See SPI Ethernet 24600 Init SPI Ethernet 24j600 Enable SPI Ethernet 24j600 CRCor S
488. t sh1 left most bits are discarded and new bits on the right are assigned zeroes Thus shifting unsigned operand to the left by n positions is equivalent to multiplying it by 2n if all discarded bits are zero This is also true for signed operands if all discarded bits are equal to the sign bit With shift right shr right most bits are discarded and the freed bits on the left are assigned zeroes in case of unsigned operand or the value of the sign bit in case of signed operand Shifting operand to the right by n positions is equivalent to dividing it by 2 MikroElektronika 218 mikroPascal PRO for PIC32 Boolean Operators Although mikroPascal PRO for PIC32 does not support boolean type you have Boolean operators at your disposal for building complex conditional expressions These operators conform to standard Boolean logic and return either TRUE all ones or FALSE zero and logical AND logical OR xor logical exclusive OR XOR not logical negation Boolean operators associate from left to right Negation operator not associates from right to left Unary Operators Unary operators are operators that take exactly one argument Unary Arithmetic Operator Operator can be used as a prefix unary operator to change sign of a signed value Unary prefix operator can be used also but it doesn t affect data For example b a Unary Bitwise Operator The result of the not bitwise negation
489. t 193 Other Units 194 Interface Section 194 Implementation Section 194 Variables 195 External Modifier 195 Variables and PIC32 196 Constants 197 Labels 198 Functions and Procedures 199 Functions 199 Calling a function 199 Example 199 MikroElektronika mikroPascal PRO for PIC32 Procedures 200 Calling a procedure 200 Example 200 Example 201 Forward declaration 201 Functions reentrancy 202 Types 202 Type Categories 202 Simple Types 203 Derived Types 203 Arrays 204 Array Declaration 204 Constant Arrays 204 Multi dimensional Arrays 204 Strings 205 String Concatenating 205 Pointers 206 Pointers and memory spaces 206 Function Pointers 207 Example 207 Operator 209 Pointer Arithmetic 209 Assignment and Comparison 209 Pointer Addition 210 Pointer Subtraction 211 Records 212 Accessing Fields 212 Types Conversions 213 Implicit Conversion 213 Promotion 213 Clipping 214 Explicit Conversion 214 Conversions Examples 214 Type Specifier 215 Type Qualifiers 216 Qualifier const 216 Qualifier volatile 216 Operators 216 Operators Precedence and Associativity 217 Arithmetic Operators 217 Division by Zero 217 Unary Arithmetic Operators 218 Relational Operators 218 MikroElektronika mikoPascal PRO for PIC32 Relational Operators in Expressions Bitwise Operators Bitwise Operators Overview Logical Operations on Bit Level Unsigned and Conversions Signed and Conversions Bitwise Shift Operators Boolean O
490. t a Record via function call MyCircle CenterX DefineCircle 100 200 30 CenterX 20 Access a Record field via function call emm mmm rieie Function returns TCircle Access to one field of TCircle end Forward declaration A function can be declared without having it followed by it s implementation by having it followed by the forward procedure The effective implementation of that function must follow later in the unit The function can be used after a forward declaration as if it had been implemented already The following is an example of a forward declaration program Volume var Volume word function First a b word word forward function Second c word word var tmp word begin tmp Eirsti2 32 result tmp c end 199 MikroElektronika mikoPascal PRO for PIC32 function First a b word word begin result a b end begin Volume Second 4 end Functions reentrancy Functions reentrancy is allowed Remember that the PIC32 have memory limitations that can vary between MCUs Types Pascal is strictly typed language which means that every variable and constant need to have a strictly defined type known at the time of compilation The type serves to determine the correct memory allocation required to interpret the bit patterns found in the object during subsequent accesses in many type checking situations to ensure that
491. t available i on its left if expressionl then if expression2 then statementl else statement2 The compiler treats the construction in this way if expressionl then begin if expression2 then statementl else statement2 end In order to force the compiler to interpret our example the other way around we have to write it explicitly if expressionl then begin if expression2 then statementl end else statement2 MikroElektronika 2241 mikroPascal PRO for PIC32 Case Statement Use the case statement to pass control to a specific program branch based on a certain condition The case statement consists of a selector expression a condition and a list of possible values The syntax of the case statement is case selector of value 1 statement 1 value n statement n else default statement end selector is an expression which should evaluate as integral value values can be literals constants or expressions and statements can be any statements The else clause is optional If using the else branch note that there should never be a semicolon before the keyword else First the selector expression condition is evaluated Afterwards the case statement compares it against all available values If the match is found the statement following the match evaluates and the case statement terminates In case there are multiple matches the first matching statement will be executed If none of values matches selector t
492. t care because IDE cannot recover them Clean Project Folder Below is the list of all files in the project folder Files in bold are those generated by the compiler and they can be easily recreated when the project is rebuilt Select which files you want to remove from the project folder Please note that selected files will be permanently deleted from your disk if you click COG xml LCD asm LCD cfg LCD dbg LCD dct LCD dlt LCD emcl LCD hex LCD log LCD Ist LCD mpas LCD mpp32 LCD mpp32 callertable txt LCD user dic v M v vi v v C Program Files Mikroelektronika mikroPascal PRO For PIC32 Examples Development Sy Related topics Customizing Projects MikroElektronika 612 mikroPascal PRO for PIC32 Compilation When you have created the project and written the source code it s time to compile it Select Project Build from the drop down menu or click the Build Icon 3h from the Build Toolbar If more more than one project is open you can compile all open projects by selecting Project Build All Projects from the drop down menu or click the Build All Projects Icon By trom the Build Toolbar Progress bar will appear to inform you about the status of compiling If there are some errors you will be notified in the Messages Window If no errors are encountered the mikroPascal PRO for PIC32 will generate output files Output Files Upon successful compilation the mikroPascal PRO f
493. t div T6963C CHARACTER HEIGHT then Delay ms 100 end end 921 MikroElektronika mikoPascal PRO for PIC32 HW Connection EE Eh Contrast Adjustment SPI T6963C Gicd HW connection MikroElektronika 022 mikroPascal PRO for PIC32 TFT Library Thin film transistor liquid crystal display TFT LCD is a variant of liquid crystal display LCD which uses thin film transistor TFT technology to improve image quality e g addressability contrast TFT LCD is one type of active matrix LCD though all LCD screens are based on TFT active matrix addressing TFT LCDs are used in television sets computer monitors mobile phones handheld video game systems personal digital assistants navigation systems projectors etc The mikroPascal PRO for PIC32 provides a library for working with HX8347 D 320x240 TFT Lcd controller The HX8347 D is designed to provide a single chip solution that combines a gate driver a source driver power supply circuit for 262 144 colors to drive a TFT panel with 320x240 dots at maximum The HX8347 D is suitable for any small portable battery driven and long term driving products such as small PDAs digital cellular phones and bi directional pagers External dependencies of TFT Library The following variables must be defined in all Vs A Description projects using TFT library var TFT DataPort Direction byte F var TFT DataPort Direction byte D
494. t in the current text panel of Glcd at coordinates x y Parameters str text to be written x text position on x axis column y text position on y axis row mode mode parameter Valid values In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons 1D13700 OVERLAY XOR In this mode the text and graphics data are combined via the logical exclusive OR SIDi3700 OVERLAY AND The text and graphic data show on display are combined via the logical AND function Glcd module needs to be initialized See the S1D13700 Init routine S1D13700 Write Text EPSON LIBRARY DE S1D13700 OVERLAY _ OR S1D13700 OVERLAY OR S1D13700 Dot Prototype procedure S 1D13700 Dot x word y word color byte Description Draws a dot in the current graphic panel of Glcd at coordinates x y Parameters x dot position on x axis y dot position on y axis color color parameter Valid values S 1D13700 BLACK Black color S1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine ea S1D13700 Dot 50 50 S1D13700 WHITE MikroElektronika 286 mikroPascal PRO for PIC32 S1D13700 Line Prototype procedure 1D13700 Line x0 y0 xl yl word pcolor byte Nothing Description Draws a line from x0
495. t sends an DHCP request for network parameters IP gateway DNS addresses and IP subnet mask and waits for DHCP reply If the requested parameters were obtained successfully their values are stored into the library global variables These parameters can be fetched by using appropriate library IP get routines SPI Ethernet 24j600 getlpAddress fetch IP address SPI Ethernet 24j600 getGwlpAddress fetch gateway IP address SPI Ethernet 24j600 getDnslpAddress fetch DNS IP address SPI Ethernet 24j600 getlpMask fetch IP subnet mask UDP port 68 is used as DHCP client port and UDP port 67 is used as DHCP server port tmax time in seconds to wait for an reply 1 network parameters were obtained successfully 0 otherwise Ethernet module has to be initialized See SPI_Ethernet_24j600_Init SPI Ethernet 244600 initDHCP 5 get network configuration from DHCP server wait 5 sec for the response The Ethernet services are not stopped while this routine waits for DNS reply The incoming packets will be processed normaly during this time When DHCP module is used global library variable SPI Ethernet 243600 userTimerSec is used to keep track of time It is user responsibility to increment this variable each second in it s code MikroElektronika 444 mikroPascal PRO for PIC32 SPI_Ethernet_24j600_doDHCPLeaseTime Prototype function SPI Ethernet 245 600 doDHCPLeaseTime byte Description
496. t sub string beginning from the 7th character memset Prototype procedure memset p byte character byte n word Description The function fills the first n words in the memory area starting at the address p with the value of word character For parameter you can use either a numerical value literal variable constant indicating memory address or a dereferenced value of an object for example mystring or PORTB MnikroElektronika memset txt a 2 routine will copy the character a into each of the first n characters of the string txt 587 MikroElektronika mikoPascal PRO for PIC32 strcat Pp procedure strcat var sl s2 string The function appends the value of EM s2 to string s1 and terminates s1 with a null character mikroElektronika ae i mikr 1 ES 8 strcat txt test routine will append the test at the place of the first null character adding terminating null character to the result strcat2 Prototype procedure strcat2 var 11 sl s2 string Description The procedure adjoins string s2 at the end of the string s1 or at the first null character of the s1 and paces the result string into a mikroElektronika an Test ll string 21 streat2 1l txt txt sub routine will adjoin strings txt and txt sub and place the result into 1 1 mikroElektronika Test strchr
497. td gt lt td gt lt script gt document write AN1 script td trot lt table gt lt td gt lt td gt lt table border 1 style font size 20px font family terminal lt tr gt lt th colspan 2 gt PORTB lt th gt lt tr gt SSGript gt WAP Str 4g stra tet Ton S247 lt 1 eee E strt lt tr gt lt td bgcolor pink gt BUTTON it lt td gt if PORTB amp 1 lt lt i strt lt td bgcolor red gt ON else strt td bgcolor cccccc gt OFF Vetere lt tde lt tee F document write str a Seripie 7 const indexPage2 string 466 lt table gt lt td gt lt td gt lt table border 1 style font size 20px font family terminal p tag lt tr gt lt th colspan 3 gt PORTD lt th gt lt tr gt lt script gt Wak stript stra p Stor 2054 lt 650 4 strt lt tr gt lt td bgcolor yellow gt LED it lt td gt if PORTD amp 1 lt lt i str lt td bgcolor red gt ON else strt td bgcolor cccccc gt OFF strt lt td gt lt td gt lt a href t it Toggle a td tr document write str lt seripuS lt table gt lt td gt lt tr gt lt table gt This is HTTP request lt script gt document write REQ lt script gt lt BODY gt lt HTML gt gt var getRequest array 15 of byte HTTP request buffer dyna
498. ter R1 By default the MCU is configured as follows Cache Enabled Prefetch enabled for executable code and constants Flash waitstates set for specified oscillator frequency Executable code allocated in the KSEGO Data allocated in the KSEG1 After this start up function has been executed MCU will jump into the main routine Interupts will be set accordingly to the settings in the Edit Project 167 MikroElektronika mikoPascal PRO for PIC32 PIC32 Memory Organization The PIC32MX microcontrollers provide 4 GB of unified virtual memory address space All memory regions including program memory data memory SFRs and Configuration registers reside in this address space at their respective unique addresses The program and data memories can be optionally partitioned into user and kernel memories In addition the data memory can be made executable allowing the PIC32MX to execute from data memory Key features of PIC32MX memory organization include the following 32 bit native data width Separate User and Kernel mode address spaces Flexible program Flash memory partitioning Flexible data RAM partitioning for data and program space Separate boot Flash memory for protected code Robust bus exception handling to intercept runaway code Simple memory mapping with Fixed Mapping Translation FMT unit Cacheable and non cacheable address regions MikroElektronika 168 mikroPascal PRO f
499. th code and RAM memory due to the mikroPascal PRO for PIC pointer to const and pointer to RAM equivalency Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draws a 10x15 part of the image starting from the upper left corner on the coordinate 10 12 Original image size is 16x32 SPI Gled PartialImage 10 12 10 15 16 32 image Use the mikroPascal PRO for PIC32 integrated Glcd Bitmap Editor Tools gt Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd MikroElektronika 458 mikroPascal PRO for PIC32 Library Example The example demonstrates how to communicate to KS0108 Glcd via the SPI module using serial to parallel convertor MCP238S17 Copy Code To Clipboard program SPI Glcd Port Expander module connections var SPExpanderRST sbit at LATD8 bit SPExpanderCS sbit at LATD9 bit SPExpanderRST Direction sbit at TRISD8 bit SPExpanderCS Direction sbit at TRISD9 bit End Port Expander module connections var someText array 20 of char counter byte procedure Delay2S begin Delay ms 2000 end begin CHECON 0x32 ADIPCFG OxFFFF Configure AN pins as digital If Port Expander Library uses SPI2 module Initialize SPI module used with PortExpander SPI2 Init Advanced SPI MASTER SPI 8 BIT 4 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE LOW SPI ACTIVE 2 IDLE SPI Glcd Init 0 Initiali
500. the assignment operator Special case is conversion between signed and unsigned types Explicit conversion between signed and unsigned data does not change binary representation of data it merely allows copying of source to destination For example var a byte b short b 9 1 a byte b a is 255 not 1 This is because binary representation remains 11111111 it s just interpreted differently now You can t execute explicit conversion on the operand left of the assignment operator word b a Compiler will report an error Conversions Examples Here is an example of conversion program test type TBytePtr byte var arr array 10 of word ptr TBytePLtr var a b cc byte dd word MikroElektronika 212 mikroPascal PRO for PIC32 begin a 241 b i 128 ee mega go equals 113 cc word a b equals 113 dd a bj equals 369 ptr TBytePtr arr ptr byte Qarr end Type Specifier The specifier type introduces a synonym for a specified type The type declarations are used to construct shorter or more convenient names for types already defined by the language or declared by the user The specifier type stands first in the declaration type synonym type definition The type keyword assigns synonym to type definition The synonym needs to be a valid identifier A declaration starting with the type specifier does not introduce an object or a
501. the upper left box corner x1 X coordinate of the lower right box corner y1 y coordinate of the lower right box corner pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE me eem TTE UU Example SPI T6963C box 0 119 239 127 SPI T6963C WHITE T NM m a RR MD M SPI T6963C circle aoe procedure SPI T6963C circle y integer r longint pcolor word Draws a circle on the Glcd Parameters x x coordinate of the circle center y y coordinate of the circle center r radius size pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE meme png ILEIUUECEOEEENLGL Example SPI T6963C circle 120 64 110 SPI 769636 WHITE Ri ie 9 0 E SPI T6963C circle fill Prototype procedure SPI T6963C circle fill x integer y integer r longint pcolor word Draws a filled circle on the Glcd Parameters x x coordinate of the circle center y y coordinate of the circle center r radius size a color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C circle fill 120 64 110 SPI T6963C WHITE MikroElektronika 484 mikroPascal PRO for PIC32 SPI T6963C image Prototype procedure SPI T6963C image pic const byte Description Displays bitmap on Glcd Parameters pic image to be displayed Bitmap
502. tine code is generated in the place of the call so the call doesn t count against the nested call limit Returns Returns next to the lowest byte of number bits 8 15 Arguments must be variable of scalar type i e Arithmetic Types and Pointers 0x12345678 tmp Hi d Equals 0x56 115 MikroElektronika mikoPascal PRO for PIC32 Higher Prototype function Higher number longint byte Description Function returns next to the highest byte of number Function does not interpret bit patterns of number it merely returns 8 bits as found in register This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Parameters number input number Returns Returns next to the highest byte of number bits 16 23 Arguments must be variable of scalar type i e Arithmetic Types and Pointers 0x12345678 tmp Higher d Equals 0x34 Highest Prototype function Highest number longint byte Description Function returns the highest byte of number Function does not interpret bit patterns of number it merely returns 8 bits as found in register This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Parameters number input number Returns Returns the highest byte of number bits 24 31 Arguments must be variable of scalar
503. tion nonzero value if the return is from a call to long jmp this value will be set by the Longjmp routine Description This function saves calling position for a later use by longjmp Parameters env buffer suitable for holding information needed for restoring calling environment var buf array 4 of word Setjmp buf Longjmp Prototype procedure longjmp var env array 4 of word val integer Description Restores calling environment saved in the env buffer by the most recent invocation of setjmp If there has been no such invocation or the function containing the invocation of setjmp has terminated in the interim the behavior is undefined Parameters env buffer holding the information saved by the corresponding set jmp invocation val value to be returned by the corresponding setjmp function Invocation of 1ongjmp must occur before return from the function in which setjmp was called encounters var buf array 4 of word Longjmp buf 2 583 MikroElektronika mikoPascal PRO for PIC32 Library Example Example demonstrates function cross calling using setjmp and longjmp functions When called Setjmp saves its calling environment in its buf argument for later use by the Longjmp Longjmp on the other hand restores the environment saved by the most recent invocation of the Setjmp with the corresponding buf argument Copy Code To Clipboard program Setjmp
504. tion sbit at TRISB2 bit var LCD EN Direction sbit at TRISB3 bit var LCD D4 Direction sbit at TRISB4 bit var LCD D5 Direction sbit at TRISB5 bit var LCD D6 Direction sbit at TRISB6 bit var LCD D7 Direction sbit at TRISB7 bit End LCD module connections var temp real txt array 20 of char Convert ADC value to Celsius degrees format function ADC to degC real begin result ADC1 Get Sample 8 Read ADC value from AN8 pin result 3 25 1024 result 0 5 100 end begin CHECON 0x32 ADIPCFG OXFFF7 Configure AN8 pin as analog I O ADC1 Init Initialize ADC Delay 100ms Lcd Init Initialize LCD Lcd Cmd LCD CLEAR Clear LCD Lcd Cmd LCD CURSOR OFF T rn cursor off Lcd Out 1 1 Temperature while TRUE do begin temp ADC to degC Convert ADC value to Celsius degrees format FloatToStr temp txt Led Chr 2 13 223 Print degree character C for Centigrades 7 Different LCD displays have different char code for degree Lcd Chr 2 14 C If you see greek alpha letter try typing 178 instead of 223 Led Out 2 5 txt Display value on the LCD Delay 1sec 1 second delay end end MikroElektronika 240 mikroPascal PRO for PIC32 CANSPI Library The SPI module is available with a number of the PIC32 MCUs The mikroPascal PRO for PIC32 provides a library driver for working with mikroElektronika s CANSPI Add
505. tion var LCD D6 Direction var LCD D7 Direction sbit sbit sbit sbit sbit sbit day sbit sbit sbit sbit at at at at at at End LCD module connections procedure Read Time begin n a n at at LATB2 bit LATB3 bit LATB4 bit LATB5 bit LATB6 bit LATB7 bit month year byte Global date time variables RF3 bit RF4 bit at TRISF3 bit at TRISF4 bit RISB2 bit RISB3 bit RISB4 bit RISB5 bit RISB6 bit RISB7 bit Reads time and date information from RTC Soft I2C Start Soft I2C Write 0xA0 Soft I2C Write 2 Lh Soft I2C Start Soft I2C Write 0xA1 Z4 seconds Soft I2C Read 1 Ti minutes Soft I2C Read 1 x hours Soft I2C Read 1 day Soft I2C Read 1 14 month Soft I2C Read 0 FF Soft_I2C_Stop end PCF8583 Issue start signal Address PCF8583 see PCF8583 datasheet Start from address 2 Issue repeated start signal Address PCF8583 for reading R W 1 Read seconds byte Read minutes byte Read hours byte Read year day byte Read weekday month byte Issue stop signal 381 MikroElektronika mikoPascal PRO for PIC32 ip eee re e ase sen a Formats date and time procedure Transform Time begin seconds seconds and OxF0 shr 4 10 seconds and 0x0F Transform seconds minutes minutes and OxF0 shr
506. tion numerals are represented as a sequence of digits without commas spaces or dots with optional prefix or operator to indicate the sign Values default to positive 6258 is equivalent to 6258 The dollar sign prefix or the prefix 0x indicates a hexadecimal numeral for example 8F or 0x8F The percent sign prefix indicates a binary numeral for example 201010000 Here are some examples 13 decimal literal 11 hex literal equals decimal 17 0x11 hex literal equals decimal 17 11 binary literal equals decimal 3 The allowed range of values is imposed by the largest data type in mikroPascal PRO for PIC32 1ongint Compiler will report an error if the literal exceeds 2147483647 S7FFFFFFE Floating Point Literals A floating point value consists of Decimal integer Decimal point Decimal fraction e or E and a signed integer exponent optional You can omit either the decimal integer or decimal fraction but not both Negative floating constants are taken as positive constants with the unary operator minus prefixed mikroPascal PRO for PIC32 limits floating point constants to range 1 17549435082 10 38 6 80564774407 1038 Q 0 0 ed 235 1 23 23 45e6 23 45 10 6 2e 5 fi 250 10 5 3E 10 ff 300 10710 09E34 0 09 10 34 181 MikroElektronika mikoPascal PRO for PIC32 Character Literals Character literal is one character fro
507. tional Operators in Expressions Precedence of arithmetic and relational operators is designated in such a way to allow complex expressions without parentheses to have expected meaning at 5 gt c 1 0 e fi a S S Ce 0 97 MikroElektronika 216 mikroPascal PRO for PIC32 Bitwise Operators Use bitwise operators to modify individual bits of numerical operands Bitwise operators associate from leftto right The only exception is the bitwise complement operator not which associates from right to left Bitwise Operators Overview bitwise AND compares pairs of bits and returns 1 if both bits are 1 otherwise it returns 0 or bitwise inclusive OR compares pairs of bits and generates a 1 result if either or both bits are 1 otherwise it returns 0 bitwise exclusive OR XOR compares pairs of bits and generates a 1 resultifthe bits are complementary otherwise it returns 0 bitwise complement unary inverts each bit shl bitwise shift left moves the bits to the left discards the far left bit and assigns 0 to the right most bit shr bitwise shift right moves the bits to the right discards the far right bit and if unsigned assigns 0 to the left most bit otherwise sign extends Logical Operations on Bit Level Bitwise operators and or and xor perform logical operations on the appropriate pairs of bits of their operands The operator not complements each bit of its operand For example 1234 and 5678 equ
508. tional compiler constant flag You can use any identifier for a flag with no limitations No conflicts with program identifiers are possible because the flags have a separate name space Only one flag can be set per directive For example SDEFINE Extended format Use SUNDEFINE to undefine clear previously defined flag Note Pascal does not support macros directives DEFINE and S UNDEFINE do not create destroy macros They only provide flags for directive 5 1 FDEF to check against Directives IFDEF IFNDEF ELSE and ENDIF Conditional compilation is carried out by the SIFDEF and IFNDEF directives 1FDEF tests whether a flag is currently defined and IFNDEF if the flag is not defined i e whether a previous SDEF INE directive has been processed for that flag and is still in force Directives STFDEF and STFNDEF are terminated with the ENDIF directive and can have an optional ELSE clause SIFDEF flag block of code SELSE alternate block of code SENDIF First SIFDEF checks if flag is defined by means of SDEFINE If so only block of code will be compiled Otherwise alternate block of code will be compiled SENDIF ends the conditional sequence The result of the preceding scenario is that only one section of code possibly empty is passed on for further processing The
509. tioned are the property of their respective owners 33 MikroElektronika mikoPascal PRO for PIC32 Fill out the registration form select your distributor and click the Submit button If you choose work offline registering method following window will be opened B How To Register Step 1 Fill in the form below Please make sure you fill in all required fields Step 2 Make sure that you provided a valid email address in the EMAIL edit box This email will be used for sending you the activation key Step 3 Make sure you select a correct distributor which will make the registration process faster If your distributor is not on the list then select Other and type in distributor s email address in the box below Step 4 Press the SEND button to send key request A default email client will open with ready to send message Note If email client does not open you may copy text of the message and paste it manually into a new email message before sending it to your distributor s email NAME John Smith your address ckOut Order Number or i e number if available 10 characters ozs jsmith example com e 3F47 546774 7F6A73 684DF Enter comments on your order DISTRIBUTOR mikroElektronika key mikroe com b Name John Smith Address Invoice number Ba Copy to clipboard Fill out the registration form select your distributor and click the Submit button This will start your e
510. tions oo o O E Build current project r1 Build all opened projects Build and program active project Start programmer and load current HEX file 11 MikroElektronika mikoPascal PRO for PIC32 Debug Toolbar Debug Toolbar comes with the following options Ten SSCS eto SSOSCS S SCS Eh Sart Sotware simiatorormioteD r creutDebuager O B sposo i O Ba ser Step Over E3 Step Out Dc LIC R LITTERE Styles Toolbar Styles toolbar allows you to easily change colors of your workspace Office 2003 Blue Office 2003 Blue Office 2003 Silver Office 2003 Olive Office XP 1 Chocolate Arctic Silverfox Soft sand MikroElektronika 18 mikroPascal PRO for PIC32 Tools Toolbar Tools Toolbar comes with the following default options E Run USART Terminal A EEPROM ASCII Chart CI Seven Segment Editor Open Active Comment editor apee o Tip The Tools toolbar can easily be customized by adding new tools in Options menu window View Toolbar ia fn View Toolbar provides access to assembly code listing file and statistics windows C erption SOS Open assembly code in editor FJ Open listing file in editor View statistics for current project 19 MikroElektronika mikoPascal PRO for PIC32 Layout Toolbar Styles toolbar allows you to easily customize workspace through a number of different IDE layouts Help Toolbar
511. ts Blocks Compound statement or block is a list of statements enclosed by keywords begin and end begin Statements end Syntactically a block is considered to be a single statement which is allowed to be used when Pascal syntax requires a single statement Blocks can be nested up to the limits of memory For example the while loop expects one statement in its body so we can pass it a compound statement while i n do begin temp a i ala t 5 i j b i temp i se Xi end Conditional Statements Conditional or selection statements select one of alternative courses of action by testing certain values There are two types of selection statements if case 223 MikroElektronika mikoPascal PRO for PIC32 If Statement Use the keyword if to implement a conditional statement The syntax of the if statement has the following form if expression then statementl else statement2 If expression evaluates to true then statement executes If expression is false then statement2 executes The expression must convert to a boolean type otherwise the condition is ill formed The else keyword with an alternate statement statement 2 is optional There should never be a semicolon before the keyword else Nested if statements Nested if statements require additional attention A general rule is that the nested conditionals are parsed starting from the innermost conditional with each else bound to the neares
512. ts cursor to row x and column y Parameters x cursor position row number y cursor position column number UCM o oOo UUU Example T6963C set cursor cposx cposy etes None T6963C displayGrPanel Rems Noting SSCS mee reese aelaersetay OOO O T6963C displayGrPanel 1 T6963C_displayTxtPanel Remum NM OOO Toshiba Glcd module needs to be initialized See the T6963C init routine display text panel 1 T6963C displayTxtPanel 1 911 MikroElektronika mikoPascal PRO for PIC32 T6963C_setGrPanel Description Compute start address for selected graphic panel and set appropriate internal pointers All subsequent graphic operations will be preformed at this graphic panel n graphic panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See the T6963C init routine set graphic panel 1 as current graphic panel T6963C setGrPanel 1 T6963C setTxtPanel text unus will be lus at this text panel Retums Wan 00000 WE scenerenencns PM T6963C_setTxtPanel 1 T6963C_panel Fill ums Noting OOOO Toshiba Glcd module needs to be initialized See the T6963C init routine clear current panel T6963C panelFill 0 Notes Nm 0 MikroElektronika 512 mikroPascal PRO for PIC32 T6963C grFill Rems NM SOS Toshiba Glcd module needs to be initialized See the T6963C init routine clear current graphic panel T6963C grFill 0 T6963C txtFill
513. ts gt lt opts gt Infile can be of c emcl and pld type The following parameters are valid P devicename MCU for which compilation will be done FO oscillator Set oscillator in MHz SP directory Add directory to the search path list filename Output files generated to file path specified by filename B directory Save compiled binary files emc1 to directory O Miscellaneous output options DBG Generate debug info SF Short message format Y Dynamic link for string literals RA Rebuild all sources in project L Check and rebuild new libraries DL Build all files as libraries HF Generate Long hex format F Project file name H filename Full EEPROM HEX file name with path EAP lt size gt Heap size in bytes Gc Generate COFF file PF Project file name SSA Enable SSA optimization UICD ICD build type INTDEF Interrupt settings EBASE Exception base address mT Aawe m MikroElektronika mikoPascal PRO for PIC32 Example mPPIC32 exe MSF DBG p32MX460F512L Y DL 011111114 fo80 N C Lcd Lcd mpp32 SP C Program Files Mikroelektronika mikroPascal PRO for PIC32 Defs SP C Program Files Mikroelektronika mikroPascal PRO for PIC32 Uses SP C Led Lib Math emcl Lib MathDouble emcl Lib System emcl Lib Delays emcl Lib LcdConsts emcl Lib Lcd emcl Lcd mpas Pa
514. ttings are not valid otherwise returns calculated timer period MCU must have the HW PWM Module Notes Number of available PWM channels depends on MCU Refer to MCU datasheet for details 303 MikroElektronika mikoPascal PRO for PIC32 PWM_Set_Duty Prototype procedure PWM Set Duty duty channel word The function changes PWM duty ratio Parameters duty PWM duty ratio Valid values 0 to timer period returned by the PWM_Init function channel number of PWM channel to change duty to Requires MCU must have the HW PWM Module PWM channel must be properly initialized See PWM Init routine Set channel 1 duty ratio to 508 var pwm periodl word PWM Set Duty pwm periodi div 2 1 Notes Number of available PWM channels depends on MCU Refer to MCU datasheet for details PWM Start Prototype procedure PWM Start enable channel x byte Starts PWM at requested channel enable channel x number of PWM channel Requires MCU must have the HW PWM Module PWM channel must be properly configured See the PWM Init and PWM Set Duty routines start PWM at channel 1 PWM Start 1 Notes Number of available PWM channels depends on MCU Refer to MCU datasheet for details PWM Stop Prototype procedure PWM Stop disable channel x byte Stops PWM at requested channel disable channel x number of PWM channel MCU must have the HW PWM Module stop PWM at channel 1 P
515. type procedure T6963C_init width height fntW word Description Initalizes the Graphic Lcd controller Display RAM organization The library cuts the RAM into panels a complete panel is one graphics panel followed by a text panel see schematic below PANEL 1 Parameters width width of the Glcd panel height height of the Glcd panel ntW font width ro9e3c ctrl 6963 etri Lo963C ctrl l6963C ctrl r6963C ctrl L6963C ctrl Lr6963C ctrl 6963C cert 6963C_dataPort Data Port wr Write signal pin rd Read signal pin cd Command Data signal pin rst Reset signal pin wr Direction Direction of Write signal pin rd Direction Direction of Read signal pin cd Direction Direction of Command Data signal pin rst Direction Direction of Reset signal pin must be defined before using this function 901 MikroElektronika mikoPascal PRO for PIC32 T6963C module connections var T6963C dataPort byte at PORTB DATA port var T6963C ctrlwr sbit at LATF2 bit WR write signal var T6963C ctrird sbit at LATF1 bit RD read signal var T6963C ctrlcd sbit at LATFO bit CD command data signal var T6963C ctrlrst sbit at LATF4 bit RST reset signal var T6963C ctrlwr Direction sbit at TRISF2 bit WR write signal direction var T6963C ctrlrd Direction sbit at TRISF1 bit RD read signal direction var T6963C ctricd Direction sb
516. uested baud rate is too high 0 successful initialization This will initialize software UART and establish the communication at 9600 bps Initialize Software UART communication on pins RF2 Rx RF3 Tx at 14400 bps Soft UART Init PORTF 2 3 14400 0 The Software UART library implements time based activities so interrupts need to be disabled when using it 387 MikroElektronika mikoPascal PRO for PIC32 Soft_UART_Read Prototype function Soft UART Read var error byte byte Description The function receives a byte via software UART This is a blocking function call waits for start bit Programmer can unblock it by calling Soft UART Break routine Parameters error Error flag Error code is returned through this variable Values 0 no error 1 stop bit error 255 user abort Soft UART Break called Byte received via UART Requires Software UART must be initialized before using this function See the Soft UART Init routine var data byte error word wait until data is received repeat data Soft UART Read error until error 0 Now we can work with data if data then begin end The Software UART library implements time based activities so interrupts need to be disabled when using it Soft UART Write ems nonn Requires Software UART must be initialized before using this function See the Soft UART Init routine Be aware that duri
517. ugh this parameter Requires MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init The file must be previously assigned See Mmc Fat Assign The file must be opened for reading See Mmc Fat Reset var character byte Mmc Fat Read character MikroElektronika 394 mikroPascal PRO for PIC32 Mmc Fat Rewrite Requires MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init The file must be previously assigned See Mmc Fat Assign open file for writing Mmc Fat Rewrite None Mmc Fat Append Prototype procedure Mmc Fat Append Description Opens the currently assigned file for appending Upon this function execution file pointers will be positioned after the last byte in the file so any subsequent file write operation will start from there Nothing Requires MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init The file must be previously assigned See Mmc Fat Assign open file for appending Mmc Fat Append None Mmc Fat Delete Requires MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init The file must be previously assigned See Mmc Fat Assign delete current file Mmc Fat Delete None 339 MikroElektronika mikoPascal PRO for PIC32 Mmc_Fat_Write Prototype procedure Mmc Fat Write var fdata array 512 of byte data len
518. ule with default settings This function enables the I C module by setting the I2CEN bit The rest of the bits in I C control register remains unchanged Default initialization after reset of IC module is Continue operation in IDLE mode T bit slave address Slew rate control enabled for High Speed mode 400 kHz General call address disabled SCL clock stretching disabled As per the I C standard SCL clock may be 100 kHz or 400 kHz However the user can specify any clock rate up to 1 MHz scl requested serial clock rate MCU with the lC module Initialize the I2C1 module with clock rate of 100000 I2C1 Init 100000 Refer to the MCU s datasheet for correct values of the scl in respect with Fosc lC library routines require you to specify the module you want to use To select the desired C module simply change the letter x in the routine prototype for a number from 1 to 3 Number of I C modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 308 mikroPascal PRO for PIC32 I2Cx Init Advanced Prototype procedure I2Cx Init Advanced Fclk Khz scl dword Description This function configures and initializes the desired I C module using Peripheral Bus Clock and default initialization settings As per the lC standard SCL clock may be 100 kHz or 400 kHz However the user can specify any clock rate up to 1 MHz Par
519. ult I2C2 Read 1 Read the data NO acknowledge I2C2 Stop end begin CHECON 0x30 ADIPCFG OxFFFFFFFF LATB 0 Set PORTB value to zero TRISB 0 Configure PORTB as output TRISA 0 TRISD 0 LATD 0 LATF 0 TRISF 0 EEPROM 24C02 Init performs I2C initialization b 0x00 for i 0x00 to 0x80 do begin EEPROM 24C02 WrSingle i b Incib s Delay ms 5 max vrednost za upis u eeprom end for i 0x00 to 0x80 do begin LATD i LATB EEPROM 24C02 RdSingle i Delay ms 100 end end 313 MikroElektronika mikoPascal PRO for PIC32 Keypad Library mikroPascal PRO for PIC32 provides a library for working with 4x4 keypad The library routines can also be used with 4x1 4x2 or 4x3 keypad For connections explanation see schematic at the bottom of this page External dependencies of Keypad Library The following variable must be defined i A 4 Description in all projects using Keypad Library var keypadPort word sfr Keypad Port var keypadPort byte at PORTB external yp Yp Y var keypadPort_Direction word var keypadPort Direction byte at sfr external Keypad Port TRISB Library Routines Keypad Init Keypad Key Press Keypad Key Click Keypad Init Reums Nang SSCS Requires Global variable keypadPort Keypad port must be defined before using this function Keypad module connections var keypadP
520. ult result SPI Ethernet putString Qtmp add PORTD value LEDs to reply tmp var PORTD result result SPI Ethernet putString Qtmp WordToStr PORTD dyna result result SPI Ethernet putString dyna tmp i 7 result result SPI_Ethernet_putString tmp add HTTP requests counter to reply WordToStr httpCounter var REQ result SPI Ethernet _putString tmp result SPI Ethernet _putString dyna tmp result result tmp result end else if getRequest 5 with t begin bitMask 0 dyna Ves 3 result SPI Ethernet putString tmp t then toggle PORTD LED bit number that comes after if isdigit getRequest 6 lt gt 0 then bits 8 amp 9 does not exist but does not matter begin bitMask getRequest 6 10 gt HTTP header with if request path name starts if 0 lt bit number lt 9 convert ASCII to integer 423 MikroElektronika mikoPascal PRO for PIC32 bitMask 1 shl bitMask create bit mask LATD PORTD xor bitMask toggle PORTD with xor operator end end if result 0 then what do to by default begin result SPI Ethernet putConstString Q0httpHeader HTTP header result result SPI Ethernet putConstString 8httpMimeTypeHTML with HTML MIME type result result SPI Ethernet _putConstString indexPage HTML page first p
521. unit any function or procedure Visibility The visibility of an identifier is that region of the program source code from which legal access to the identifier s associated object can be made Scope and visibility usually coincide though there are circumstances under which an object becomes temporarily hidden by the appearance of a duplicate identifier i e the object still exists but the original identifier cannot be used to access it until the scope of the duplicate identifier is ended Technically visibility cannot exceed scope but scope can exceed visibility 189 MikroElektronika mikoPascal PRO for PIC32 Name Spaces Name space is a scope within which an identifier must be unique The mikroPascal PRO for PIC32 uses two distinct categories of identifiers 1 Global variables are visible throughout the whole unit from the place of declaration Also they can be seen in other units if they are declared above the Implementation section 2 Local variables parameters types function results must be unique within the block in which they are declared For example var level byte procedure control sens byte var location byte begin location 1 sens location level 123 end procedure temperature begin location 0 ILLEGAL sens 23 ILLEGAL redefinition of sens level 95 end MikroElektronika 190 mikroPascal PRO for PIC32 Units In mikroPasca
522. urrence from the memory address p or OxFFFF if ch was not found For the parameter p you can use either a numerical value literal variable constant indicating memory address or a dereferenced value of an object for example mystring or PORTB E mikroElektronika res memchr txt e 16 example locates first occurrence of the letter e in the string txt in the first 16 characters of the string memcmp Prototype function memcmp pl p2 byte n word integer Description The function returns a positive negative or zero value indicating the relationship of first n words of memory areas starting at addresses p1 and p2 This function compares two memory areas starting at addresses p1 and p2 for n words and returns a value indicating their relationship as follows Value Meaning 0 pl less than p2 pl equal to p2 gt 0 pl greater than p2 The value returned by the function is determined by the difference between the values of the first pair of words that differ in the strings being compared For parameters p1 and p2 you can use either a numerical value literal variable constant indicating memory address or a dereferenced value of an object for example mystring or PORTB txt mikroElektronika txt sub i mrkro res memcmp G8txt Gtxt sub 16 returns 69 which is ASCII code of the first differing character letter E MikroElektronika 586
523. urrent text panel of Glcd at coordinates x y x dot position on x axis y dot position on y axis color color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C dot x0 yO SPI T6963C BLACK SPI T6963C write char Prototype procedure SPI T6963C write char c x y mode byte Writes a char in the current text panel of Glcd at coordinates x y Parameters c char to be written x char position on x axis y char position on y axis node mode parameter Valid values SPI T6963C ROM MODE OR SPI T6963C ROM MODE XOR SPI T6963C ROM MODE AND and SPI T6963C ROM MODE TEXT Mode parameter explanation OR Mode In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in negative mode i e white text on black background AND Mode The text and graphic data shown on display are combined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet Toshiba Glcd module needs to be initialized S
524. using CANSPI Description Library var CanSpi CS sbit sfr r var CanSpi CS sbit at external Chip selectins LATFO bit var CanSpi Rst sbit sfr Reset line var CanSpi Rst sbit at external Ho LATEL bit var CanSpi CS Direction gt var CanSpi CS Direction sbit sfr external Direction aptae Chip Seleer pin sbit at TRISFO bit var CanSpi Rst Direction d var CanSpi Rst Direction Sbit sfr external Direction or thie Reset pin sbit at TRISF1 bit 221 MikroElektronika mikoPascal PRO for PIC32 Library Routines CANSPISetOperationMode CANSPIGetOperationMode CANSPIInit CANSPISetBaudRate CANSPISetMask CANSPISetFilter CANSPIRead CANSPIWrite CANSPISetOperationMode Prototype procedure CANSPISetOperationMode mode byte WAIT byte Sets the CANSPI module to requested mode Parameters mode CANSPI module operation mode Valid values CANSPI OP MODE constants See CANSPI _ OP MODE constants WAIT CANSPI mode switching verification request If WAIT 0 the call is non blocking The function does not verify if the CANSPI module is switched to requested mode or not Caller must use CANSPIGetOperationMode to verify correct operation mode before performing mode specific operation If WATT 0 the call is blocking the function won t return until the requested mode is set Requires The CANSPI routines are supported only by MCUs with the SPI module MCU
525. ut Toolbar Help Toolbar MikroElektronika A mikroPascal PRO for PIC32 File Toolbar 5 File Toolbar is a standard toolbar with the following options Die o LB Opens a new editor window Open source file for editing or image file for viewing nl Save changes for active window Save changes in all opened windows Edit Toolbar Edit Toolbar is a standard toolbar with the following options S BeeWplan e Undo last change E3 Redo last change Cut selected text to clipboard Copy selected text to clipboard Paste text from clipboard 15 MikroElektronika mikoPascal PRO for PIC32 Advanced Edit Toolbar Advanced Edit Toolbar comes with the following options Icon DIT C X S LIT C S a Generate HTML code suitable for publishing current source code on the web Find Replace Toolbar D222 Find Replace Toolbar is a standard toolbar with the following options r Find text in current editor FUR Franextoseurenoe O O r1 Replace text Find text in files MikroElektronika 16 mikroPascal PRO for PIC32 Project Toolbar Project Toolbar comes with the following options Don BesHpies New project Open Project Save Project UNI Edit project settings Close current project Clean project folder n Add File To Project Remove File From Project Build Toolbar a ME Build Toolbar comes with the following op
526. ut different from T6369C datasheets Appropriate relations between these labels are given in the table below Adapter Board T6369C datasheet Library Dependency Tree m gt Port Expander SPI T6963C Gicd Trigonometry External dependencies of SPI T6963C Graphic Lcd Library The implementation of SPI T6963C Graphic Lcd Library routines is based on Port Expander Library routines External dependencies are the same as Port Expander Library external dependencies 475 MikroElektronika mikoPascal PRO for PIC32 Library Routines SPI T6963C config SPI T6963C writeData SPI T6963C writeCommand SPI T6963C setPtr SPI T6963C waitReady SPI T6963C fill SPI T6963C dot SPI T6963C write char SPI T6963C Write Text SPI T6963C line SPI T6963C rectangle SPI T6963C rectangle round edges SPI T6963C rectangle round edges fill SPI T6963C box SPI T6963C circle SPI T6963C circle fill SPI T6963C image SPI T6963C Partiallmage SPI T6963C sprite SPI T6963C set cursor SPI T6963C clearBit SPI T6963C setBit SPI T6963C negBit SPI T6963C displayGrPanel SPI T6963C displayTxtPanel SPI T6963C setGrPanel SPI T6963C setTxtPanel SPI T6963C panelFill SPI T6963C grFill SPI T6963C txtFill SPI T6963C cursor height SPI T6963C graphics SPI T6963C text SPI T6963C cursor SPI T6963C cursor blink MikroElektronika 416 mikroPascal PRO f
527. utine see Available SPI Lcd8 Commands ani MikroElektronika mikoPascal PRO for PIC32 Available SPI Lcd8 Commands Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected Library Example This example demonstrates how to communicate Lcd in 8 bit mode via the SPI module using serial to parallel convertor MCP23S17 Copy Code To Clipboard program SPI Lcd8 var text array 16 of char var counter byte Port Expander module connections var SPExpanderRST sbit at LATD8 bit SPExpanderCS sbit at LATD9 bit SPExpanderRST Direction sbit at TRISD8 bit SPExpanderCS Direction sbit at TRISD9 bit End Port Expander module connections procedure Move Delay Function used for text moving begin Delay ms 500 You can change the moving speed here end begin CHECON 0x32 ADIPCFG OxFFFF Configure AN pins as digital text mikroElektronika MikroElektronika 412 mikroPascal PRO for PIC32 If Port Expander Library uses SPI2 module Initialize SPI module used with PortExpander SPI2 Init Advanced SPI MASTER SPI 8 BIT 4 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE LOW SPI ACTIVE 2 IDLE SPI Lcd8 Config 0 Initialize Lcd over SPI interface SPI Lcd8 Cmd LCD CLEAR Clear display SPI Lcd8 Cm
528. west subpriority to 3 the highest Interrupts and Register Sets The PIC32MX family of devices employs two register sets a primary register set for normal program execution and a shadow register set for highest priority interrupt processing Register Set Selection in Single Vector Mode In Single Vector mode you can select which register set will be used By default the interrupt controller will instruct the CPU to use the first register set This can be changed later in the code Interrupts and Register Sets When a priority level interrupt matches a shadow set priority the interrupt controller instructs the CPU to use the shadow set For all other interrupt priorities the interrupt controller instructs the CPU to use the primary register set Interrupt Coding Requirements In order to correctly utilize interrupts and correctly write the ISR code the user will need to take care of these things 1 Write the Interrupt Service Routine You may use Interrupt Assistant to easily write this routine 2 Initialize the module which will generate an interrupt 3 Set the correct priority and subpriority for the used module according to the priorities set in the Interrupt Service Routine 4 Enable Interrupts Interrupt Service Routine Interrupt service routine is defined in this way procedure interrupt iv IVT ADC ilevel 7 ics ICS SOFT begin Interrupt service routine code end 139 MikroElektronika mikoPascal PRO
529. when DHCP is not used Parameters ipMask IP subnet mask gwIpAddr gateway IP address dnsIpAddr DNS IP address Nothing Ethernet module has to be initialized See SPI Ethernet 24j600 Init va ipMask array 4 of byte network mask for example 255 255 255 0 gwlIpAddr array 4 of byte gateway router IP address dnsIpAddr array 4 of byte DNS server IP address gwlIpAddr 0 gwipAddr 1 gwlpAddr 2 gwlpAddr 3 192 168 205 6 dnsIpAddr dnsIpAddr dnsIpAddr dnsIpAddr 192 168 20 100 2554 2597 2557 0 Ethernet 243600 confNetwork ipMask gwIpAddr dnsIpAddr network configuration parameters The above mentioned network parameters should be set by this routine only if DHCP module is not used Otherwise DHCP will override these settings MikroElektronika mikoPascal PRO for PIC32 SPI_Ethernet_24j600_arpResolve Prototype function SPI Ethernet 245 600 arpResolve var ip array 4 of byte tmax byte word Description This is ARP module routine It sends an ARP request for given IP address and waits for ARP reply If the requested IP address was resolved an ARP cash entry is used for storing the configuration ARP cash can store up to 3 entries Parameters i IP address to be resolved tmax time in seconds to wait for an reply MAC address behind the IP address the requested IP address was resolved 0 otherwise Ethernet module has to be initi
530. will assume string type MONTHS array 1 12 of byte 31 28 31 30 31 30 31 31 30 31 30 31 195 MikroElektronika mikoPascal PRO for PIC32 Labels Labels serve as targets for goto statements Mark the desired statement with a label and colon like this label identifier statement Before marking a statement you must declare a label Labels are declared in declaration part of unit or routine similar to variables and constants Declare labels using the keyword label1 label labell labeln Name of the label needs to be a valid identifier The label declaration marked statement and goto statement must belong to the same block Hence it is not possible to jump into or out of a procedure or function Do not mark more than one statement in a block with the same label Here is an example of an infinite loop that calls the Beep procedure repeatedly label loop loop Beep goto loop Note Label should be followed by end of line CR otherwise compiler will report an error label loop loop Beep compiler will report an error loop compiler will report an error MikroElektronika 196 mikroPascal PRO for PIC32 Functions and Procedures Functions and procedures collectively referred to as routines are subprograms self contained statement blocks which perform a certain task based on a number of input parameters When executed a function returns a value while procedure does not Functions A functi
531. wnloading from our website It is a fully functional software with the mikrolCD in circuit Debugger all the libraries examples and comprehensive help included The only limitation of the free version is that it cannot generate hex output over 2K of program words Although it might sound restrictive this margin allows you to develop practical working applications with no thinking of demo limit If you intend to develop really complex projects in the mikroPascal PRO for PIC32 then you should consider the possibility of purchasing the license key Who Gets the License Key Buyers of the mikroPascal PRO for PIC32 are entitled to the license key After you have completed the payment procedure you have an option of registering your mikroPascal PRO for PIC32 In this way you can generate hex output without any limitations How to Get License Key After you have completed the payment procedure start the program Select Help How to Register from the drop down menu or click the How To Register Icon 2 You can choose between two registering methods work online or work offline based on your current internet connection and click Request license key now button MikroElektronika 32 mikroPascal PRO for PIC32 How to register Choose registration method f work online Choose this option if you are connected to internet You will be directed to a web page which will help you o send the license key request This is the
532. word Writes requested number of bytes to the currently assigned file opened for writing Parameters fdata data to be written data len number of bytes to be written Requires MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init The file must be previously assigned See Mmc Fat Assign The file must be opened for writing See Mmc Fat Rewrite or Mmc Fat Append var file contents array 42 of byte Mme Fat_Write file_contents 42 write data to the assigned file Mmc_Fat_Set_File_Date Prototype procedure Mmc Fat Set File Date year word month byte day byte hours byte mins byte seconds byte Description Sets the date time stamp Any subsequent file write operation will write this stamp to the currently assigned file s time date attributes Parameters year year attribute Valid values 1980 2107 month month attribute Valid values 1 12 day day attribute Valid values 1 31 hours hours attribute Valid values 0 23 mins minutes attribute Valid values 0 59 seconds seconds attribute Valid values 0 59 Requires MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init The file must be previously assigned See Mmc_Fat_Assign The file must be opened for writing See Mmc_Fat_Rewrite or Mmc_Fat_Append April 1st 2005 18 07 00 Mmc Fat Set File Date 2005 MikroElektronika 336 mikroPascal PRO for
533. writing to files but the file data is being read from the FAT table only i e there is no recovery if the FAT1 table gets corrupted If MMC SD card has Master Boot Record MBR the library will work with the first available primary logical partition that has non zero size If MMC SD card has Volume Boot Record i e there is only one logical partition and no MBRs the library works with entire card as a single partition For more information on MBR physical and logical drives primary secondary partitions and partition tables please consult other resources e g Wikipedia and similar Before write operation make sure you don t overwrite boot or FAT sector as it could make your card on PC or digital camera unreadable Drive mapping tools such as Winhex can be of a great assistance Library uses SPI module for communication The user must initialize the appropriate SPI module before using the MMC Library For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by using the SPI Set Active function See the SPI Library functions The SPI module has to be initialized through SPIx_ Init Advanced routine with the following parameters SPI Master 8bit mode secondary prescaler 1 primary prescaler 64 Slave Select disabled data sampled in the middle of data output time clock idle high Serial output data changes on transition from active clock state to idle clock state Tip
534. ws MikroElektronika 42 mikroPascal PRO for PIC32 Show Hide Software Simulator mikroICD In Circuit Debugger Debug Windows rcc scc a rc acc Eo cum The Tools toolbar can easily be customized by adding new tools in Options F12 window Related topics Keyboard shortcuts Integrated Tools 43 MikroElektronika mikoPascal PRO for PIC32 Project Project Menu Options Project Menu allows the user to easily manipulate current project New Project Shift Ctrl N Open Project Shift Ctri O Open Project Group Recent Projects Save Project Save Project As Close Project Close Project Group J Add File To Project f Remove File From Project Edit Search Paths Import Project Ctrl I Edit Project Shift Ctrl E Clean Project Folder Import Project Ctrl I Export Project Ctr Alt E C Fees Besplon a aeons rr Coo al rc Related topics Keyboard shortcuts Project Toolbar Creating New Project Project Manager Project Settings MikroElektronika 44 mikroPascal PRO for PIC32 Build Build Menu Options Build Menu allows the user to easily manage building and compiling process M Build Ctrl F9 Rebuild All Sources Alt F9 Build All Projects Shift F9 Stop Build All Ctri F12 Build Program Ctrl
535. xOD1F IVT SPI 2 VECTOR 0x0020 IVT_UART_2_ VECTOR 0x0021 IVT I2C 2 VECTOR 0x0022 IVT FAIL SAFE MONITOR VECTOR 0x0023 IVT RTCC VECTOR fixfini24 WT DMA N VECTOR L only used By checking the Only Used box you can display only the used breakpoints MikroElektronika 104 mikroPascal PRO for PIC32 Regular Expressions Introduction Regular Expressions are a widely used method of specifying patterns of text to search for Special metacharacters allow you to specify for instance that a particular string you are looking for occurs at the beginning or end of a line or contains n recurrences of a certain character Simple matches Any single character matches itself unless it is a metacharacter with a special meaning described below A series of characters matches that series of characters in the target string so the pattern short would match short in the target string You can cause characters that normally function as metacharacters or escape sequences to be interpreted by preceding them with a backslash For instance metacharacter matches beginning of string but matches character and matches V etc Examples unsigned matches string unsigned unsigned matches string unsigned Escape sequences Characters may be specified using an escape sequences n matches a newline Nt a tab etc More generally xnn where nn is a string of hexadecimal
536. xample demonstrates simple data exchange via UART If MCU is connected to the PC you can test the example from the mikroPascal PRO for PIC32 USART communication terminal launch it from the drop down menu Tools USART Terminal or simply click the USART Terminal Icon Copy Code To Clipboard program UARTI var uart rd byte begin CHECON 0x32 ADIPCFG OxFFFF UART1 Init 56000 Delay ms 100 UART1 Write Text Start UART1 Write 13 UART1 Write 10 Hl Configure AN pins as digital I O Initialize UART module at 56000 bps Wait for UART module to stabilize while TRUE do Endless loop begin if UART1 Data Ready lt gt 0 then If data is received begin uart rd UART1 Read read the received data UART1 Write uart rd and send data via UART end end end MikroElektronika mikroPascal PRO for PIC32 HW Connection SUB D 9p Receive data Rx CONNECT MCU TO PC Send CONNECT Data Tx PC TO MCU veca nna nnnnnnannnnnnannnnnnnn vecs SUB D 9p OSCILLATOR GND o VCC3 UTGUUUUDUUUUTUUUUUUUUUUUU RS232 HW connection 561 MikroElektronika mikoPascal PRO for PIC32 USB Library Universal Serial Bus USB provides a serial bus standard for connecting a wide variety of devices including computers cell phones game consoles PDAs etc USB Library contains HID routines that support H
537. xpander s PORTA to be output Expander Set DirectionPortB 0 0xFF Set Expander s PORTB to be input Expander Set PullUpsPortB 0 0xFF Set pull ups to all of the Expander s PORTB pins while TRUE do Endless loop begin Expander Write PortA 0 counter Write i to expander s PORTA Inc counter PORTB Expander Read PortB 0 Read expander s PORTB and write it to LEDs Delay ms 75 end end MikroElektronika 396 mikroPascal PRO for PIC32 HW Connection ovcca ovcca Port Expander HW connection 39 MikroElektronika mikoPascal PRO for PIC32 PS 2 Library The mikroPascal PRO for PIC32 provides a library for communication with the common PS 2 keyboard Important The library does not utilize interrupts for data retrieval and requires the oscillator clock to be at least 6MHz The pins to which a PS 2 keyboard is attached should be connected to the pull up resistors Although PS 2 is a two way communication bus this library does not provide MCU to keyboard communication e g pressing the Caps Lock key will not turn on the Caps Lock LED External dependencies of PS 2 Library The following variables must be defined Dax rintion in all projects using PS 2 Library p external zd PS2 Clock 3 bit fr 3 jen ci fot 777 PS 2 Clock line var PS2 Clock sbit at RBl bit external ES var PS2 Data Direction sbit var PS2
538. y file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between the file name and extension i e MIKROELETXT gt MIKROELE TXT In this case the last 3 characters of the string are considered to be file extension file attr file creation and attributes flags Each bit corresponds to the appropriate file attribute MikroElektronika 210 mikroPascal PRO for PIC32 E COC Besipim Number of the start sector for the newly created swap file if there was enough free space on CF card to create file of required size 0 otherwise CF card and CF library must be initialized for file operations See Cf Fat Init Try to create a swap file with archive atribute whose size will be at least 1000 sectors ay If it succeeds it sends the No of start sector over UART var size dword size Cf Fat Get Swap File 1000 mikroE txt 0x20 if size lt gt 0 then begin UART1 Write 0xAA UART1 Write Lo size UART1 Write Hi size VARTI Write Higher size VARTI Write Highest size VARTI Write 0xAA end Long File Names LFN are not supported 271 MikroElektronika mikoPascal PRO for PIC32 Library Example This project consists of several blocks that demonstrate various aspects of usage of the Cf Fat16 library These are Creation of new file and writing down to it Opening existing file and re writing it writing from start of fi
539. y axis mode mode parameter Valid values T6968C ROM MODE OR T6963C ROM MODE XOR T6963C ROM MODE AND and T6963C ROM MODE TEXT Mode parameter explanation OR Mode In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in the negative mode i e white text on black background AND Mode The text and graphic data shown on display are combined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C write char A 22 23 T6963C ROM MODE AND MikroElektronika mikoPascal PRO for PIC32 T6963C_write_text Prototype ti M T6963C write text var str array 10 of byte x y mode byte Writes text in the current text panel of Glcd at coordinates x y Parameters str text to be written x text position on x axis y text position on y axis mode mode parameter Valid values T6963C ROM MODE OR T6963C ROM MODE XOR T6963C ROM MODE AND and T6963C ROM MODE TEXT Mode parameter explanation OR Mode In t
540. y lasts for x 16384 y MCU clock cycles Parameters x NumberOfCycles divided by 16384 y remainder of the NumberOfCycles 16384 division Example Delay Cyc 1 10 1x16384 10 16394 cycles pause Delay Cyc isa library function rather than a built in routine it is presented in this topic for the sake of convenience 191 MikroElektronika mikoPascal PRO for PIC32 Delay_Cyc_Long procedure Delay Cyc Long CycNo word eum Noting OO Example Delay Cyc Long 16384 16384 cycles pause Delay Cyc Long is a library function rather than a built in routine it is presented in this topic for the sake of convenience Clock kHz Prototype function Clock kHz longint Description Returns device clock in kHz rounded to the nearest integer This is an inline routine the code is generated in the place of the call Returns Device clock in kHz rounded to the nearest integer clk Clock_kHz notes None Clock_MHz Prototype function Clock MHz word Description Returns device clock in MHz rounded to the nearest integer This is an inline routine the code is generated in the place of the call Parameters None Retums Device cockin MHZ rounded to the nearestiniegern SCS Example ork coe etes Nm MikroElektronika 152 mikroPascal PRO for PIC32 Get_Fosc_kHz Reums Device dock O OSS Example ik Get Fosc EE C Get Fos
541. you to specify the number of iterations The syntax of the for statement is for counter initial value to final value do statement list or for counter initial value downto final value do statement list counter is a variable which increments or decrements if you use downto with each iteration of the loop Before the first iteration counter is set to initial value and will increment or decrement until it reaches final value final value will be recalculated each time the loop is reentered This way number of loop iterations can be changed inside the loop by changing final value With each iteration statement list will be executed initial value and inal value should be expressions compatible with counter If final value is a complex expression whose value can not be calculated in compile time and number of loop iterations is not to be changed inside the loop by the means of final value it should be calculated outside the for statement and result should be passed as for statement s final value statement list is a list of statements that do not change the value of counter If statement 1ist contains more than one statement statements must be enclosed within begin end block Here is an example of calculating scalar product of two vectors a and b of length 10 using the for statement s 0 for i 0 to 9 do S 25 s ali bial Endless Loop The for statement results in an endless loop if final value equals or exceeds th
542. ype procedure SPI Glcd Line x start y start x end y end integer color byte Description Draws a line on Glcd Parameters Parameters x start x coordinate of the line start Valid values 0 127 y start y coordinate of the line start Valid values 0 63 x end X coordinate of the line end Valid values 0 127 y end y coordinate of the line end Valid values 0 63 color color parameter Valid values 0 2 Parameter color determines the line color 0 white 1 black and 2 inverts each dot Nothing Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draw a line between dots 0 0 and 20 30 SPI Glcd Line 0 0 20 30 1 SPI Glcd V Line Prototype procedure SPI Glcd V Line y start y end x pos color byte Description Draws a vertical line on Glcd Parameters y start y coordinate of the line start Valid values 0 63 y end y coordinate of the line end Valid values 0 63 x pos X coordinate of vertical line Valid values 0 127 color color parameter Valid values 0 2 Parameter color determines the line color 0 white 1 black and 2 inverts each dot Nothing Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draw a vertical line between dots 10 5 and 10 25 SPI Glcd V Line 5 25 10 1 None 451 MikroElektronika mikoPascal PRO for PIC32 SPI_Glcd_H_Line Prototype procedure S
543. ype procedure LongWordToHex input dword var output array 8 of char Description Converts input number to a string containing the number s hexadecimal representation The output string is right justified and remaining positions on the left if any are filled with zeros Parameters input unsigned long integer number to be converted output destination string var input dword txt array 8 of char i I input i9 65535 LongWordToHex input txt txt is 0000FFFF LonglntToHex Prototype procedure LongIntToHex input longint var output array 8 of char Description Converts input number to a string containing the number s hexadecimal representation The output string is right justified and remaining positions on the left if any are filled with zeros Parameters input signed long integer number to be converted output destination string Nothing var input longint txt array 8 of char Mns input 2147483648 LongIntToHex input txt txt is 80000000 MikroElektronika 580 mikroPascal PRO for PIC32 StrTolnt Prototype function StrToInt var input string 6 integer Converts a string to an integer input String to be converted Returns Integer variable Requires Input string is assumed to be the correct representation of a number The conversion will end with the first character which is not a decimal digit var ii integer begin ii StrToInt 12
544. yyyyyyyyyyyY YYyyYyyyyyyYYYYyY yyyyyy yyyyyy yYyyyyyyvyyyvyvvyyy YyyyyyyyyyyYyyyY YyYyyyyyyyyyyvyyy Yyyyyyyvyyvyyvyyy YyyyYyyyyyyyyYYyY Yyyyyyyvyyyyvyyyy MikroElektronika mikroPascal PRO for PIC32 Graphic Lcd Bitmap Editor The mikroPascal PRO for PIC32 includes the Graphic Lcd Bitmap Editor Output is the mikroPascal PRO for PIC32 compatible code You can launch it from the drop down menu Tools Glcd Bitmap Editor MikroElektronika GLCD Bitmap Editor 240x128 pix bw D 128x128 T 963C I 128x6 not Imp yet d Ey 7 128x32 nating yet Vw M GLCD Picture name banner bmp GLCD Model Toshiba T6963C 240x128 unsigned char const banner bmp 3840 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 128 0 0 0 0 0 0 O 0 O O O O 0 0 0 0 O 0 O 0 O O O 1 128 O0 0 0 0 O 0 O 0 O 0 0 O O 0 O O 0 89 MikroElektronika mikoPascal PRO for PIC32 HID Terminal The mikroPascal PRO for PIC32 includes the HID communication terminal for USB communication You can launch it from the drop down menu Tools HID Terminal A mikroElektronika USB HID Terminal Terminal Descriptor HID Devices Info ABBAHOHE ABBAHOHE mikroE HID Librar Dell Premium USB Optical Mouse r Communication HID Read Write Test Send Append CR vw Send as Typing
545. ze Glcd via SPI SPI Glcd Fill 0x00 Clear Glcd while TRUE do begin SPI Glcd Image 8truck bmp Draw image Delay2s Delay2s SPI Glcd fill 0x00 Clear GLCD SPI Gled Partiallmage 0 0 68 30 128 64 0truck bmp Partial image Delay 1 ms 500 SPI Glcd Partiallmage 24 16 68 30 128 64 8truck bmp Delay 1 ms 500 SPI Glcd Partiallmage 56 34 68 30 128 64 8truck bmp Delay2s Delay2s SPI Glcd Fill 0x00 Clear GLCD SPI Glcd Box 62 40 124 56 1 Draw box SPI Gled Rectangle 5 5 84 35 1 Draw rectangle Delay 1 ms 1000 SPI Glcd Rectangle Round Edges 2 2 87 38 7 1 Delay 1 ms 1000 SPI Glcd Rectangle Round Edges Fil11 8 8 81 32 12 1 Delay 1 ms 1000 SPI Glcd Line 0 0 127 63 1 Draw line Delay2s 459 MikroElektronika mikoPascal PRO for PIC32 counter 5 while counter lt 59 do Draw horizontal and vertical lines begin Delay_ms 250 SPI Glcd V Line 2 54 counter 1 SPI Glcd H Line 2 120 counter 1 Counter counter 5 end Delay2S SPI Glcd Fill 0x00 Clear GLCD SPI Glcd Set Font G8Font Glcd Character8x7 8 7 32 Choose font Character8x7 SPI Gled Write Text mikroE 1 7 2 Write string for counter 1 to 10 do Draw circles SPI Gled Circle 63 32 3 counter 1 Delay2S SPI Glcd Circle Fill 63 32 30 1 Draw circles Delay2S SPI Glcd Box 10 20 70 63 2 Draw box Delay2s SPI

Download Pdf Manuals

image

Related Search

Related Contents

Dispositivo Apontador “Touch Pad”  Télécharger - Bienvenue sur Sémaphore, le dépôt numérique  AcuRite 00634A3 weather station  manual de instalacion y mantenimiento dosificadores peristalticos  Manual de Instrucciones  KETTLE KRAZY™    bq500414Q bqTESLA Wireless Power TX EVM  総合カタログ  PDC 4350 ML UM IT.indd  

Copyright © All rights reserved.
Failed to retrieve file