Home
mikroPascal PRO - MikroElektronika
Contents
1. Unlike IFDEF IFNDEF checks if flag is not defined by means of DEFINE thus producing the opposite results Include Directive I The i parameter directive instructs mikroPascal PRO for dsPIC30 33 and PIC24 to include the named text file in the compilation In effect the file is inserted in the compiled text right after the I 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 dsPIC30 33 and PIC24 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 source file See also Predefined Project Level Defines MikroElektronika 234 mikroPascal PRO for dsPIC30 33 and PIC24 Linker Directives mikroPascal PRO for dsP IC30 33 and PIC24 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 Directive absolute Directive absolute specifies the starting address in RAM for a variable If the variable is multi byte h
2. 389 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 dbuff buffer of minimum 512 bytes in length for data storage 0 if reading was successful 1 if an 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 Mme Read Sector sectorNo dataBuffer 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 sectorNo 510 error Mme Write Sector sectorNo dataBuffer MikroElektronika 390 mikroPascal PRO for dsPICSO 33 and PIC24 Mmc_Read_Cid Prototype function Mmc
3. RS485Slave Init 160 fi dat 0O OxAA dat 1 OxF0 dat 2 Ox0F dat 4 z 0 Ty datis 0 ie dat 6 0 URXISEL1 U2STA bit 0 URXISEL1 U2STA bit 0 NSTDIS bit ie U2RXIF bit 0 U2RXIE_ bit 1 while TRUE do begin if dat 5 lt gt 0 then Zy begin PORTD OxAA fd dat 5 0 end if dat 4 lt gt 0 then If begin dat 4 2 0 if J dae lsd for i 1 to dat 3 do if PORTB dat i 1 datio dat 0 1 Delay ms 1 RS485Slave Send dat 1 as end end end initialize UART2 module Intialize MCU as slave address 160 ensure that message received flag is 0 ensure that error flag is 0 no nesting of interrupts ensure interrupt not pending enable intterupt if an error detected signal it by setting portd to OxAA upon completed valid message receive data 4 is set to OxFF show data on PORTB increment received dat 0 and send it back to master 446 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 HW Connection Shielded pair no longer than 300m 2 O fan RF2 ae om 4 LTC485 Example of interfacing PC to dsPIC MCU via RS485 bus with LTC485 as RS 485 transceiver MikroElektronika 44 mikroPascal PRO for dsPIC30 33 and PIC24 Message format and CRC calculations Q How is CRC checksum calculated on RS485 master side Copy Code To Clipboard const START
4. 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 1 dyna 6 tmp 2 dyna 7 2 byteToStr remoteHost 2 tmp second dyna 8 tmp 0 dyna 9 tmp 1 dyna 10 tmp 2 dyna 11 Wrz byteToStr remoteHost 3 tmp second dyna 12 tmp 0 dyna 13 tmp 1 dyna 14 tmp 2 dyna iS lt 2 add separator then remote host port number WordToStr remotePort tmp dyna 16 tmp 0 dyna 17 tmp 1 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 neal ae dyna 28 0 the total length of the request is the length of the dynamic string plus the text of the request result 28 reqhength 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 reqLength 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 496 MikroElektronika mikoPascal P
5. Gled Tave MikroElektronika 390 mikroPascal PRO for dsPIC30 33 and PIC24 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 Side 0 yi Gled Select Side 10 Notes For side x axis and page layout explanation see schematic at the bottom of this page Glcd_Set_X we procedure 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 PRetums Noting SSCS ampe erase OOOO Notes For side x axis and page layout explanation see schematic atthe botom ofthis pags Glcd_Set_Page Prototype procedure Glcd Set Page page byte Selects page of the Glcd page page number Valid values 0 7 Rems nonn OOOO Example erca ses res OOOO Notes For side x axis and page layout explanation see schematic atthe botom ofthis pags 391 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Glcd_Read_Data PRetums One byte rom Gica memory fom
6. If Port Expander Library uses SPI2 module SPI2 Init Initialize SPI module used with SPI_Glced_Init 0 SPI Glcd_Fill1 0x00 while TRUE do begin SIFDEF COMPLETE EXAMPLE SPI _Glcd_Image truck_bmp Delay2s Delay2s SENDIF SPI_Glcd_Fill1 0x00 Delay2s SPI Glcd_ Box 62 40 124 63 1 SPI Gled Rectangle 5 5 84 35 1 SPI Glcd Line 0 0 127 63 1 Delay2s counter 5 while counter lt 60 do begin Delay ms 250 f f Ina tialize AN pins as digital tExpander PortExpander tialize Glcd via SPI Clear Gled Draw image Cle ar Gled Draw box Draw rectangle Draw line Draw horizontal and vertical line mikoPascal PRO for dsPIC30 33 and PIC24 SPI Gled V Line 2 54 counter 1 SPI Gled H Line 2 120 counter 1 counter counter 5 end Delay2s SIFDEF COMPLETE EXAMPLE SPI_Gled_Fill 0x00 SPI Gl d Set Font Character8x7 8 7 32 SPI Gled Write Text mikroE 1 7 2 SENDIF for counter 1 to 10 do Draw circles SPI Gled Circle 63 32 3 counter 1 Delay2s SIFDEF COMPLETE EXAMPLE SPI Gled Box 10 20 70 63 2 Delay2s SPI_Gled_Fill 0xFF SPL Gled Set Font Charactersx7 8 Tr 32 someText 8x7 Font SPI Gled Write Text someText 5 0 2 Delay2s SPI_Gled_Set_Font System3x5 3 5 32 someT
7. 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 LATFO bit var SPExpanderCS sbit at LATF1 bit var SPExpanderRST Direction sbit at TRISFO bit var SPExpanderCS Direction sbit at TRISF1 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 text mikroEk SPIL Txt 7 Initialize SPI interface If Port Expander Library uses SPI2 module SPI2 Init j Initialize SPI module used with PortExpander Spi_Lced8 Config 0 Intialize LCD in 8bit mode via SPI Spi Lcd8 Cmd LCD CLEAR Clear display Spi Lcd8 Cmd LCD CURSOR OFF Turn cursor off Spi_Led8 Out 1 6 text Print text to LCD lst row 6th column Spi Leds Chr CPi Append Spi Leda Out 2 1 mikroelektronika Print text to LCD 2nd row 1st column ae Spi Legg Out 3 1 text For LCD modules with more than two rows Tf Spi_Lced8 Out 4 15 text For LCD modules with more than two rows Delay ms 2000 Moving text for counter 0 to 3 do Move text to the right 4 times be
8. file contents 41 10 newline filename MIKROOOXTXT S DEFINE COMPLETE EXAMPLE comment this line to make simpler smaller example PORTD 0 TRISD 0 PORTF 0 TRISF 0 ADPCFG OxFFFF initialize AN pins as digital set up USART for the file read SPI1 Init _Advanced _ SPI MASTER SPT BIT SPI PRESCALE SEC 1 SPI _PRESCALE _ PRI 64 _SPI_SS_ DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 IDLE UART1 Init 19200 Initialize UART module at 9600 bps Delay _ms 100 Wait for UART module to stabilize U1LMODE ALTIO 1 Switch Rx and Tx pins on their alternate locations This is used to free the pins for other module namely the SPI UART Write Line dsPIC Started asPIC present report use fat16 quick format instead of init routine if a formatting is needed if Mme Fat _Init 0 then begin reinitialize spi at higher speed 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 IDLE Test start UART Write Line Test Start Create New File S IFDEF COMPLETE EXAMPLE Create Multiple Files Open File Rewrite Open File Append Open File Read Delete File Test File Exist 7 Create Swap File SENDIF UART Write Line Test End en
9. 367 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 dsPIC30 33 and PIC24 Copy Code To Clipboard program I2C Simple begin ADPCFG OxFFFF initialize AN pins as digital LATB 0 TRISB 0 Configure PORTB as output T2Cl_ Tnit 100000 7 initialize I2C communication T2C1 Start issue I2C start signal I2C1 Write 0xA2 send byte via I2C device address W I2Cl Write 2 send byte address of EEPROM location I2Cl_ Write 0xAA send data data to be written LACL Stop issue I2C stop signal Delay 100ms T2 1 Start issue I2C start signal I2Cl_ Write 0xA2 send byte via I2C device address W I2C1l Write 2 send byte data address T2C1 Restart issue I2C signal repeated start I2Cl_ Write 0xA3 send byte device address R PORTB I12Cl Read 1 Read the data NO acknowledge T2C1_Stop 7 issue I2C stop signal end HW Connection vec vcc v Interfacing 24c02 to dsPIC30 33 and PIC24 via C MikroElektronika 368 mikroPascal PRO for dsPIC30 33 and PIC24 Keypad Library mikroPascal PRO for dsPIC
10. Library Example The following code demonstrates usage of the Lcd Library routines Copy Code To Clipboard program Lcd Test LCD module connections RS spit EN sbit D4 sbit DS Ssbit D6 sbit D7 gt sbit var LC var LC var LC var LC var LC var LC var LC var LC var LC var LC var LC var LC RS_Directi EN Directi D4 Directi D5 Directi D6 Directi D7 Directi LS A J PO at at at at at at on on on on on on LATB1 bi LATB2 bi sbit sbit sbit sbit sbit Spit oo oo om End LCD module connections var txtl array 1 txt2 gt array 1 txt3 array 8 txt4 array 7 ri byte 6 1 of char LATDO bit LATD1 bit LATBO bit LATB3 bit Ly Ly Ly Cr i T a i of char of char of char procedure Move Delay begin Delay ms 500 end begin ADPCFG OxFFFF txtl mikro Led Ina z Led cma LCD C LE AR Led Cmda LCD CURSOR OFF LCD Out 1 6 tZ Ted cmdt LCD C t3 r z Delay ms 500 LCD Out 2 6 txt4 Delay ms 2000 EAR LCD Out 1 1 Ext1 7 Led Out 2 3 txb2 7 Elektronika txt2 EasydsPIC4A txt3 Led4bit txt4 example i ni A m RISDO bit RISD1 bit RISBO bit RISB1 bit RISB2 bit RISB3 bit ie Lf Lf Loop variable Function
11. MikroElektronika 221 mikroPascal PRO for dsPICSO 33 and PIC24 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 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 evaluated 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 sid
12. at TRISF3 bit sbit at TRISF2 bit at at at at at at End LCD module connections LATDO bit LATD1 bit LATBO bit LATB1 bit LATB2 bit LATB3 bit a TRISDO bit TRISD1 bit TRISBO bit TRISB1 bit TRISB2 bit TRISB3 bit possesses asssSSsssos Reads time and date information from RTC PCF8583 procedure Read Time begin Soft_I2C Start Issue start signal Soft_I2C_ Write 0xA0 Address PCF8583 see PCF8583 datasheet Soft T20 Write 2 Start from address 2 Soft_I2C Start 7 Issue repeated start signal Soft _I2C Write 0xA1 Address PCF8583 for reading R W 1 seconds Soft _I2C Read 1 Read seconds byte minutes Soft _I2C_ Read 1 Read minutes byte hours Soft _12C Read 1 Read hours byte day Soft_I2C Read 1 Read year day byte month Soft _I2C Read 0 Read weekday month byte Soft_I2C_Stop Issue stop signal end MikroElektronika 453 mikroPascal PRO for dsPIC30 33 and PIC24 D S es ae Formats date and time procedure Transform Time begin seconds seconds and 0xF0 shr 4 10 seconds and 0x0F Transform seconds minutes minutes and OxFO shr 4 10 minutes and Ox0F Transform months hours hours and OxFO shr 4 10 hours and Ox0OF Transform hours year day and 0xC0O shr 6 Transform year day day and 0x30 shr 4 10 day and Ox0F Transform day month month and 0x
13. begin ADPCFG OxFFFF Configure AN pins as digital I O UART1 Init 19200 Initialize UART module at 19200 bps Ps2 Config Init PS 2 Keyboard Delay 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 VARTI 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 430 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 HW Connection net F 2 a CONNECTOR t N NC CLK vec ge OSCILLATOR T 5V as t u i A NC DATA ow Example of PS2 keyboard connection PWM Library The CCP module is available with a number of dsPIC30 33 and PIC24 MCUs mikroPascal PRO for dsPIC30 33 and PIC24 provides a library which simplifies using of the PWM HW Module Imp
14. e Ct Configure AN pins as digital Initialize GLCD Clear GLCD Draw image Clear GLCD Draw box Draw rectangle Draw line Draw horizontal and vertical lines Glcd Set Font Character8x7 Ba Uy Sear Choose font Character8x7 Gled Write Text mikrok 1 7 2 Write string SENDIF for counter 1 to 10 do Draw circles Gled Circle 63 32 3 ecounter 1 Delay2S Glied Box 10 20 70 63 2 7 Draw box Delay2S SIFDEF COMPLETE EXAMPLE Glcd_Fill OxFF Fill GLCD Gled Set Font Character8x7 8 7 32 Change font someText 8x7 Font Gica Write Text someText 5 0 2 Write string delay2S Gled_ Set Font System3x5 3 5 32 Change font someText 3X5 CAPITALS ONLY Gled Write Text someText 60 2 2 Write string delay2S Gled Set Font font5x7 5 7 32 Change font 362 mikroPascal PRO for dsPIC30 33 and PIC24 someText 5x7 Font Glced_ Write Text someText 5 4 2 Write string delay2S Gled_ Set Font FontSystem5x7 v2 5 7 32 Change font someText 5x7 Font v2 Gled Write Text someTexty 50 6r 2 7 Write string delay2S SENDIF end end HW Connection o Leftside Right side 127 X axe gf Sqz0e02S580 OSCILLATOR 2 a O rN gt w Glcd HW connection mikoPascal PRO for dsPIC30 33 and PIC24 I
15. j abiti sfr external Direction of the Write pin Direction of the Read pin Direction of the Command Data pin Direction of the Reset pin var sfr T6963C_dataPort external var T6963C_ctrlw external var T6963C_ctrird external var T6963C_ ctrl external var T6963C_ctrird Direction sbit sfr external var T6963C_ctricd Direction sbit sfr external var T6963C_ctrirst_Direction sbit sfr external var T6963C_dataPort word at PORTB r6963C_ctrlwr sbit at r6963C_ctrird sbit at T6963C_ctrlcd sbit at var T6963C_ctrlirst r6963C_ctrlwr_ Direction sbit at F2 biti 69630 Ctrlrd Direction Fl bit sbit at 6963C ctrlcd Direction FO bit sbit at var T6963C_ctrirst_Direction sbit at TRISF4 bit MikroElektronika 367 mikroPascal PRO for dsPICSO 33 and PIC24 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_panel Fill T6963C_grFill T6963C_txtFill T6963C_cursor_height
16. routine will append the test at the place of the first null character adding terminating null character to the result MikroElektronika 675 mikroPascal PRO for dsPIC30 33 and PIC24 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 L the result string into 1 mikroElektronika pos Test Ld lt s strang 21 streat2 L1 txt txt_sub routine will adjoin strings txt and txt_sub and place the result into 1 1 mikroElektronika Test strchr Prototype function strchr var s string ch byte word Description The function searches the string s for the first occurrence of the character ch The null character terminating s is not included in the search The function returns the position index of the first character ch 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 Meaning sl less than s2 sl equal to s2 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 txt_sub mikr
17. while RB4 bit lt gt 0 do nop Wait for button to be released end if Button PORTB 3 1 1 then If PORTB 3 is pressed play Tonel begin Melody while RB3 bit lt gt 0 do nop Wait for button to be released end end end MikroElektronika 465 mikroPascal PRO for dsPIC30 33 and PIC24 HW Connection L vee RB3 o e v oi b gt RB7 w 7 J g PIEZO a SPEAKER Example of Sound Library 466 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI Library The SPI module is available with all dsPIC30 33 and PIC24 MCUs mikroPascal PRO for dsPIC30 33 and PIC24 provides a library for initializing the Slave mode and initializing and comfortable work with the Master mode The dsPIC30 33 and PIC24 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 the 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 SPlx_Read
18. 5 send Hello message to the above IP address from UDP port 10001 to UDP port 10001 MikroElektronika 513 mikroPascal PRO for dsPICSO 33 and PIC24 SPI_Ethernet_24j600_dnsResolve Prototype function SPI Ethernet 24j600 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 holding the IP address the requested host name was resolved 0 otherwise Ethernet module has to be initialized See SPI_Ethernet_24j600_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 _24j600 dnsResolve swisstime ethz eH 7 595 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
19. Counts how many chars have been written on LCD if chr counter 25 then If there were more then 25 characters begin gt synchronization is off Led_Cmd _ LCD CLEAR Clear the LCD of garbled communication Man_Synchro Try to synchronize again end end else chr counter 0 7 reset chr counter end Delay ms 25 end until byte rcevd Ox0E end If End byte was received exit do loop end The following code is code for the Manchester transmitter it shows how to use the Manchester Library for transmitting data Copy Code To Clipboard program Manchester Transmitter Manchester module connections var MANRXPIN sbit at RFO bit MANRXPIN Direction sbit at TRISFO bit MANTXPIN sbit at LATFL bit MANTXPIN Direction sbit at TRISF1 bit End Manchester module connections var index character byte sl array 17 of char begin sl mikroElektronika ADPCFG OxFFFF Configure AN pins as digital I O Man Send Init Initialize transmitter while TRUE do Endless loop mikoPascal PRO for dsPIC30 33 and PIC24 begin Man Send 0x0B Delay ms 100 character s1 0 index 0 while character lt gt 0 begin Man Send character Delay ms 90 Inc index Send start byte Wait for a while Take first char from string Initialize index variable do String ends with zero Send character Wait for a while
20. DEVICES device MCU name as specified 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 pt emp late provided with mikroPascal PRO for dsPIC30 33 and PIC24 installation 59 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 Web links http www mikroe com include main LCD_LRS LCD_EN LCD_D4 LCD_D5 LCD_D6 LCD_D LCD_RS_Direction LCD_EN_Direction LCD_D4_Direction LCD_DS_Direction LCD_D6_Direction e e e e M LCD_D _Direction txt1 txt2 txt3 txt4 i love_Delay The following options are available in the Code Explorer eon Description Expand Collapse all nodes in tree Ey Locate declaration in code MikroElektronika 60 mikroPascal PRO for dsPICSO 33 and PIC24 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 b
21. 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 longint number to be converted Serna destination string var input longint txt array 8 of char EP ines input 2147483648 LongIntToHex input txt txt is 80000000 668 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 StrToInt 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 Li StrTolnt 1234 StrToWord Prototype function StrToWord var input string 5 word Converts a string to word input string to be converted Returns 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 ww StrToword 65432 Bcd2Dec Prototype function Bcd2Dec bcdnum byte byte FRetums Converted decimalvawe O OC oS var a b byte 22 Bcd2Dec a b equals 34 MikroElektronika 669 mikroPascal P
22. Description Gets calibration constants after calibration is done and stores them in x min x max y min and y_max ee 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 ni y coordinate of the upper right corner of the working area TP Get Calibration Consts x min y min x max y max calibration constants MikroElektronika 609 mikroPascal PRO for dsPIC30 33 and PIC24 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 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_mint 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 Set Calibration Consts 148 3590 519 3370 Set calibration constants Notes None SSCS Library Example The following drawing demo tests routines of the Touch Panel library Copy Code To Clipboard program TouchPanelCalibrationAndwWrite Glcd module connections var GLCD D7 sbit at RD3 bit GLED DG sbit at RD2 bit GLCD D5 sbit at RDI bit GLCD _ D4 sbit at RDO DIC GLCD D3 sbit at RB3 bit GLCD D2 sbit at RB2 bit GLCD
23. FLASH_Write_Init FLASH_Write_Loadlatch4 FLASH_Write_Loadlatch4_Compact FLASH_Write_DoWrite FLASH_Read4 FLASH_Read4_Compact PIC24 and dsPIC33 Functions FLASH_Erase FLASH_Write FLASH_Write_Compact FLASH_Read FLASH_Read_Compact 337 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 dsPIC30 Functions FLASH_Erase32 erase the 32 instruction block starting from address 0x006000 FLASH Erase32 0x006000 The user should take care about the address alignment see the explanation at the beginning of this page FLASH_Write_Block Prototype procedure FLASH Write Block flash_ address longint data_address word Description Fills one writeable block of Flash memory 4 instructions 8 addresses 12 bytes in the regular mode Addresses and data are being mapped 1 on 1 This also means that 3rd byte of each program location remains unused Parameters flash address starting address of the FLASH memory block data_ address data to be written Requires The block to be written to must be erased first either from the user code through the RTSP or during the programming of MCU Please note that block size that is to be erased is different from the one that can be written with this function var flash_address longint cArr string 4 ptr_data word flash_address 0x006000 cArr ABCD ptr data cArr FLASH Write Block flash_address p
24. Increment index variable character sl index Take next char from string end Man Send 0x0E Delay _ms 1000 end end Connection Example Antenna V Antenna Send end byte Transmitter RF module vec OSCILLATOR GND LAL Simple Transmitter connection Receiver RF module vec Simple Receiver connection MikroElektronika mikroPascal PRO for dsPICSO 33 and PIC24 Multi Media Card Library 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 PDA s mikroPascal PRO for dsPIC30 33 and PIC24 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
25. This library implements time based activities so interrupts need to be disabled when using OneWire library Library Routines Ow_Reset Ow_Read Ow_Write Ow_Reset a function Ow Reset var port word pin word word Issues OneWire reset signal for DS18x20 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 PORTF 6 Naes nos OO MikroElektronika 407 mikroPascal PRO for dsPICSO 33 and PIC24 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 6 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 PORTF 6 OxCC 408 MikroElektronika mikoPascal PRO for dsPIC30
26. byte writebuff byte Initialize the USB module of the MCU Parameters readbuff Read Buffer writebuff Write Buffer Com needs to be enabled before using this function See HID_Enable _ Enable Gen_Enable readbuff writebuff 0 writebuff Gen_Read dais iis 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 iie while Gen Read readbuff 64 1 Gen_Write TOODE 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 ee while Gen Write writebuff 64 1 do MikroElektronika 633 mikroPascal PRO for dsPICSO 33 and PIC24 Library Example This example establishes connection with the HID terminal that is active on the PC Upon connec
27. initial valueand final 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 list 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 c s ala bial Endless Loop The for statement results in an endless loop if final value equals or exceeds the 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 221 mikroPascal PRO for dsPIC30 33 and PIC24 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
28. initialize ECAN ECAN1SetBufferSize ECANLRAMBUFFERSIZE set number of rx tx buffers in DMA RAM ECAN1SelectTxBuffers Ox000F select transmit buffers 0x000F buffers 0 3 are transmit buffers ECAN1SetOperationMode _ECAN MODE CONFIG OxFF set CONFIGURATION mode ECAN1SetMask _ECAN MASK 0 le ECAN CONFIG MATCH MSG TYPE and ECAN CONFIG XTD MSG set all maskl bits to ones ECAN1SetMask _ECAN MASK 1 1 ECAN CONFIG MATCH MSG TYPE and ECAN CONFIG XTD MSG s t all mask2 bits to ones ECAN1SetMask _ECAN MASK 2 Sl ECAN CONFIG MATCH MSG TYPE and ECAN CONFIG XTD MSG set all mask3 bits to ones ECAN1SetFilter ECAN FILTER 10 ID 2nd ECAN MASK 2 ECAN RX BUFFER 7 ECAN CONFIG set id of filter10 to 2nd node ID ECAN1SetOperationMode _ECAN MODE NORMAL 0xFF ECAN1Write ID 1st RxTx Data 1 Can_Send Flags A Tf assign mask2 to filterl0 assign buffer7 to filterl0 set NORMAL mode send initial message 314 mikroPascal PRO for dsPIC30 33 and PIC24 while TRUE do endless loop begin Msg Revd ECAN1Read Rx_ ID RxTx Data Rx Data_Len Can Rev Flags receive message if Rx_ID ID 2nd and Msg Revd lt gt 0 lt gt 0 then if message received check id begin PORTB RxTx Data 0 id correct output data at PORTB Inc RxTx Data 0 Delay ms 10 ECAN1Write ID_1st RxTx Data 1 Can Send Flags send incremented data back end end end Co
29. 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_Te963C WHITE 952 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_T6963C_rectangle_round_edges fill Prototype ea oe SPI T6963C rectangle round edges fill x0 lt integer 79 integer integer yl integer radius integer 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 yl 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 Gied module needs to be initialized See SP _T6963C_Config routine a SPI _T6963C rectangle round edges fill 20 20 219 107 12 SPI T6963C_ WHITE SPI_T6963C_box Prototype procedure SPI T6963C box x0 yO 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 the upper left box corner x1 x coordinate of the lower right box corner yl y coordinate of the lower right box corner pcolor color parameter Valid values SPI_T6963C_BLACK and SPI_T6963
30. width width of the Glcd panel height height of the Glcd panel fntw 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 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 MikroElektronika 547 mikroPascal PRO for dsPICSO 33 and PIC24 Port Expander module connections SPExpanderRST sbit at LATFO bit SPExpanderCS sbit at LATFI1 bit SPExpanderRST Direction sbit at TRISFO bit SPExpanderCS Direction sbit at TRISFI1 bit End Port Expander module connections Initialize SPI module SPIL IDIEN SPI_T6963C_config 240 64 SPI_T6963C_writeData Prototype procedure SPI T6963C writeData data_ byte Rems noms OOOO O Example SP1 169630 wrrceata taata y OSS moes fnn Ooo 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
31. 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 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 262 mikroPascal PRO for dsPICSO 33 and PIC24 CANSP GetOperationMode 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 SUJW BRP PHS EG2 PROPSEG CANSPI CONFIG FLAGS chariy Description Initializes the CANSPI module Stand Alone CAN controller
32. 12 Then select the MPLAB ICD 2 from the Debugger gt Select Tool menu for hardware debugging M MPLAB IDE v8 36 Output DER T Fie Edt view Project REE er Programmer Tools Configure Window Help Dou sm v None a Clear Memory gt 1 MPLAB Build Yersion Control Find in Files 2PIckit 3 Loaded C Program Files Mikroelektronika plage me 4000 Examples Development Boards EasydsPICAA UART UAI 5 MPLAB ICE 200 6 REAL ICE 7 PIckit 2 8 MPLAB ICD 3 3 PIC32 Starter kit 10 Starter k dsPIC30F4013 oabsabIPO denovzc 13 Complete the MPLAB ICD 2 Setup Wizard from the Debugger menu if needed mikoPascal PRO for dsPIC30 33 and PIC24 14 After completing MPLAB ICD 2 Setup Wizard click on the Debugger Connect M MPLAB IDE v8 36 Output T Fie Edit view Project Oo Build Version Control Find Connecting to MPLAB ICL Connected Setting Vdd source to tar Target Device dsPIC3OF Reading ICD Product IC Running ICD Self Test Passed MPLAB ICD 2 ready for n Debugger Dor Programmer Tools Configure Window Help ax Select Tool Clear Memory Run Animate Halt Step Into Step Over Step Out Reset b gt PB O 3M HweP m u Breakpoints anced Breakpoints MPLAB ICD 2 Setup Wizard Program Read Read EEPROM Abort Operation Connect Download ICD2 Operating System Settings MikroElektronika
33. Ctrl P exit Alt x O e foem OOOO Related topics Keyboard shortcuts File Toolbar Managing Source Files M MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Edit Edit Menu Options The Edit Menu contains commands for editing the contents of the current document Undo Ctrl z Redo Shift Ctrl zZ My Cut Ctrl x Copy Ctrl C Paste Ctrl Delete Select All Ctri Find Ctrl F Find Next F3 Find Previous Shift F3 Replace Ctrl R Find In Files Alt F3 Goto Line Ctrl G Advanced Edit Description Cid MikroElektronika 42 mikroPascal PRO for dsPIC30 33 and PIC24 Find Text Dialog box for searching the document for the specified text The search is performed in the direction specified If the string is 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 mikroElektronika mikroE 43 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 th
34. 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 buffer 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_ 283 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Cf_Fat_lInit 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 Cf Fat _Init 0 then Cf_Fat_QuickFormat Prototype function Cf Fat QuickFormat var cf fat label string 11 word Formats to FAT16 and initializes CF card Parameters cf f
35. 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 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 filled rounded edge rectangle between dots 5 5 and 40 40 with the edge radius of 12 Gled Rectangle Round Edges Fill 5 5 40 Gicd_Box Prototype procedure Glcd Box x upper left y upper left x bottom right y bottom_ Fight 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 dot
36. MikroElektronika 317 mikoPascal PRO for dsPIC30 33 and PIC24 EEPROM _ Erase ne alittle Erase address longint var eeAddr longint esheds Ox7FFC80 EEPROM Erase eeAddr CPU is not halted for the Data Erase cycle The user can poll WR bit use NVMIF or Timer IRQ to detect the end of erase sequence EEPROM _Erase_Block E procedure E Erase Block address longint 24F04KA201 and 24F16KA102 family it is 8 words a eet eg OO var eeAddr longint eeAddr 0Ox7FFC20 EEPROM Erase Block eeAddr CPU is not halted for the Data Erase cycle The user can poll WR bit use NVMIF or Timer IRQ to detect the end of erase sequence EEPROM Read aA aa function EEPROM Read address longint word C noniliespadiodaiseen var eeAddr longint temp word eeAddr Ox7FFC20 temp EEPROM Read eeAddr MikroElektronika 318 mikroPascal PRO for dsPICSO 33 and PIC24 EEPROM_Write ibe procedure EEPROM Write address longint data_ word Writes data to specified address Parameters address address of the EEPROM memory location to be written data data to be written var wrAddr longint eeData word eeData OxAAAA wrAddr 0x7FFC30 EEPROM Write wrAddr eeData Notes Specified memory location will be erased before writing starts EEPROM_Write_Block Prototype ee age
37. 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_lInit Set Port Expander s PORTB to be input Expander Set DirectionPortB 0 5FF Notes None OOOO Expander_Set_DirectionPortAB aes procedure Expander Set DirectionPortAB ModuleAddress Direction word The function sets Port Expander s PortA and PortB direction Parameters Modul ecAddress 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 Di rection 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_lInit Set Port Expander s PORTA to be output and PORTB to be input Expander Set _DirectionPortAB 0 00FF Expander_Set_PullUpsPortA Prototype procedure Expander Set PullUpsPortA ModuleAddress Data byte
38. Properties bg Add All k Remove all o 3 i A Me kaha Select variable from list e Led_Cmd _LCD CLEAR ppm x gt Led_Cma _LCD_CURSOR_OFF Search for variable by assembly name _text f i 1 to 17 d esse bs 2 v Peripherals Freeze begin gt DM e Lcd_Chr 1 i text i 1 Name Value Address Eo o ae O B ena TRIB 0x text hom 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 o H negin Watch Values E ADPCFG OxFFFF gt 49 mikroElektr a BE Ei Bx wu o OL e ij A a Add Remove gt Properties tg AddAll a Remove All 50 Led_Init Select variable from list i o Led Cmd _LCD_CLEAR caze d Led Cmd _LCD_CURSOR_OFF Search for variable by assembly name _text Ci y J ea Si Dl ak ue ai Che J Peripherals Freeze i begin E od Led_Chr i i text i 1 Name Value Address e end a o end TRIB RC OLB eC ADPCFG OxFFFF 0x02A8 text alec 0x0800 PC 0x000288 0 10 us MikroElektronika 120 mikroPascal PRO for dsPIC30 33 and PIC24 Step Into F7 Step Over F8 and
39. Set CS pin as Output Soft_Spi_Init Initialize Soft_SPI end DAC increments 0 4095 gt output voltage 0 Vref procedure DAC Output valueDAC word var temp byte volatile MikroElektronika 457 mikroPascal PRO for dsPIC30 33 and PIC24 begin Chip Select 0 Select DAC chip Send High Byte temp word valueDAC shr 8 and 0x0F 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 ADPCFG OxFFFF Configure AN pins as digital InitMain Perform main initialization value 2048 When program starts DAC gives the output in the mid range while TRUE do Endless loop begin if RBO bit and value lt 4095 then I RBO button is pressed Inc value FI increment value else begin if RB1 bit and value gt 0 then If RB1 button is pressed Dec value tf decrement value end DAC_Output value Send value to DAC chip Delay ms 1 Slow down key repeat pace end end 458 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Software UART Library The mikroPascal PRO for dsPIC30 33 and PIC24 provides routines for implementing Software UART commun
40. T6963C_graphics T6963C_text T6963C_cursor T6963C_cursor_blink 568 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 T6963C_init Prototype 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 4 width width of the Glcd panel height height of the Glcd panel fntw font width 6963C_dataPort Data Port r6963C_ctriwr Write signal pin 6963C_ctrird Read signal pin r6963C_ctrlcd Command Data signal pin 6963C_ctrirst Reset signal pin r6963C_ ctrlwr Direction Direction of Write signal pin 6963C_ ctrlrd Direction Direction of Read signal pin r6963C ctrled Direction Direction of Command Data signal pin r6963C_ ctrlrst Direction Direction of Reset signal pin must be defined before using this function MikroElektronika 569 mikroPascal PRO for dsPIC30 33 and PIC24 T6963C module connections var T6963C_dataPort byte at PORTB DATA port var T6963C_ctrlwr sbit at LATF2 bit WR write signal var T6963C ctrird lt bit at LATFL bit RD read signal var T6963C_ctrlcd sbit at LATFO bit CD command data signal var T6963C_ctrirst sbit at LATF4 bit RST reset signal var T6963C_ctrlwr Direction sbit at TRISF2 bi
41. WordToStr IntToStr Long ntToStr 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 659 mikroPascal PRO for dsPIC30 33 and PIC24 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 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 short number to be converted eo aii destination string var t short txt array 4 of char 24 ByteToStr t txt txt is 24 one blank here 660 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 WordToStr Prototype procedure
42. You can specify your own custom search paths select Project Edit Search Paths option from the drop down menu Search Paths C Program Files Mikroelektronika mikroPascal PRO for dsPIC Defs C Program Files Mikroelektronika mikroPascal PRO for dsPIC uses C Program Files Mikroelektronika mikroPascal PRO For dsPIC Examples Development Systems EasydsPIC4A Lcd fimer samas Apply Doctors Following options are available mn Remove Search Path Purge Invalid Paths MikroElektronika 699 mikroPascal PRO for dsPICSO 33 and PIC24 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 dsPIC30 33 and PIC 24 will look for the file in following locations in this particular order 1 the project folder folder which contains the project file mppds 2 your custom search paths 3 mikroPascal PRO for dsPIC30 33 and PIC 24 installation folder gt Uses folder Related topics File Menu File Toolbar Project Manager Project Settings 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 y
43. 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 Description This is MAC module routine It stores requested number of const bytes into ENC28 760 RAM starting from current ENC28J60 write pointer EWRPT location Parameters ptr const buffer containing bytes to be written into ENC28760 RAM n number of bytes to be written Nothing 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 481 mikroPascal PRO for dsPICSO 33 and PIC24 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 S
44. 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 lease time has expired it s time to renew it Ethernet module has to be initialized See SPI_Ethernet_Init while true do begin if SPI Ethernet _doDHCPLeaseTime lt gt 0 then begin it s time to renew the IP address lease end 490 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_Ethernet_renewDHCP Prototype function SPI Ethernet renewDHCP tmax byte byte i O O o 0 otherwise renewal request timed out while true do begin if SPI Ethernet doDHCPLeaseTime lt gt 0 then begin SPI_Ethernet_renewDHCP 5 it s time to renew the IP address lease with 5 secs for a reply end 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 t0 t7 will toggle RDO to RD7 bit and return HTML main page all other r
45. ext sub i makr res strncemp txt_sub txt 3 compares the first 3 characters from the string txt with the sting txt sub and returns a difference 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 mikroElektronika txt sub mikr res strstr txt_sub txt mikoPascal PRO for dsPIC30 33 and PIC24 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 mikroElektronika txt sub mikr res strcespn txt_sub txt strpbrk 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
46. resolved host IP address buffer These locations should not be altered by the user in any case 514 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_Ethernet_24j600_initDHCP Prototype function SPI Ethernet 247600 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_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 243600 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
47. s 0 i 0 while i lt n do begin S i 8 alil pilil i 31 I 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 s 0 i 0 repeat begin s s ali b il i i 1 end until i n 228 MikroElektronika mikroPascal PRO for dsPICSO 33 and PIC24 Jump Statements The jump statement when executed transfers control unconditionally There are four such statements in mikroPascal PRO for dsPIC30 33 and PIC24 break continue exit goto Break and Continue Statements Break Statement Sometimes you might need to stop the loop from within its body Use the break statement within loops to pass control to the first statement following the innermost loop for while or repeat block For example Led Out 1 1 Insert CF card Wait for CF card to be plugged refresh every second while TRUE do begin if Cf Detect 1 then break Delay _ms 1000 end Now we can work with CF card Led
48. 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 O white 1 black and 2 inverts each dot 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 1 3 024 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_Glcd_Rectangle_Round_Edges Fill Prototype procedure SPI 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 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
49. 4 Next open MPLAB and select the appropriate device by choosing Configure gt Select Device mikroPascal PRO for dsPIC30 33 and PIC24 w MPLAB IDE v8 36 Output File Edit View Project Debugger Programmer Tools Kesiti Window Help Osa sue Shoam e Configuration Bits Build Version Control Find in Files External Memor ID Memory Settings 712 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 5 After device selection click on the File Import Open file dialog box should appear Then go to the project folder and open the generated COFF file UART cof PLAB ID 8 36 Outp LJ m Edit View Project Debugger Programmer Tools Configure Window Help 8 x New Ctrl N Add New File to Project a B B Open Ctrl 0 Close Ctrl E Open Workspace Save Workspace Save Workspace As Close Workspace Export Print Ctrl P Recent Files Recent Workspaces Exit dsPIC30F4013 oab sab IPO denovzc mikroPascal PRO for dsPICSO 33 and PIC24 6 Then select the MPLAB SIM from the Debugger gt Select Tool menu for software debugging w MPLAB IDE v8 36 Output T Fie Edit View Project REMer ig Programmer Tools Configure Window Help Select Tool J None Dee m P a Clear Memory gt 1 MPLAB ICD 2 o Ei Build Version Control Find 7 2PICkit 3 Run 3 MPLAB ICE 4000 a z 5 MPLAB I
50. Active Comment Actions New Rename Properties Attributes Url Image File Events OnLeftClick Alt N OnRightClick OnDblClick OnMouseOver Add Image To Project Add File To Project 89 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 Ascii Chart NUL SOH STX ETX EOT ENQ ACK BEL BS LF YT FF CR 0 1 2 3 4 5 6 7 8 9 10 11 12 13 DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS 19 20 2 22 23 2 25 26 27 amp 35 36 37 38 9 43 3 6 54 F MikroElektronika 90 mikroPascal PRO for dsPIC30 33 and PIC24 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 dsPIC30 33 and PIC24 IDE project name hex file will be loaded automatically while i hex file must be loaded manually MikroElektronika EEPROM Editor PAA RAARAARAALAAL SAA AAARARAAAL AL YIVYIIVIVI IIIT 0040 yyyy yyy 0050 VIVVIVITIV IVI IY 0070 0080 YIVYVIVEVV IVY 0090 LAARA ARARA AARAA Filter Designer The Filter designer is a tool for designing FIR and IIR filters It has a
51. As you type the actual parameter the next expected parameter will become bold channel byte ADC_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 55 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 amp Editor Colors Editor Settings Sass Current Scheme Office 2003 Blue Delete Editor Colors Stare Stup DEFINE PWM SEQUENCE ON A Element j Assembler Auto Correct Binary Character Comment R Float Auto
52. CANSPI_OP_MODE Constants The CANSPI_ OP MODE constants define CANSPI operation mode Function CANSPISetOperationMode expects one of these as it s argument 269 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 CANSPIlnit CANSPISetBaudRate CANSPISetMask and CANSP ISetFilter expect one of these or a bitwise combination as their argument Copy Code To Clipboard const CANSPI CONFIG DEFAULT byte SFF fh VIATTTITT CANSPI CONFIG PHSEG2 PRG BIT byte 01 CANSPI CONFIG PHSEG2 PRG ON byte SFF XXXXXXX1 CANSPI CONFIG PHSEG2 PRG OFF byte SFE XXXXXXX0 CANSPI CONFIG LINE FILTER BIT byte 02 CANSPI CONFIG LINE FILTER ON byte SFF XXXXXX1X CANSPI CONFIG LINE FILTER OFF byte FD XXXXXXOX CANSPI CONFIG SAMPLE BIT byte 04 CANSPI CONFIG SAMPLE ONCE byte FF XXXXX1XX CANSPI CONFIG SAMPLE THRICE byte FB XXXXXOXX CANSPI
53. 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 C c Jae c a TFT module needs to be initialized See the TFT_Init routine Example TFT_Dot 50 50 CL_BLACK 596 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 C a pen_width sets thickness TFT module needs to be initialized See the TFT_Init routine TFT Set _Pen CL BLACK 10 MikroElektronika 597 mikroPascal PRO for dsPIC30 33 and PIC24 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 Description 598 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Description gradient enabled enable gradient Enable gradient oo Disable gradient gradient orientation sets gradi
54. First of all the user should know that dsPIC30 33 and PIC24 s ALU which performs arithmetic operations is optimized for working with 16 bit types Although mikroPascal PRO for dsPIC30 33 and PIC24 is capable of handling types like byte char or short dsPIC30 33 and PIC24 will generate a better code for 16 bit types word and integer Therefore use byte char and short only in places where you can significantly save RAM e g for arrays a array 30 of byte 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 dsPIC30 33 and PIC24 but they should be used very carefully due to dsPIC30 33 and PIC24 stack and memory limitations Also calling functions from interrupt is allowed Calling function from both interrupt and main thread is allowed Be carefull because this programming technique may cause unpredictable results if common resources are used in both main and interrupt Limits of Indirect Approach Through PSV Constant aggregates are stored in Flash and are accessible through PSV mikroPascal PRO for dsPIC30 33 and PIC24 can allocate more than 32KByte of constants See near and far memory specifiers Limits of Pointer to Function Currently pointer to functions are 16 bit variables For functions which
55. 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 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 387 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Library Dependency Tree r MMC Fs MMC FAT16 C String C Type External dependencies of MMC Library The following variable must be defined D scribtion in all projects using MMC library P i var Mmc Chip Select sbit sfr var Mmc Chip Select sbit at LATFO Chip select pin f z external bit var Mme Chip Select Direction Direction of the chip select pin 2 Mme Chip Select Direction sbit sfr external P 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_lInit Mmc_Fat_QuickFormat Mmc_Fat_Assign Mmc_Fat_Reset Mmc_Fat_Read Mmc_Fat_R
56. Glcd needs to be initialized see Glcd_Init routine Draw a fees chine dots 5 15 and 20 40 Glcd_Box Loe 20g 1 Notes None SSS MikroElektronika 356 mikroPascal PRO for dsPICSO 33 and PIC24 Glcd_Circle Prototype procedure Gled Circle x center y center radius integer color byte 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 see Glcd_Init routine Draw a circle with center in 50 50 and radius 10 Gled Circle 50 50 10 1 7 Gled_Circle_Fill Prototype procedure Glcd Circle eae 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 line 0 white 1 black and 2 inverts each dot Glcd needs to be initialized see Glcd_Init routine Draw a filled circle with center in 50 50 and radius 10 aled Circle Paki a0 S0 10 14 397 MikroElektro
57. 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 Tree Compact Flash FAT16 Compact Flash C_Type i 271 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 External dependencies of Compact Flash Library The following variables must be defined in all projects using Compact Flash Description Library CF Data Port Er ge ara FOr pyes ar Compact Flash Data Port var CF Data Port byte at PORTD external CF_RDY f bit fri pie sis sia Ready signal line var CF RDY sbit at RB7 bit external e var CF WE sbit sfr external Write Enable signal line var CF WE sbit at
58. Ox7F62 Ox7E9D Ox7D8A Ox7C2A Ox7A7D 0x7885 0x7642 0x73B6 Ox70E3 Ox6DCA Ox6A6E 0x66D0 Ox62F2 Ox5ED7 Ox5A82 Ox55F6 0x5134 0x4C40 0x471D Ox41CE 0x3C57 Ox36BA Ox30FC Ox2B1F 0x2528 Ox1F1A Ox18F9 0x0000 OxF9B8 OxF374 OxED38 OxE707 OxEOE6 OxDAD8 OxD4E1 OxCFO04 0xC946 OxC3A9 OxBE32 OxB8E3 OxB3C0 OxAECC OxAAOA OxA57E OxA129 Ox9DOE 0x9930 0x9592 0x9236 Ox8FL1D Ox8C4A 0x89BE 0x877B 0x8583 0x83D6 0x8276 0x15E2 0x096B OxFCDC OxF055 OxE3F4 OxD7D9 UxCE2T OxCOE9 OxB64C OxAC65 OxA34C Ox9BIT 0x93DC Ox8DAB 0x8894 0x84A3 Ox81E2 0x8059 Ox7FFE Ox7FC2 Ox7F38 Ox7E60 0Ox7D3A 0x7BC6 Ox7A06 Ox77FB Ox75A6 0x7308 0x7023 Ox6CF9 0x698C Ox65DE Ox61F1 0x 5DC8 0x5964 Ox54CA Ox4FEB Ox4AFB 0x45CD 0x4074 Ox3AF3 0x354E Ox2F87 Ox29A4 Ox23A7 Ox1D93 0x176E 0x81E2 0x8059 Ox800A Ox80F6 Ox831c Ox8676 Ox8AFB Ox90A1 0x9759 0x9F14 0xA7BD 0xB140 OxBB85 0xC673 OxD1EF OxDDDC OxEA1E OxF695 OxFE6E OxF827 OxF1E4 OxEBAB OXES 7D OxDF6 1 0xD958 OxD367 OxCD92 OxC7DB 0xC248 OxBCDA 0xB796 OxB27F OxAD97 OxA8E2 0xA463 OxA01C 0x9011 0x9843 0x94B5 0x9169 0x8E62 Ox8BAO 0x8927 Ox86F6 0x8511 Ox8377 0x822A 0x12C8 0x0648 OxF9B8 OxED38 OxEOE6 OxD4E1 0xC946 OxBE32 OxBSCO OxAAOA OxA129 0x9930 0x9236 Ox8C4A
59. byte SFF XXXXX1XX CANSPI TX XTD FRAME gt byte SF7 XXXXXOXX CANSPI TX RTR BIT byte 40 CANSPI TX NO RTR FRAME byte FF Jf XIXXXXXKX CANSPI TX RTR FRAME byte SBF A SO You may use bitwise 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 FRAMI and CANSPI TX NO RTR FRAME sal 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 271 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Copy Code To Clipboard const CAN PI RX FILT LS CAN PI RX FILTER CA Z PI RX FILT CA zZ GA Z PE RX FLETI CA Zz PI RX FILT CA Z S S S SPI RX FILTER S S S PI RX FILT 71 t po Nu FP WHE w Ze _CA _CAN CAN S S S CANS PI _RX_ OVERFLOW PI_RX_INVAI PI RX XTD FRAMI PI RX RTR_ FRAMI LID MSG F E F E CANSPI RX DBL BUFFERED buffered You may use bitwise and to adjust the appropriate flags Copy Code To Clipboard byte byte byte byte byte byte byte byte byte byte byte byte if MsgFlag and _CANSPI RX OV
60. mikroPascal PRO for dsPICSO 33 and PIC24 UARTx_Write SS UARTx Write data_ word E 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_ 0x1E UART1 Write data_ 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 4 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library UARTx_Write_Text Prototype procedure UARTx Write Text var uart_text string Sends text via UART Text should be zero terminated UART_text text to be sent 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 4 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
61. mikroPascal PRO fordsPIC Manual mikroPascal PRO for dsPIC30 33 and PIC 24 is a full featured compiler for dsPIC30 dsPIC33 and PIC24 MCUs from Microchip It is designed for developing building and debugging dsPIC30 33 and PIC24 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 4 MikroElektronika SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD waking it single mikoPascal PRO for dsPIC30 33 and PIC24 Table of Contents CHAPTER 1 32 INTRODUCTION 32 Introduction to mikroPascal PRO for dsPIC30 33 and PIC24 33 Features 33 Where to Start 33 What s new in mikroPascal PRO for dsPIC30 33 and PIC24 34 Compiler Changes 34 IDE Changes 34 Software License Agreement 35 mikroElektronika Associates License Statement and Limited Warranty 35 IMPORTANT READ CAREFULLY 35 LIMITED WARRANTY 35 HIGH RISK ACTIVITIES 36 GENERAL PROVISIONS 36 Technical Support 37 How to Register 37 Who Gets the License Key 37 How to Get License Key 37 After Receving the License Key 39 CHAPTER 2 41 mikroPascal PRO for dsPIC30 33 and PIC24 Environment 41 Main Menu Options 42 File 43 Fi
62. retrieve low address word of myvar and move it to W1 retrieve high address word of myvar and move it to W1 retrieve hi address byte of routine proc and move it to OV lo_addr _msg WO retrieve low address word of constant msg and move it to OV _myvarl 2 w0 accessing hi word of myvarl variable and move it to W1 0xABCD 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 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 i integer y center lt integer radius integer end var Circle Circle Parameters begin With Circle do 232 MikroElektronika mikroPascal PRO for dsPIC
63. s literal value In the second case your constant will be placed in Flash in the exact location specified 235 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 To place a routine on a specific address in Flash memory you should write the following procedure proc par byte org 0x200 begin Procedure will start at address 0x200 end org directive can be used with main routine too For example program Led Blinking begin org 0x800 main procedure starts at 0x800 end Directive orgall Use the orgal1 directive to specify the address above which all routines and constants will be placed Example begin orgall 0x200 All the routines constants in main program will be above the address 0x200 end MikroElektronika 236 mikroPascal PRO for dsPICSO 33 and PIC24 CHAPTER 9 mikroPascal PRO for dsPIC30 33 and PIC24 Libraries mikroPascal PRO for dsPIC30 33 and PIC24 provides a set of libraries which simplify the initialization and use of dsPIC30 33 and PIC24 and their modules Use Library manager to include mikroPascal PRO for dsPIC30 33 and PIC24 Libraries in you project 231 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Hardware Libraries ADC Library CAN Library CANSPI Library Compact Flash Library Enhanced CAN Library EEPROM Library Epson S 1D13700 Graphic Lcd Library Flash Memory Library Graphic Lcd Library IC Library Keypad Libra
64. sbit at TRISF1 bit var error word ErrorCount chr counter byte rcevd byte begin ErrorCount 0 che counter 0 ADPCFG OxFFFF Configure AN pins as digital I O Led Tage 7 Initialize LCD Led_Cmd _ LCD CLEAR Clear LCD display Man Receive Init Initialize Receiver while TRUE do Endless loop begin Led Cmd LCD FIRST ROW Move cursor to the 1st row while TRUE do Wait for the start byte begin byte _revd Man Receive error Attempt byte receive if byte rcvd 0x0B then Start byte see Transmitter example break We got the starting sequence if error lt gt 0 then Exit so we do not loop forever break MikroElektronika 384 mikroPascal PRO for dsPIC30 33 and PIC24 end repeat begin byte rcvd Man Receive error Attempt byte receive if error lt gt 0 then If error occured begin Led Chr CPi V2 js Write question mark on LCD Inc ErrorCount Update error counter if ErrorCount gt 20 then In case of multiple errors begin an Synchro Try to synchronize again Man Receive Init Alternative try to Initialize Receiver again ErrorCount 0 Reset error counter end end else No error occured begin if byte rcvd lt gt 0x0E then If End byte was received see Transmitter example begin do not write anymore received byte on LCD Led Chr CP byte rcvd else write character on LCD Inc chr_ counter
65. 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 s string 5 5 mik s 0 is char literal m sfl 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 since overwriting the end of a string will cause an unpredictable behavior String Concatenating mikroPascal PRO for dsPIC30 33 and PIC24 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 MikroElektronika 205 mikroPascal PRO for dsPIC30 33 and PIC24 Here is an example var msg string 20 res txt string 5 res channel word begin rae 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 Result of ADC Ud sss Notes In current version plus operator for concatenating strings will accept at most two operands mikroPascal PRO for dsPIC30 33 and PIC24 includes a String Library which automatizes string rela
66. 0 logical zero and 1 logical one var oldstate bit oldstate 0 ADPCFG OxFFFF initialize AN pins as OxFFFF initialize PORTD as 0x0000 initialize PORTB as while TRUE do begin if Button PORTD 0 DL 1 detect logical one on RBO pin oldstate 1 if oldstate and Button PORTD 0 1 0 then begin detect one to zero transition on RBO pin LATB not LATB oldstate 0 end endless loop MikroElektronika 655 mikroPascal PRO for dsPICSO 33 and PIC24 C Type Library The mikroPascal PRO for dsPIC30 33 and PIC24 provides a set of library functions for testing and mapping characters Library Functions isalnum isalpha iscntrl isdigit isgraph islower ispunct isspace isupper isxdigit toupper tolower isalnum Prototype function isalnum character byte word Function returns OxFF if the character is alphanumeric A Z a z 0 9 otherwise returns zero res isalnum o returns OxFF res isalnum r returns 0 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 isalpha 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
67. 0x87 7B 0x83D6 0x8163 0x8027 Ox7FF6 Ox7FA7 Ox7FOA Ox7E1E Ox7CE4 0x7B5D 0x798A 0x77 oC 0x7505 027255 Ox6F5F 0x6C24 Ox68A7 0x64E9 Ox60EC Ox5CB4 0x5843 0x539B Ox4ECO 0x49B4 Ox447B Ox3F17 0x398D Ox33DF Ox2E11 0x2827 0x2224 OxLCOC Ox15E2 0x8163 0x8027 0x8027 0x8163 0x83D6 0x877B Ox8C4A 0x9236 029930 0xA129 OxAAOA 0xB3C0 OxBE32 0xC946 OxD4E1 OxEOE6 OxED38 OxF9B8 OxFCDC OxF695 OxF055 OxEA1E OxE3F4 OxDDDC OxD7D9 OxDI1EF OxCC21 OxC673 OxCOES OxBB85 OxB64C 0xB140 OxAC65 OxA7BD OxA34C Ox9F14 0x9B17 0x9759 0x93DC Ox90A1 Ox8DAB Ox8AFB 0x8894 0x8676 0x84A3 Ox831C Ox81k2 OxOFAB 0x0324 OxF695 OxEA1E OxDDDC OxD1EF 0xC673 OxBB85 0xB140 OxA7BD Ox9F14 0x9759 Ox90A1 Ox8AFB 0x8676 Ox831C Ox80F6 Ox800A Ox7FEA Ox7F87 Ox7ED6 Ox7DD6 Ox7C89 Ox7AEF 0x790A Ox76D9 0x7460 0x719E 0x6E97 0x6B4B 0x 67BD Ox63EF Ox5SFE4 Ox5B9D Ox571E 0x5269 0x4D81 0x486A 0x4326 0x3DB8 03825 0x326E Ox2C99 Ox26A8 0x209F 0x1A83 0x1455 Ox80F6 Ox800A 0x8059 0x81E2 0x84A3 0x8894 Ox8DAB 0x93DC OxSB17 OxA34C OxAC65 OxB64C OxCOE9 OxCC21 0xD7 DS OxE3F4 OxF055 OxF CDC OxFB4A OxF505 OxEEC6 OxE892 OxE26D OxDeS9 0xD65C 0xD079 OxCAB2 OxC50D OxBF8C OxBA33 0xB505 0xB005 0xAB36 OxA69C 0xA238
68. 208690 781F80 200060 781F80 200020 781F80 O7FF7F ot 0O t lt 5PC gt lt US gt B1006F 200CC8 273987 ED200E SAFFFE ED2010 3AFFFC 200010 0 lt FF gt lt 5PC gt 9 781F80 07FF35 B1002F 208700 781F80 200010 781F80 200010 lt U5S gt x5 lt BELL gt j 781F80 07FF6D BIOO6F 208810 781F80 200050 781F80 200020 lt US gt xm lt BELL gt o 1 gt 127 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 CHAPTER 9 Software Simulator Overview MikroElektronika 128 mikroPascal PRO for dsPICSO 33 and PIC24 Software Simulator The Source level Software Simulator is an integral component of the mikroPascal PRO for dsPIC30 33 and PIC24 environment It is designed to simulate operations of the Microchip dsP IC30 33 and PIC24 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 Elg Device Name p30F4013 Hp MCU Clock Choose Release type if you want to use software simulator Frequency 80 000000 MHz E Build Debugg Build Type gt Release ICD Debug Debugger Software O mikroIcb After you have successfuly compiled your project you can run the Software Simulator by selecting Run gt Start Debugger from the drop down menu or by clicking the Start Debugger Icon f
69. Example mPdsPIC exe MSF DBG p30F4013 Y DL 011111114 f 080 N C Lcd Lcd mppds SP C Program Files Mikroelektronika mikroPascal PRO for dsPIC Defs SP C Program Files Mikroelektronika mikroPascal PRO for dsPIC Uses SP C Led __ Lib Math mcl Lib MathDouble mcl Lib System mcl Lib Delays mcl Lib LcedConsts mcl Lib Led mcl Lcd mpas MikroElektronika 114 mikroPascal PRO for dsPICSO 33 and PIC24 Parameters used in the example DBG Generate debug info DL All files built as libraries MSF Short Message Format used for internal purposes by IDE p30F4013 MCU 30F4013 selected y Dynamic link for string literals enabled 011111114 Miscellaneous output options 080 Set oscillator frequency in MHz N C Lced Led mppds SP C Program Files Mikroelektronika mikroPascal PRO for dsPIC Defs Output files generated to file path specified by filename SP C Program Files Mikroelektronika mikroPascal PRO for dsPIC Defs Add directory to the search path list SP C Program Files Mikroelektronika mikroPascal PRO for dsPIC Uses Add directory to the search path list SP C Lced Add directory to the search path list Lced mpas Lib Math mcl Lib MathDouble mcl Lib System mcl Lib_ Delays mcl Lib LcdConsts mcl Lib Lcd mcl Specify input files 115 MikroElektro
70. Led 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 MikroElektronika 84 mikroPascal PRO for dsPIC30 33 and PIC24 Step 3 Move the pointer over the corresponding portion of the guide diamond An outline of the window appears in the designated area a man 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 ER To set the layout select the desired layout from the layout drop down list and click the Set Layout Icon om i To remove the layout from the drop down list select the desired layout from the list and click the Delete Layout Icon id lt Default Layout gt Code Layout Debug Layout fe 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 on the title bar of the window mikoPascal PRO for dsPIC30 33 and PIC24 Project Manager x a PS S ESS as G aa B Sources E Lcd mpas i Binaries P
71. MICROCHIP RADIX 1 15 Oie 4308E49C 86 08 E4 9C 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 dsPIC 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 MikroElektronika 14 mikroPascal PRO for dsPICSO 33 and PIC24 The Macro offers the following commands Men o o o Starts recording keystrokes for later playback Stops capturing keystrokes 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 dsPIC30 33 and PIC24 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 EE Project Manager 1 1 RS4 85_Master_Example mppds 7e e832 64 else amp amp RS485_
72. Note Code Watch Window is available only when mikrolCD is selected as a debugger To show the Code Watch Window select Debug Windows gt 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 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 Read Code 000000 A75010 A822CA 470060 464010 4902CA 474010 4802C4 2088C0 lt DLE gt P E G lt DLE A60010 A802D6 A70010 A902D6 07FF96 470060 A63010 A962CA lt DLE gt O lt STX gt lt DL A73010 Ag62CA 470060 A62010 A942CA A72010 A842cA 470060 lt DLE gt 05 b G lt DLI A61010 A922CA A71010 A822CA 470060 A60010 A902CA A70010 lt DLE gt lt DLE gt lt DI 4802CA 2088C0 460010 4802D6 470010 4902D6 07FF7C 2oaeco lt STX gt lt SPC gt lt D A60010 370002 07FF64 370001 07FF86 FA8000 o60000 FAooo2 lt DLE gt lt 5TX gt 7d lt 37000F 200800 9FBF40 370019 200c00 9FBF40 370016 200940 lt SI gt 7 lt B5 gt lt 5PC gt 9FBF40 370013 200040 9FBF40 370010 200800 9FBF40 370000 lt DC3 gt 7 lt CR gt 97B84E E10061 32FFEE 97B84E E10062 32FFEE 97B84E E10063 N
73. Parameters address starting address of the FLASH memory block to be read write to starting address of RAM buffer for storing read data Returns Starting address of RAM buffer for storing read data var flash address longint cArr array 4 of word ptr data gt word flash_address 0x006000 ptr_data cArr FLASH Read4 flash_address ptr_data The user should take care of the address alignment see the explanation at the beginning of this page MikroElektronika 342 mikroPascal PRO for dsPICSO 33 and PIC24 FLASH_Read4_Compact Prototype procedure FLASH Read4 Compact flash_address longint write _to word Reads one latch row 4 instructions 8 addresses in the compact mode Parameters address starting address of the FLASH memory block to be read write to starting address of RAM buffer for storing read data Returns Starting address of RAM buffer for storing read data var flash address longint cArr array 8 of word ptr data word flash_address 0x006000 ptr data cArr FLASH Read4 Compact flash_address ptr_ data pee The user should take care of the address alignment the explanation at the beginning of this page PIC24 and dsPIC33 Functions FLASH_Erase procedure FLASH Erase address longint C erase the flash memory block starting from address 0x006400 var flash address longint flash address 0x006400 FLASH _Erase flas
74. Please read the appropriate datasheet before utilizing this library MikroElektronika 366 mikroPascal PRO for dsPIC30 33 and PIC24 I2Cx_Write Prototype function I2Cx Write data_ byte word Sends data byte via the C bus data_ data to be sent 0 if there were no errors 1 if write collision was detected on the I C bus Requires MCU with at least one I C module Used 1 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 12Cx_Start var data byte error word T2C1 Write data_ I2Cl_ Write 0xA3 IC 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 C modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library I2Cx_Stop Requires MCU with at least one I C module Used C module must be initialized before using this function See I2Cx_Init routine Issue STOP signal T2 1 Step IC 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 C modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library
75. Previously a command must be sent through 1D13700_Write_Command routine S1D13700 Write Command S1D13700 CSRW set cursor address 51013700 Write Parameter Lo start send lower byte of cursor address S 1D13700_ Write Parameter Hi start send higher byte cursor address 1D13700_Read_Parameter PRetums Nothing SSS Example parameter S1D13700 Read Parameter S1D13700_Fill Prototype si aa 91013700 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 1D13700 Fill 0x20 0x3000 Ox7FFF 329 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 Gicd module needs to be initialized See the S1D13700_Init routine clear current graphic panel 1D13700 GrFill 0 1D13700_TxtFill Prototype procedure S1D13700_ TxtFill d byte Description Fill current text panel with appropriate value 0 to clear Parameters d this value will be used to fill text pa
76. 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 SPI1 Read SPI1 Write Sets the SPI1 module active Number of SPI modules 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 RAO pin as input TRISB1 bit 1 Set RAI pin as input Chip Select 1 Deselect DAC Chip Select Direction 0 Set CS pin as Output SPIL Ins 60 Initialize SPI module end DAC increments 0 4095 gt output voltage 0 Vref procedure DAC Output valueDAC word var temp byte begin Chip Select 0 Select DAC chip Send High Byte 472 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 temp word valueDAC shr 8 and Ox0F Store valueDAC 11 8 to temp 3 0 temp temp or 0x30 Define DAC setting see MCP4921 datasheet SPI1 Write temp Send high byte v
77. SPIx_Init_ Advanced routines 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 S 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 PRI 4 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 IDLE MMC SD card has to be formatted to FAT16 file system MikroElektronika 392 mikroPascal PRO for dsPICSO 33 and PIC24 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 appropr
78. SPIx_Write SPI_Set_Active MikroElektronika 467 mikroPascal PRO for dsPIC30 33 and PIC24 SPIx_Init Prototype procedure SPIx Init Description Configures and initializes the SPI module with default settings Default settings Master mode 8 bit data mode secondary prescaler 1 1 primary prescaler 64 1 Slave Select disabled input data sampled in the middle of interval clock idle state low Serial output data changes on transition from active clock state to idle clock state MCU must have the SPI1 module Initialize the SPI1 module with default settings SPIL Init 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 468 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPIx_Init_Advanced Prototype procedure SPIx_Init _Advanced master_ mode model6 sec _prescaler pri_ prescaler slave select data_sample clock_idle edge word Description Configures and initializes the SPI module with user defined settings Parameters Parameters master mode model6 sec _
79. TBI 1 enable ECAN1 tx interrupt C1LINTE RBIE 1 enable ECAN1 rx interrupt PORTB 0 clear PORTB TRISB 0 set PORTB as output for received message data displaying Can Init Flags 0 oe Can Send Flags 0 clear flags Can Rev Flags 0 Can_ Send Flags _ECAN TX PRIORITY 0 and Form value to be used _ECAN TX _XTD FRAME and with CANSendMessage ECAN TX NO RTR FRAME Can Init Flags ECAN CONFIG SAMPLE THRICE and Form value to be used ECAN CONFIG PHSEG2 PRG ON and with CANInitialize ECAN CONFIG XTD MSG and ECAN CONFIG MATCH MSG TYPE and ECAN CONFIG LINE FILTER OFF ECAN1DmaChannelInit 0 1 ECANIRxTxRAMBuffer init dma channel 0 for dma to ECAN peripheral transfer ECAN1DmaChannelInit 2 0 ECANIRxTxRAMBuffer init dma channel 2 for ECAN peripheral to dma transfer ECANIInitialize 1 3 3 3 1 Can_Init_Flags initialize ECAN ECAN1SetBufferSize ECAN1RAMBUFFERSIZE set number of rx tx buffers in DMA RAM ECAN1SelectTxBuffers 0x000F select transmit buffers 0x000F buffers 0 3 are transmit buffers ECAN1SetOperationMode _ECAN MODE CONFIG OxFF set CONFIGURATION mode ECAN1SetMask _ECAN MASK 0 lars ECAN CONFIG MATCH MSG TYPE and ECAN CONFIG XTD MSG set all mask1 bits to ones ECAN1SetMask _ECAN MASK 1 i ECAN CONFIG MATCH MSG TYPE and ECAN CONFIG XTD MSG set all mask2 bits to ones ECAN1SetMask _ECAN
80. The function sets Port Expander s PortA pull up down resistors Parameters ModulecAddress 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_lInit Set Port Expander s PORTA pull up resistors Expander Set _PullUpsPortA 0 SFF Notes None OOS MikroElektronika 423 mikroPascal PRO for dsPICSO 33 and PIC24 Expander_Set_PullUpsPortB Prototype procedure Expander Set PullUpsPortB ModuleAddress Data byte The function sets Port Expander s PortB pull up down resistors Parameters ModulecAddress 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_lInit Set Port Expander s PORTB pull up resistors Expander Set _PullUpsPortB 0 OxFF Expander_Set_PullUpsPortAB Prototype procedure Expander Set PullUpsPortAB ModuleAddress byte PullUps word The function sets Port Expander s PortA and PortB pull up down resistors Parameters ModulecAddress Port Expander hardware address see schematic at
81. Write a code for your library and save it 4 Add Lib Example file in some project see Project 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 mcl should appear in mikroPascal PRO for dsPIC 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 dsPIC Defs and it is named MCU_NAME mlk for example 30F4013 m1lk 7 Add the the following segment of code to lt LTBRARIES gt node of the definition file definition file is in XML format lt LIB gt lt ALIAS gt Example Library lt ALIAS gt lt FILE gt 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 mc1 file Fo
82. 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 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 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 MODI MikroElektronika 973 mikroPascal PRO for dsPICSO 33 and PIC24 T6963C_write_text Prototype ae 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
83. Writes data from the EEPROM window into MCU s internal EEPROM memory EEPROM Watch Read EEPROM Write EEPROM FF FF FF FF FF FF FF FF FF FF FF FF FF FF o0 o0 00 00 00 00 oo oo 00 oo 00 nn STATUS Idle MikroElektronika 126 mikroPascal PRO for dsPIC30 33 and PIC24 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 gt 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 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 A822CA 470060 A64010 A902CA A74010 asozca 2ogeco lt DLE gt P5 G lt DE 60010 A802D6 A70010 A902D6 07FF96 470060 A63010 A962CA lt DLE gt lt 5TX gt lt DL A73010 A862CA 470060 A62010 AS42CA A72010 A842CA 470060 lt DLE gt 0 Eb G lt DLI A61010 A922CA A71010 A822CA 470060 A60010 A902CA A70010 lt DLE gt lt DLE gt E lt DI asozca 2088CO A60010 A802D6 A70010 A902D6 07FF7C 2088co lt STX gt lt SPC gt lt D 60010 370002 07FF64 370001 07FF86
84. XOR compares pairs of bits and generates a 1 result if the bits are complementary otherwise shr it returns 0 bitwise complement unary inverts each bit bitwise shift left moves the bits to the left discards the far left bit and assigns 0 to the right most bit 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 equals 1230 because 1234 0001 0010 0011 0100 5678 0101 0110 0111 1000 and 0001 0010 0011 0000 that is 1230 Similarly 1234 or 5678 equals 567C 1234 xor 5678 equals S444C not 1234 equals SEDCB 218 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Unsigned and Conversions If anumber is converted from less complex to more complex data type the upper bytes are filled with zeroes If a num ber 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 SOOAO Signed and Conversions If number is converted from less complex to more complex data type the upper
85. a variable followed by colon sign as label byte var3 adding a comment solves the parsing problem opmode 2 end Nested Case Statements Note that the case statements can be nested values are then assigned to the innermost enclosing case statement 226 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Iteration Statements Iteration statements let you loop a set of statements There are three forms of iteration statements in mikroPascal PRO for dsPIC30 33 and PIC24 for while do do 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 cont inue begins executing the next iteration of the sequence For Statement The for statement implements an iterative loop and requires you to specify the number of iterations The syntax of the for statement is for counter initial value to final value do statement list of OL 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 counteris setto 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 willbe executed
86. 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 4 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 9600 delim OK while TRUE do begin if UART1 Data Ready 1 then begin UARTI Read Text txt delim 10 UART1 Write Text txt end end
87. gram function or procedure block including all blocks enclosed within that scope Identifiers in the out ermost scope file scope of the main unit are referred to as globals while other identifiers are locals IIdentifier is declared in the interface section of a Scope extends the interface section of a unit from the point where it is 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 section Scope extends from the point where it is declared to the end of the unit of a unit but not within the block of any function or The identifier is available to any function or procedure in the unit 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 Name Spaces Name space is a scope within which an identifier must be unique The mikroPascal PRO for dsPIC30 33 and PIC24 uses two distinct categories of identifiers 1 Global variables are visible throughout the
88. in all projects using SPI Ethernet Description ENC24J600 Library var SPI Ethernet _24j600 CS 3 F var SPI Ethernet_24j600 CS sbit at sbit sfr external ENC24J600 chip select pin LATF1 bit var SPI Ethernet 247600_ CS Direction sbit sfr external Direction of the ENC24J600 chip var SPI Ethernet _24j600 CS Direction select pin sbit at TRISF1 bit The following routines must be defined in all project using SPI Ethernet Description ENC24J600 Library p function SPI Ethernet_24j600_UserTCP var remoteHost array 4 of byte Refer to the library remotePort word TCP request example atthe bottom localPort word handler of this page for code reqLength word implementation var flags TEthj600PktFlags word function SPI Ethernet 24j600 UserUDP var remoteHost array 4 of byte a z E Refer to the library remotePort word UDP request example at the bottom destPort word handler of this page for code reqLength word implementation var flags TEthj600PktFlags word 500 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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_
89. mikoPascal PRO for dsPIC30 33 and PIC24 IIR Filter Library mikroPascal PRO for dsPIC30 33 and PIC24 includes a library for Infinite Impulse Response IIR filter All routines work with fractional Q15 format A infinite impulse response IIR filter is a type of a digital filter whose impulse response the filter s response to a delta function is non zero over an infinite length of time Library Routines IIR_Radix IIR_Radix Prototype function IIR Radix BScale integer AScale integer ptrB word ptrA word FilterOrder word ptrInput word InputLen word ptrOutput word Index word word This function applies IIR filter to ptriInput Parameters BScale B scale factor AScale Ascale factor ptrB pointer to B coefficients in program memory ptrA pointer to A coefficients in program memory FilterOrder order of the filter 1 ptrinput address of input samples InputLen number of samples ptrOutput pointer to output samples Output length is equal to Input length Index index of current sample N M W y n gt Acoeff n x n k gt Bcoef k y n kl k 0 k 1 const BUFFER SIZE A const FILTER ORDE const COEFF B array LTER_ORDER 1 of word 0x0548 Ox1FAE Ox4F34 0x699B Ox4F34 Ox1lFAE 0x0548 const COEFF A array FILTER ORDER 1 of word 0x4000 OxB3FE 0x5389 OxD4D8
90. 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 CD1 sbit at RB4 bit CF Chl sit at LATBS bit for writing CF A2 sbit at LATB2 bit for writing CF Al sbit at LATB1 bit for writing CF AQ sbit at LATBO bit for writing CF_RDY direction sbit at TRISB7 bit CF WE direction sbit at TRISB6 bit CF OP direction sbit at TRISB5 bit CF CDI direction sbit at TRISB4 bit CF_CEH1 direction sbit at TRISB3 bit CF A2 direction sbit at TRISB2 bit CF Al direction sbit at TRISB1 bit CF AO direction sbit at TRISBO bit end of compact fash pinout Gf Init initialize CF MikroElektronika 280 mikroPascal PRO for dsPIC30 33 and PIC24 Cf_Detect Proteus Checks for presence of CF card by reading the chip detect pin Parameters None 1 if CF card was detected 0 otherwise The corresponding MCU ports must be appropriately initialized for CF card See Cf_Init Wait until CF card is inserted while Cf Detect 0 do nop dsPIC30 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_
91. simply change the letter x in the routine prototype for a number from 1 to 2 Number of ECAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library ECANxSetBufferSize Prototype function ECANxSetBufferSize EcanlBuffSize word word The function configures the total number of receive and transmit buffers in DMA RAM Parameters EcanlBuffSize Number of ECAN DMA RAM receive and transmit buffers Valid values 4 6 8 12 16 24 32 Each buffer is 16 bytes long 0 if input parameter is valid OxFFFE if input parameter is invalid Requires The ECAN routines are supported only by MCUs with the ECAN module Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus The ECAN module must be initialized See the ECANxInitialize routine DMA RAM will have 16 rx tx buffers ECAN1SetBufferSize 16 The same value should be used for DMA RAM buffer definition in the ECan_Defs mpas header file located in the ECAN project folder ECAN library routine require you to specify the module you want to use To select the desired ECAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of ECAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 303 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 ECA
92. var remoteHost array 4 of byte remotePort word destPort word reqLength word var flags TEthPktFlags word Refer to the library example at the bottom UDP request handler of this page for code implementation 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_getGwlipAddress SPI_Ethernet_getDnslpAddress SPI_Ethernet_getlpMask SPI_Ethernet_confNetwork SPI_Ethernet_arpResolve SPI_Ethernet_sendUDP MikroElektronika 475 mikroPascal PRO for dsPIC30 33 and PIC24 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 ENC28 760 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 transmi
93. 0 Set DriveB pin as output GLed Tnat iz Initialize GLCD Gled_Fill 0 Clear GLCD ADOL Init Initialize ADC TP Tne 128 64 6 7I Initialize touch panel TP_Set_ADC_Threshold 3900 Set touch panel ADC threshold end procedure Calibrate begin GLed Dot 0 63 1 7 Draw bottom left dot Gled Write Text TOUCH BOTTOM LEFT 12 3 1 TP Calibrate Bottom Left Calibration of bottom left corner Delay ms 1000 Gled Dot 0 63 0 Clear bottom left dot Gled Dot 127 0 1 7 Draw upper right dot Glcd Write Text S12 T Gled Write Text TOUCH UPPER RIGHT 12 4 1 TP Calibrate Upper Right Calibration of upper right corner Delay _ms 1000 end begin write msg WRITE clear_msg CLEAR erase msg ERASE MikroElektronika 611 mikroPascal PRO for dsPIC30 33 and PIC24 Initialize Gled Pal l 0 7 Clear GLCD Gled Write Text CALIBRATION 12 3 1 Delay ms 1000 Gled_Fill 0 Clear GLCD Calibrate Gled_Fill 0 Gled Write Text WRITE ON SCREEN 20 5 2 3 Delay _ms 1000 led Pali 0 T led V_Line 0 7 0 1 7 led Write Text clear msg 1 0 0 led V_Line 0 7 97 1 lcd Write Text erase msg 98 0 0 GI G G G Pen Menu Gled Rectangle 41 0 52 9 1 Glcd_ Box 45 3 48 6 1 Gled Rectangle 63 0 70 7 1 7 Glcd Box 66 3 67 4 1 Gled Rectangle 80 0 86 6 1 Gled Dot 83 3
94. 1D13700_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 display dimension Glcd module needs to be initialized See the 1D13700_Init routine Example eooo mesemes O MikroElektronika 334 mikroPascal PRO for dsPICSO 33 and PIC24 1D13700_Partiallmage Prototype procedure S 1D13700 PartialImage 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 Gicd module needs to be initialized See the 1D13700_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 SIDL3700 Partiallmage 10 12 10 15 16 32 image 339 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Flash M
95. 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 0x2000 use an array consisting of single element const SimpleConstant array 1 of byte 0xAA org 0x800 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 144 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 procedure proc par byte org 0x200 begin Procedure will start at address 0x200 end org directive can be used with main routine too For example program Led Blinking begin org 0x800 main procedure starts at 0x800 end Directive orgall Use the orgal1 directive to specify the address above which all routines and constants will be placed Example begin orgall 0x200 All the routines constants in main program will be above the address 0x200 end MikroElektronika 145 mikroPascal PRO for dsPICSO 33 and PIC24 Built in Routines mikroPascal PRO for dsPIC30 33 and PIC24 compiler provides a set of useful built in utility functions Built in functions do not have any special requirem
96. 33 and PIC24 Library Example This example reads the temperature using DS18x20 connected to pin RF6 After reset MCU obtains temperature from the sensor and prints it on the Lcd Be sure to set Fosc appropriately in your project to pull up RF6 line and to turn off the PORTF leds Copy Code To Clipboard program OneWire LCD module connections var LCD RS sbit at LATB4 bit var LCD EN sbit at LATB6 bit var LCD D4 sbit at LATD4 bit var LCD D5 sbit at LATDS bit var LCD D6 sbit at LATD6 bit var LCD D7 sbit at LATD7 bit var LCD RS Direction sbit at TRISB4 bit var LCD EN Direction sbit at TRISB6 bit var LCD D4 Direction sbit at TRISD4 bit var LCD D5 Direction sbit at TRISDS bit var LCD D6 Direction i sbit at TRISD6 bit var LCD D7 Direction sbit at TRISD7 bit End LCD module connections Set TEMP RESOLUTION to the corresponding resolution of used DS18x20 sensor 18820 9 default setting can be 9 10 11 or 12 i18B20 12 const TEMP RESOLUTION byte 9 var text array 9 of char temp word procedure Display Temperature temp2write word const RES SHIFT TEMP RESOLUTION 8 var temp whole byte temp fraction word begin text 000 0000 Check if temperature is negative if temp2write and 0x8000 then begin text 0 temp2write not temp2write 1 end Extract temp whole temp whole word te
97. 33 and PIC24 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 the first closed brace This gives us word which would generate a syntax error Tokens Token is the smallest element of a mikroPascal PRO for dsPIC30 33 and PIC24 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 dsPIC30 33 and PIC24 recognizes the following kinds of tokens keywords identifiers constants operators punctuators also known as separators MikroElektronika 181 mikoPascal PRO for dsPIC30 33 and PIC24 Token Extraction Example Here is an example of token extraction Take a look at the following example code sequence end flag i 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 Literals Literals are tokens representing fixed numeric or character values The data type of a constant is deduced by the compiler using such c
98. 42 write data to the assigned file Mmc_Fat_Set_File_Date Prototype Description Parameters Requires procedure Mmc Fat Set File Date year word month byte day byte hours byte mins byte seconds byte Sets the date time stamp Any subsequent file write operation will write this stamp to the currently assigned file s time date attributes 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 Nothing 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 Ist 2005 18 07 00 Mmc Fat Set File Date 2005 4 1 18 7 0 None 397 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 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
99. 633 HID_Write 633 HID_ Disable 634 USB _Interrupt_Proc 634 USB_Polling_Proc 634 Gen_Enable 635 Gen_Read 635 Gen_Write 635 Library Example 636 HW Connection 636 Digital Signal Processing Libraries 637 Digital Signal Processing Libraries 637 FIR Filter Library 638 Library Routines 638 MikroElektronika A mikroPascal PRO for dsPICSO 33 and PIC24 FIR_Radix 638 IIR Filter Library 639 Library Routines 639 IIR_Radix 639 FFT Library 640 Library Dependency Tree 640 FFT 640 Twiddle Factors 641 TwiddleCoeff_64 641 TwiddleCoeff_128 641 TwiddleCoeff_256 641 TwiddleCoeff_512 642 Bit Reverse Complex Library 644 Library Routines 644 BitReverseComplex 644 Vectors Library 645 Library Routines 645 Vector_Set 645 Vector_Power 646 Vector_Subtract 646 Vector_Scale 647 Vector_Negate 647 Vector_Multiply 648 Vector_Min 648 Vector_Max 649 Vector Dot 649 Vector_Correlate 650 Vector_Convolve 651 Vector_Add 651 Matrix Library 652 Matrices Library 652 Library Routines 652 Matrix_Transpose 652 Matrix_Subtract 653 Matrix_Scale 653 Matrix_Multiply 654 Matrix_Add 655 Miscellaneous Libraries 656 Button Library 656 Library Routines 656 Button 657 C Type Library 658 Library Functions 658 isalnum 658 isalpha 658 MikroElektronika 25 mikoPascal PRO for dsPIC30 33 and PIC24 iscntrl 658 isdigit 659 isgraph 659 islower 659 ispunct 659 isspace 659 isupper 660 isxdigit 660 toupper 660 tolower 660 Conversions Library
100. 80564774407 10 Here are some examples QO 0 0 1 23 ff 1 23 23 45e6 23 45 10 6 2e 5 Lf 2 0 LO 5 3E 10 3 0 10 10 09E34 0 09 10 34 Character Literals Character literal is one character from 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 dsPIC30 33 and PIC24 String Literals String literal is a sequence of characters from the extended ASCII character set enclosed with quotes 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 quotes null string is stored as a single nu11 character You can assign string literal to a string variable or to an array of char 183 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Here are several string literals Hello world message 12 chars long Temperatur
101. ADC C BitReverseComplex C Button CO can C can_spr o Conversions C_Type C EEPROM Ej ret C FirRadix C FLASH C Gled O Gled_Fonts Fi tec O TirRadix C Keypad4x4 Led Led_Constants Manchester C Matrices Mme Mmc_FAT16 C one_Wire C Port_Expander PS2 a O pwm teon o Description S O E Refresh Library by scanning files in Uses folder Useful when new libraries are added by copying files to BB BBB BBB BB GB D E ay E 2 8 E Uses folder Sy pn ra a a a MikroElektronika 64 mikroPascal PRO for dsPICSO 33 and PIC24 Managing libraries using Package Manager The Package Manager is a tool which enables users to easily install their own libraries in the mikrolIDE 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 E Library Manager ix Powe C Sound O spr C SPI_Ethernet C SPI_Gled CO SPILed CO S5PI_Lede C sPI_T6963C C Sprintf C Sprinti C Sprint E T6963C C Time C TouchPanel amp Trigonometry Om C UART E Conversions onversions2 a ByteToBinaryStr WordToBinaryStr LongWordToBinaryStr BinaryToGray GrayToBinary w From
102. 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 CRE STOP_BYTE OxA9 DATALEN bits bit7 1 MASTER SENDS 0 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 0 DATA3 if exists UNCHANGED bit3 1 DATA2 if exists WAS XORed with 1 IT WAS EQUAL TO START BYTE or STOP BYTE 0O DATA2 if exists UNCHANGED bit2 1 DATA1 if exists WAS XORed with 1 IT WAS EQUAL TO START BYTE or STOP BYTE 0O DATA if exists UNCHANGED bitlbitO 0 to 3 NUMBER OF DATA BYTES SEND CRC generation cre send datalen xor address cre send ore send xor data 0 if exists ere send cre send xor data 1 if exists crc_send crc_send xor data 2 if exists cre send cre send not cre send if crc_send START BYTE or cro send STOP BYTE then ere send i cre send 17 NOTE DATALEN lt 4 0 gt can not take the START BYTE lt 4 0 gt or STOP BYTE lt 4 0 gt values 448 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Software I C Library The mikroPascal PRO for dsPIC30 33 and PIC24 provides routines for implementing So
103. CHAPTER 10 Tutorials Managing Project Projects New Project New Project Wizard Steps Customizing Projects Managing Project Group Add Remove Files from Project Project Level Defines Source Files Managing Source Files Creating new source file Opening an existing file Printing an open file Saving file Saving file under a different name Closing file Search Paths Paths for Source Files mpas Edit Project Clean Project Folder Compilation Output Files Assembly View Creating New Library Multiple Library Versions Using Microchip MPLAB IDE with mikroElektronika compilers Debugging Your Code Using MPLAB ICD 2 Debugger Using MPLAB Simulator Frequently Asked Questions Can use your compilers and programmer on Windows Vista Windows 7 690 690 690 690 690 691 691 692 692 692 692 693 693 693 693 694 694 698 698 698 699 700 700 700 700 700 700 700 701 701 702 702 703 704 704 704 705 705 706 706 706 713 718 718 MikroElektronika 28 mikroPascal PRO for dsPIC30 33 and PIC24 am getting Access is denied error in Vista how to solve this problem 718 What are differences between mikroC PRO mikroPascal PRO and mikroBasic PRO compilers 718 Why do they have different prices 718 Why do your PIC compilers don t support 12F508 and some similar chips 718 What are limitations of demo versions of mikroElektronika s compilers 718 Why do still get demo limit error wh
104. CONFIG MSG TYPE BIT byte 08 CANSPI CONFIG STD MSG byte FF XXXX1XXX CANSPI CONFIG XTD MSG byte SF7 XXXXOXXX CANSPI CONFIG DBL BUFFER BIT byte 10 CANSPI CONFIG DBL BUFFER ON byte FF XXX1XXXX CANSPI CONFIG DBL BUFFER OFF byte SEF XXXOXXXX CANSPI CONFIG MSG BITS byte 60 CANSPI CONFIG ALL MSG byte FF X11XXXXX CANSPI CONFIG VALID XTD MSG byte DF X10XXXXX CANSPI CONFIG VALID STD MSG byte BF XO1XXXXX CANSPI CONFIG ALL VALID MSG byte S9F XOOXXXXX MikroElektronika 210 mikroPascal PRO for dsPICSO 33 and PIC24 You may use bitwise and to form config byte out of these values For example Copy Code To Clipboard 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 3 1 ares 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 0 byte FC ff BXXRRKOO _CANSPI_TX PRIORITY 1 byte FD FT RXXXXKOI _CANSPI_ TX PRIORITY 2 byte SFE Sf MHKREXLO _CANSPI_TX PRIORITY 3 byte SFF FT MRT CANSPI TX FRAME BIT byte 08 CANSPI TX STD FRAME
105. Complete Hexadecimal i ca Identifier e Illegal Char Style Number Octal Preprocessor Reserved Word Space String Symbol web link Text Attributes Bold E Underline T Italic F Strikeout Foreground Background m Elack DEL Bleck x Active Line Color C7 Custom v V show Active Line Gutter Colors Gradient From Gradient To E Sky Blue Cj white Font R Bue Tools Output MikroElektronika 56 mikroPascal PRO for dsPIC30 33 and PIC24 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 Editor Settings Y Enable Auto Correct ah Add Original Replacement Vy 9 Remove Editor Colors e Auto Correct Advanced J Tools V Correct Case to Match Declaration Y Show Notification f 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 5 MikroElektronika mikoPascal PRO for dsPIC30 33 and P
106. Delay end while TRUE do For LCD with more than For LCD with more than Move text to the right Endless loop two rows two rows 4 times begin for counter 0 to 6 do Move text to the left 7 times begin Spi Led Cmd LCD SHIFT LEFT Move Delay end MikroElektronika 937 mikroPascal PRO for dsPIC30 33 and PIC24 for counter 0 to 6 do Move text to the right 7 times begin Spi Led Cmd LCD SHIFT RIGHT Move _Delay end end end EE E LOY IdSP Led HW connection by default initialization using SPI_Lced_Init mikoPascal PRO for dsPIC30 33 and PIC24 SPI Lcd8 8 bit interface Library The mikroPascal PRO for dsPIC30 33 and PIC24 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 When using this library with dsPIC33 and PIC24 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 Se
107. 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 MikroElektronika 198 mikroPascal PRO for dsPICSO 33 and PIC24 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 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 function 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
108. ECAN_MASK Constants The ECAN MASK constants define mask codes The routine ECANxSetMask expect one of these as their argument Copy Code To Clipboard const _ECAN MASK 0 word 0 _ECAN MASK 1 word _ECAN MASK 2 word 2 ll an se ECAN FILTER Constants The ECAN FILTER constants define filter codes The routine ECANxSetFilter expect one of these as their argument ont MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Copy Code To Clipboard const LTER 0 LTER 1 LTER 2 LTER 3 LTER 4 TER 5 LTER 6 LTER_7 LTER 8 LTER_9 TER 10 LTER 11 LTER 12 LTER_13 LTER 14 LTER_15 word word word word word word word word word word word word word word word word ECAN_RX_BUFFER Constants The ECAN RX BUFFI their argument Copy Code To Clipboard Ni Se Ns Pee NPFPOWMIHRHDUAWNHERO Sees Aa NG he Se ap ee SS L3 14a Ly ER constants define RX buffer codes codes The routine ECANxSetFilter expect one of these as const ECAN RX BUFFER 0 word 0 ECAN RX BUFFER 1 word 1 ECAN RX BUFFER 2 word 2 ECAN RX BUFFER 3 word 3 ECAN RX BUFFER 4 word 4 ECAN RX BUFFER 5 word 5 ECAN RX BUFFER 6 word 6 ECAN RX BUFFER 7 word 7 ECAN RX BUFFER 8 word 8 ECAN RX BUFFER 9 word 9 ECAN RX BUFFER 10 word 10 ECAN RX
109. Ethernet 243600 userTimerSec is used to keep track of time It is user responsibility to increment this variable each second in it s code SPI_Ethernet_24j600_doDHCPLeaseTime Prototype function SPI Ethernet 247600 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 lease time has expired it s time to renew it Ethernet module has to be initialized See SPI_Ethernet_24j600_Init while true do begin if SPI Ethernet 243600 doDHCPLeaseTime lt gt 0 then begin it s time to renew the IP address lease MikroElektronika 019 mikroPascal PRO for dsPIC30 33 and PIC24 SPI_Ethernet_24j600_renewDHCP Prototype function SPI Ethernet 24j600 renewDHCP tmax byte byte This is DHCP module routine It sends IP address lease time renewal request to DHCP server tmax time in seconds to wait for an reply 1 upon success lease time was renewed 0 otherwise renewal request timed out Ethernet module has to be initialized See SPI_Ethernet_24j600_Init while true do begin if SPI Ethernet 243600 doDHCPLeaseTime lt gt 0 then begin SPI Ethernet 243600 renewDHCP 5 it s time to renew the IP address lease with 5 secs for a reply en
110. F11 Ctrl Shift Space Ctrl Shift number Ctrl Alt Select cre mikrolCD Debugger and Software Simulator Shortcuts Jump To Interrupt MikroElektronika 112 mikroPascal PRO for dsPICSO 33 and PIC24 Ctrl F5 Add to Watch List Ctrl F8 Step Out Alt D Disassembly View Shift F5 Open Watch Window Ctrl Shift A Show Advanced Breakpoints 113 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 CHAPTER 3 mikroPascal PRO for dsPIC30 33 and PIC24 Command Line Options Usage mPdsPIC exe lt opts gt lt opts gt lt infile gt lt opts gt lt opts gt Infille canbe of c mcl and pid type The following parameters and some more see manual are valid P lt devicename gt MCU for which compilation will be done FO lt oscillator gt Set oscillator in MHz SP lt directory gt Add directory to the search path list lt filename gt Output files generated to file path specified by filename B lt directory gt Save compiled binary files mc1 to directory O Miscellaneous output options DBG Generate debug info L Check and rebuild new libraries DL Build all files as libraries UICD ICD build type EH lt filename gt Full EEPROM HEX file name with path y Dynamic link for string literals LHF Generate Long hex format GC Generate COFF file PF Pass project file name to command line RA Rebuild all sources in project
111. FA8000 oso000 FAooo2 lt DLE gt j lt STX gt 7dy lt 37000F 200800 9FBF40 370019 200c00 9FBF40 370016 200940 lt SI gt 7 lt BS gt lt SPC gt 9FBF40 370013 200040 9FBF40 370010 200800 9FBF40 370000 lt DC3 gt 7 lt CR gt 97B84E E10061 32FFEE 97B84E E10062 32FFEE 97B84E E10063 N a 2N b 32FFEE 97B84E E10064 32FFEE 37FFFO 97B83E 5000E1 570068 TY2N d a1 y2ay7 gt 408010 9FBF40 781F80 07FF98 B1002F 2088co A10010 EF2000 lt DLE gt lt US gt 980700 97B8AE 470060 408010 E00410 32000C 97B8AE 470060 lt BELL gt G lt I 408010 784010 FB8000 781F80 07FF32 B1002F 200011 470060 lt DLE gt lt DLE gt x 408810 37FFEF 2088C0 A00010 FA8000 060000 FA0002 EF2000 lt DLE gt iy7 A lt sPC 984700 90400E E10468 310009 20010 781F80 07FF78 B1002F G lt 50 gt O h lt EOT 07FF31 B3C011 470060 40810 37FFF4 FA8000 060000 FA0002 1 lt BELL gt lt DC1 gt EF2000 984700 90400E E10468 310009 200180 781F80 07FF67 lt 5PC gt G lt 50 gt C B1002F 07FF20 B3C011 470060 400810 S7FFF4 FA8000 oso000 lt 5PC gt lt BELL gt lt C 2088EF 20FFFO B7A020 200000 B7A034 200040 B72044 FA0000 i lt SPC gt lt SPC gt lt 5F 0203D8 000000 2FFFFO B7AZAS O7FF1D 2000c0 781F80 O7FFAF lt ETX gt lt 5TX gt 8 B1002F 208610 781F80 200060 781F80 200010 781F80 07FF87 lt DLE gt t lt SPC gt lt B1006F
112. FO VERTICAL Vertical orientation TFT module needs to be initialized See the TFT_Init routine Example TFT_Set_Font TFT_defaultFont CL_BLACK FO_HORIZONTAL MikroElektronika 593 mikroPascal PRO for dsPICSO 33 and PIC24 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 Nothing 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 DEMO WELCOME 0 094 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 TFTA Sereen CL UAC O OO MikroElektronika 595 mikroPascal PRO for dsPIC30 33 and PIC24 TFT_Dot Prototype procedure TFT Dot x y integer color word
113. File To Project Save By clicking the New button you are prompted to enter a name for the comment 9 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Active Comments Editor Enter comment name activeComment Active Comment Actions New Rename Properties 3 Attributes Url Image File 3 Events OnLeftClick Alt OnRightClick OnDbIClick OnMouseOver Add Image To Project Add File To Project You can notice that when you start typing aname properties pane is automatically displayed so you can edit properties if you wish A Comment 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 Project 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 MikroElektronika 98 mikroPascal PRO for dsPICSO 33 and PIC24 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 onl
114. Files from Project Related topics Project Settings Project Menu Options File Menu Options Project Toolbar Build Toolbar Add Remove Files from Project MikroElektronika 62 mikroPascal PRO for dsPICSO 33 and PIC24 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 Name p30F4013 4 MCU Clock Frequency 80 000000 Build Debugger T Build Type Release ICD Debug Debugger Software O mikroIcD Related topics Edit Project Customizing Projects Project Manager 63 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Library Manager Library Manager enables simple handling libraries being used in a project Library Manager window lists all libraries extension mc1 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 EJ and all libraries will be selected In case none library is needed in a project press the button Clear All 03 and all libraries will be cleared from the project Only the selected libraries will be linked Library Manager als aaa E mikroE E
115. 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 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 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
116. Gap 0x15 in full duplex mode 0x12 in half duplex mode Non Back to Back Inter Packet Gap 00012 in full duplex mode 0x0C12 in half duplex mode Collision window is set to 63 in half duplex mode to accomodate some ENC 247600 revisions silicon bugs CLKOUT output is disabled to reduce EMI generation half duplex loopback disabled LED configuration default LEDA link status LEDB link activity 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 Set transmission speed of 10Mbps Set transmission speed of 100Mbps Note Itis 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 manual negotiation 902 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Requires Global variables SPI Ethernet 2435600 CS Chip Select line SPI Ethernet 243600 CS Direction Direction of the Chip Select pin SPI Ethernet 243600 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
117. IP address remotePort Client s port dest Port 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_24j600_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_setUserHandlers Prototype Description Parameters Requires procedure SPI Ethernet _ 243600 setUserHandlers TCPHandler STSPI_ Ethernet 247600 UserTCP UDPHandler TSPI Ethernet 24 j600 UseruUDP Sets pointers to User TCP and UDP handler function implementations which are automatically called by SPI Ethernet ENC24J600 library TCPHandler TCP request handler UDPHandler UDP request handler Nothing SPI_Ethernet_24j600_UserTCP and SPI_Ethernet_24j600_UserUDP have to be previously defined SPI_ Ethernet _ 243600 setUserHandlers SPI Ethernet 243600 UserTCP SPI_ E
118. LATB6 bit var CF_OE sbit sfr external Output Enable signal line var CF OE sbit at LATB5 bit var CF CD1 sbit str F P i i Chip Detect signal line var CF CD1 sbit at RB4 bit external var CF CEL sbit sfr F i 5 Chip Enable signal line var CF CE1 sbit at LATB3 bit external a var CF A2 sbit sfr external Address pin 2 var CF A2 sbit at LATB2 bit var CF Al sbit sfr external Address pin 1 var CF Al sbit at LATB1 bit var CF AO sbit sfr external Address pin 0 var CF_AO sbit at LATBO bit var CF RDY direction Direction of the Ready pin CF RDY direction sfr external y piin SB7_bit var CF WE direction sbit sfr 5 r P E direction Direction of the Write Enable pin a external C var CF OE direction sbit sfr r P CF OR direction axtasnal Direction of the Output Enable pin SB5 bit var CF CDI direction Sbit x D1 direction ee Direction of the Chip Detect pin fie sfr external Ez var CF CEL direction E i R r i CF CE1 direction gies estoma Direction of the Chip Enable pin SB3 bit var CF_A2 direction sbit sfr fos CP A2 direction external Direction of the Address 2 pin SB2 bit var CF Al direction sbit sfr s r i CF_Al direction external Direction of the Address 1 pin SB1 bit var CF AO direction sbit sfr A A CF A0 direction rt rnal Direction of the Address 0 pin SBO bit MikroElektronika 218 mikroPasc
119. Lcd_Init routine Write text Here at current cursor position Led Out Cp Here y Led Chr eure 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 ff art character i at row 2 column 3 Led Chr Se PEONY 379 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Lcd_Chr_Cp Prototype procedure Lcd Chr Cp out_char byte Prints character on Lcd at current cursor position Both variables and literals can be passed as a character out _ char character to be written The Lcd module needs to be initialized See Lcd_Init routine Write character e at current cursor position bed Chr Cpe jr Notes None OOS S Lcd _Cmd Prototype procedure Lcd Cmd out_char byte Sends command to Lcd out char command to be sent The Led module needs to be initialized See Led_Init table Clear Lcd display Led _Cmd _ LCD CLEAR Notes Predefined constants can be passed to the function see Available Lcd Commands Available Lcd Commands es eee te dey _LCD_CURSOR_OFF Turn off cursor MikroElektronika 3 6 mikroPascal PRO for dsPIC30 33 and PIC24
120. 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 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 dec
121. MSG TYPE and CAN CONFIG XTD MSG set all maskl bits to ones CAN1SetMask _ CAN MASK B2 l CAN CONFIG MATCH MSG TYPE and CAN CONFIG XTD MSG set all mask2 bits to ones CAN1SetFilter CAN FILTER B2 F3 ID 2nd CAN CONFIG XTD MSG set id of filter B2 F3 to 2nd node ID CAN1SetOperationMode _ CAN MODE NORMAL OxFF set NORMAL mode CANIWrite ID 1st RxTx Data 1 Can_Send Flags while TRUE do begin Msg Revd CAN1Read Rx_ ID RxTx Data Rx Data Len Can Rey Flags if Rx_ID ID 2nd and Msg Revd lt gt 0 lt gt 0 then begin PORTB RxTx Data 0 output data at PORTB RxTx Data 0 RxTx Data 0 1 Delay ms 10 CAN1Write ID 1st RxTx Data 1 Can Send Flags send incremented data back end end end Code for the second CAN node Copy Code To Clipboard program Can 2nd var Can Init Flags Can Send Flags Can_Rcv_ Flags Rx Data Len word RxTx Data array 8 of byte Rx ID longint Msg Revd word const ID 1st longint 12111 const ID 2nd longint 3 node IDs begin ADPCFG OxFFFF PORTB 0 TRISB 0 Can Init Flags 0 Can Send Flags z 0 MikroElektronika 258 mikroPascal PRO for dsPIC30 33 and PIC24 Can Rev Flags 0 Can Send Flags _CAN TX PRIORITY 0 and form value to be used _CAN TX_XTD_ FRAME and with CANSendMessage CAN TX NO RTR_ FRAME Can_Init Flags CAN CONFIG SAMPLE THRICE an
122. OxSEOF Ox9A22 0x9674 0x9307 Ox8FDD Ox8CF8 Ox8A5A 0x8805 Ox85FA 0x843A Ox82C6 Ox81A0 640 mikoPascal PRO for dsPIC30 33 and PIC24 0x12C8 0x8163 0x113A 0x812A OxOFAB Ox80F6 Ox0E1C 0x80C8 Ox0C8C Ox809E OxOAFB Ox8079 0x096B O0x8059 Ox07D9 0Ox803E 0x0648 0x8027 0x04B6 0x8016 0x0324 Ox800A 0x0192 0x8002 0x0000 Ox8000 OxFE6E 0x8002 OxFCDC Ox800A OxFB4A 0x8016 OxF9B8 0x8027 OxF827 Ox803E OxF695 0x8059 OxF505 0x8079 OxF374 Ox809E OxF1E4 0x80C8 OxF055 Ox80F6 OxEEC6 0x812A OxED38 0x8163 OxEBAB 0x81A0 OxEA1E 0x81E2 OxE892 0x822A OxE707 Ox8276 OxES7D Ox82C6 OxESF4 Ox831C OxE26D 0x8377 OxEOE6 Ox83D6 OxDF61 0x843A OxDDDC 0x84A3 0OxDC59 0x8511 OxXDAD8 Ox8583 0xD958 Ox85FA OxD7D9 Ox86 76 OxDG65SC Ox86F6 OxD4E1 0x877B 0xD367 0x8805 OxDIEF 0x8894 OxD079 0x8927 OxCFO4 Ox89BE OxCD92 Ox8A5A OxCC21 Ox8AFB OxCAB2 Ox8BAO 0xC946 Ox8C4A OxC7DB Ox8CF8 0xC673 Ox8DAB OxC50D O0x8E62 OxC3A9 Ox8F1D 0xC248 Ox8FDD OxCOE9 Ox90A1 OxBF8C 0x9169 OxBE32 0x9236 OxBCDA 0x9307 OxBB85 0x93DC 0OxBA33 0x94B5 OxB8E3 0x9592 OxB796 0x9674 OxB64C 029759 OxB505 0x9843 OxB3C0O 0x9930 OxB27F 0x9A22 OxB140 0x9B17 OxBO05 Ox9C11 OxAECC Ox9DOE OxAD97 Ox9EOF OxAC65 O0x9F14 OxAB36 OxAQIC OxAAOA OxA129 OxA8E2 0xA238 OxXA7BD OxA34C OxA69C 0xA463 OxA57E OxA57E O0xA463 OxA69C OxA34C OxA7BD OxA238 OxA8E2 OxA129 OxAAOA
123. PRO for dsPICSO 33 and PIC24 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 TIFI Write Data Ptr Nothing Description This function sets appropriate pointers to a user defined basic routines in order to enable multiple Requires working modes Parameters Set Index Ptr Set_Index handler Write Command Ptr _Write_Command handler Write Data Ptr Write_Data handler None Example of establishing 16 bit communication between TFT display and PORTD PORTE of MCU procedure Set Index index byte TFT _RS Lo LATD Procedure Write Command cmd byte Le Lo LATD cmd ye LF 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 TFT Init 320 240 092 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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
124. 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 Nothing Requires The CANSPI module must be in Config mode otherwise the function will be ignored See CANSP SetOperationMode 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 the appropriate filter value and message type CANSPISetOperationMode _CANSPI_ MODE CONFIG 0xFF set CONFIGURATION mode CANSPI module must be in config mode for filter settings Set id of filter Bl Fl to 3 CANSPISetFilter CANSPI FILTER Bl Fl 3 _CANSPI CONFIG XTD MSG 267 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 s
125. 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 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 MMC SD card must be initialized See Mmc_Init var error word dataBuffer array 16 of byte rror Mmo Read Csd dataBuffer 391 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Mmc_Fat_Init Prototype function Mme Fat _Init word Initializes MMC SD card reads MMC SD FAT16 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
126. Reading file contents Deleting file s Creating the swap file see Help for details Copy Code To Clipboard program MMC FAT Test var Mmc Chip Select sbit at LATFO bit for writing to output pin always use latch PIC18 family Mme Chip Select Direction sbit at TRISFO bit 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 401 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 buffer array 512 of byte UART write text and new line carriage return line feed procedure UART Write Line var uart_text string begin VARTI Write Text uart_text UART1 Write 13 UART1 Write 10 end 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 2005 6 21 10 35 0 Set file date amp time info Mme Fat Assign filename OxA0 Will not find file and then create file To clear file and start with new data We want 5 files on the MMC card Mmc_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 Mmc Fat Write file contents LINE LEN 1 write data to the assigned file end end P i aa Creates many new files and writes dat
127. Requires MCU with the CAN module MCU must be connected to the CAN transceiver MCP2551 or similar which is connected to the CAN bus set the CAN1 module into configuration mode wait inside CAN1SetOperationMode until this mode is set CAN1SetOperationMode _CAN MODE CONFIG OxFF CAN library routine require you to specify the module you want to use To use the desired CAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of CAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library lat dalle Mode device datasheet for operation mode codes Returns Curentoperatonmode SOSC S SCSCSCSCSCSCSCSCSCSSCS Requires MCU with the CAN module MCU must be connected to the CAN transceiver MCP2551 or similar which is connected to the CAN bus CAN library routine require you to specify the module you want to use To use the desired CAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of CAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library check whether the CAN1 module is in Normal mode and if it is then do something if CANIGetOperationMode _CAN MODE NORMAL 241 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 CANxtInitialize Prototype procedure CANxInitialize SJW BRP PHSI E
128. S1D13700 WHITE 1D13700_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 round 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 1D13700_ BLACK Black color 1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700_Init routine 51013700 Rectangle Round Edges 20 20 219 107 12 S1D13700 WHITE MikroElektronika 332 mikroPascal PRO for dsPICSO 33 and PIC24 1D13700 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 lo
129. 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 SPIx_Write Prototype procedure SPIx Write data_out word Description Writes one word or byte depending on mode set by init routines via the SPI bus Parameters data_out data to be sent Returns 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 SPIx_Init_ Advanced routines write a byte to the SPI bus var buffer byte SPI1 Write buffer 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 SPI library routines require you to specify the module you want to use To select the desired SPI MikroElektronika ani mikroPascal PRO for dsPICSO 33 and PIC24 SPI_Set_Active Prototype procedure SPI Set _Active read_ptr TSPI_Rd_ Ptr write ptr TSPI_Wr_ PEE i Description 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
130. 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 e 647 begin ADPCFG OxFFFF e text mikroElektronika 50 Led Init Led_Cmd LCD CLEAR a s3 Led_Cmd _LCD_CUR for i 1 to 17 do Led_Chr i i text i 1 f H begin i i i end Watch Values Eh Eh Eh 90 o9 ef a Add Remove Pro Select variable from list text A k Add All at Remove All aE perties Search for variable by assembly name _text V Peripherals Freeze Name Value text uf PC 0x0002DA 65 55 ms Run Pause Debugger F6 and Toggle Breakpoints F5 are mikrolCD debugger functions that are 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 every time this function is reached After reaching breakpoint we must press F6 again to continue the program execution 647 begin ADPCFG OxFFFF e text mikroElektronika 50 H i Led_I
131. The SPI module is available with a number of the dsPIC30 33 and PIC24 MCUs The mikroPascal PRO for dsPIC30 33 and PIC 24 provides a library driver for working with mikroElektronika s CANSPI Add 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 In the mikroPascal PRO for dsPIC30 33 and PIC24 each routine of the CAN library has its own CANSPI counterpart with identical syntax For more information on Controller Area Network consult the CAN Library Note that an effective communication speed depends on SPI and certainly is slower than real CAN 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
132. To Clipboard program PWM var pwm period current duty word begin ADPCFG OxFFFF initialize AN pins as digital PORTB 0 TRISB 2 0 initialize portb as output current duty 10 Delay ms 1000 pwm period PWM1 MC Init 5000 1 0x01 0 Pwm Mc Init returns calculated timer period PWM1 MC Set Duty current duty 1 PWM1 MC Start while TRUE do begin Endless loop if RBO bit then Button on RBO pressed begin Delay ms 20 Inc current_ duty Increment current duty if current duty gt pwm period then If we increase current duty greater then possible pwm period value begin current duty 0 reset current duty value to zero end PWM1 MC Set _Duty current duty 1 Set newly acquired duty ratio end 438 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 if RB1 bit then Button on RB1 pressed begin Delay ms 20 Dec current duty Decrement current_duty if current_duty gt pwm period then If we decrease current_duty greater then possible pwm period value overflow begin current duty pwm period set current_duty to max possible value end PWM1 MC Set_Duty current_duty 1 Set newly acquired duty ratio end Delay ms 5 Slow down change pace a little end end HW Connection a a mm a OSCILLATOR UUL GND osc1 Sr ae OL0 DIidSP vcc aie PWM
133. VALID XTD MSG and CAN CONFIG LINE FILTER OFF CANl1Initialize 1 1 3 3 1 init initialize CAN CAN_TX_MSG_FLAGS Constants CAN TX MSG FLAGS are flags related to transmission of a CAN message Copy Code To Clipboard const _CAN TX PRIORITY BITS word 0x03 _CAN_TX_PRIORITY_0 word OxFC XXXXXX00 _CAN TX PRIORITY 1 word OxFD XXXXXX01 _CAN TX PRIORITY 2 word OxFE XXXXXX10 _CAN TX PRIORITY 3 word OxFF XXXXXX11 CAN_TX FRAME BIT word 0x08 _CAN TX STD FRAME word OxFF XXXXX1XX _CAN TX _XTD_ FRAME word OxF7 XXXXXOXX CAN TX RTR BIT word 0x40 CAN_TX NO RTR FRAME word OxFF X1XXXXXX _CAN_TX_RTR_FRAME word OxBF XOXXXXXX You may use bitwise and to adjust the appropriate flags For example Copy Code To Clipboard form value to be used with CANSendMessage send config CAN TX PRIORITY 0 and _CAN_TX_XTD_FRAMI and CAN TX NO RTR FRAME les CANSendMessage id data 1 send config 255 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 CAN_RX_MSG_FLAGS Constants CAN RX MSG FLAGS are flags related to reception of CAN message If a particular bit is set corresponding meaning is TRUE or else it will be FALSE Copy Code To Clipboard const CAN RX FILTER CAN RX FILTER CAN RX CAN RX FILTER FILTER CAN RX FILTER CAN RX FILT
134. Vector_Power Prototype sub function Vector Power dim N as word dim byref srcV as word 1024 as word Function returns result of power value powVal in radix point 1 15 Parameters number elements in vector s srcV pointer to source vector a i powVal srcV nl srcV n dim vecl as word 3 Vector Power 3 veci W0 W2 used not restored W4 used not restored AccuA used not restored CORCON saved used restored Vector_Subtract Prototype ae Vector Subtract var dest vl v2 array 1024 of word numElems word Description This function does subtraction of two vectors dstV n v1 n v2 n n e 0 numElems 1 Parameters numElems must be less or equal to minimum size of two vectors vi first vector v2 second vector dest result vector i var vecl array 3 of word vec2 array 3 of word vecDest array 3 of word Vector Subtract vecDest vecl v AccuA used not restored CORCON saved used restored 644 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Vector Scale Prototype procedure Vector Scale N word ScaleValue integer var SrcVector DestVector array 1024 of word Description This function does vector scaling with scale value dstV n sclVal srcV n n e 0 numElems 1 Parameters N buffer length SrcVector original vector DestVector scaled vector ScaleValue scale value Nothing Requires Nothing var vecl
135. a 2N b 32FFEE 97B84E E10064 32FFEE 37FFFO 97B83E 5000E1 570068 2N d aiy2ay7 gt 408010 9FBF40 781F80 07FF98 B1002F 2088c0 A10010 EF2000 lt DLE gt lt US gt 980700 97B8AE 470060 408010 E00410 32000C 97B8AE 470060 lt BELL gt _ G lt 0 408010 784010 FB8000 781F80 07FF32 B1002F 200011 470060 lt DLE gt lt DLE gt x 408810 37FFEF 2088C0 A00010 FA8000 oso000 FA0002 EF2000 lt DLE gt i 7 lt SPC 984700 90400E E10468 310009 2001C0 781F80 07FF78 B1002F G lt 50 gt O h lt E0T 07FF31 B3C011 470060 40C810 37FFF4 FASOOD o60000 FA0002 19 lt BELL gt lt DC1 gt EF2000 984700 90400E E10468 310009 200180 781F80 07FF67 lt SPC gt i G lt 50 gt C B1002F 07FF20 B3C011 470060 40C810 37FFF4 FA8000 060000 lt SPC gt lt BELL gt lt C 2088EF 20FFFO B7020 200000 B7A034 200040 B72044 FA0000 lt 5PC gt 4 lt SPC gt lt SF 0203D8 000000 2FFFFO B7A2A8 07FF1ID 2000c0 781F80 O7FF4F lt ETX gt lt STX gt 89 B1002F 208610 781F80 200060 781F80 200010 781F80 07FF87 amp lt DLE gt t lt SPC gt lt B1006F 208690 781F80 200060 781F80 200020 781F80 O7FF7F 0 4 O t lt SPC gt lt US gt B1006F 200cc8 273987 ED200E 3AFFFE ED2010 3AFFFC 200010 0 E lt FF gt lt SPC gt 9 781F80 07FF35 B1002F 208700 781F80 200010 781F80 200010 lt U5 gt x5 lt BELL gt 7
136. address mapping the mikroPascal PRO for dsPIC30 33 and PIC24 offers two sets of Flash handling functions regular and compact Using the regular set the user can write one byte of data to a single address which means that each byte of written data has its own address but on every 2 written bytes one byte of Flash memory remains empty Using the compact set every byte of Flash memory including those non addressable is filled with data this method can only be used for data organized in bytes The compact functions have Compact as name suffix MikroElektronika 336 mikroPascal PRO for dsPIC30 33 and PIC24 24F04KA201 and 24F16KA102 Family Specifics These MCU s have their Flash memory organized into memory blocks of 32 instructions 96 bytes unlike other PIC24 devices Erasing can be done only in 32 instructions 64 addresses 96 bytes memory blocks which means that the block start address should be a multiply of 64 i e have 6 lower bits set to zero Data is read and written in 32 instructions 64 addresses 96 bytes blocks This means that the block start address should be a multiply of 64 i e have 6 lower bits set to zero Unlike other PIC24 devices writing or erasing one block of data 32 instructions is followed by erasing the memory block of the same size 32 instructions Library Routines dsPIC30 Functions FLASH_Erase32 FLASH_Write_Block FLASH_Write_Compact
137. 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 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 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 zZ 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 metacha
138. are filled with zeros Parameters input word to be converted output destination string var t longint txt array 11 of char Fives t 12345678 LongIntToStrWithZeros t txt tat s Y 0012345678 MikroElektronika 665 mikroPascal PRO for dsPICSO 33 and PIC24 Byte ToHex Prototype procedure ByteToHex input byte var output 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 byte to be converted destination string var t byte txt array 2 of char E c 2 te tzt is o2 ShortToHex Prototype procedure ShortToHex input short var output 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 short number to be converted oi destination string var t short txt array 2 of char 100 ShortToHex t txt txt is 9C 666 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 WordToHex Prototype procedure WordToHex input word var output array 4 of char Description Converts input number to a string containing the number s hexadecimal representatio
139. array 3 of word vecDest array 3 of word Vector Scale 3 2 vecl vecDest WO W5 used not restored AccuA used not restored CORCON saved used restored Vector_Negate Prototype procedure Vector Negate var srcVector DestVector array 1024 numElems word Description This function does negation of vector dstV n 1 srcV1 n 0 n e 0 numElems Parameters srcVector original vector destVector result vector numElems number of elements in vector s Nothing Requires Nothing var vecl array 3 of word vecDest array 3 of word Vector Negate vecl vecDest 3 Negate of 0x8000 is Ox7FFF WO W5 used not restored AccuA used not restored CORCON saved used restored MikroElektronika 645 mikroPascal PRO for dsPICSO 33 and PIC24 Vector_Multiply Prototype procedure Vector Multiply var vl v2 dest array 1024 of word num word Description This function does multiplication of two vectors dstV n srcV1 n sreV2 n n e 0 numElems 1 Parameters num lems number elements in vector s must be less or equal to minimum size of two vectors vi first vector v2 second vector dest result vector Nothing Requires Nothing var vecl array 3 of word vec2 array 3 of word vConDest array 10 of word Vector Multiply vecl vConDest vec2 3 WO W5 used not restored AccuA used not resto
140. 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 i Soft I2C Read 0 Soft_I2C_Write ae function Soft I12C Write data_ byte byte Sends data byte via the I C bus data_ data to be sent 0 if there were no errors 1 if write collision was detected on the I C bus Requires Soft C 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 lt Soft I2C eur aight error Soft_ I2C Write A3 Soft_I2C_Stop FRetums Nong OOOO SSS Soft C must be configured before using this function See Soft_I2C_Init routine Issue STOP signal Soft 726 Stop MikroElektronika 451 mikroPascal PRO for dsPICSO 33 and PIC24 Soft_I2C_Break Prototype procedure Soft 12C Break Description All Software 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 This mechanism is similar to WDT Nothing Requires Nothing var datal error counter byte procedure TimerliInt 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 TITE bit 3 0
141. be the power of 2 ReIm output sample from FFT Nothing Requires Nothing var InputSamples array 512 of word ydata Y data is required by FFT routine See datasheet for your dsPIC to see Y data space limits Perform FFT DFT 7 stages 128 samples of complex pairs Twiddle factors are taken from help FFT 8 word TwiddleCoeff 256 InputSamples DFT butterfly algorythm bit reverses output samples We have to restore them in natural order BitReverseComplex 8 InputSamples Input samples must be in Y data space mikoPascal PRO for dsPIC30 33 and PIC24 Vectors Library mikroPascal PRO for dsPIC30 33 and PIC24 includes a library for working and using vectors All routines work with fractional Q15 format Library Routines Vector Set Vector_Power Vector_Subtract Vector_Scale Vector_Negate Vector_Multiply Vector_Min Vector_Max Vector_Dot Vector_Correlate Vector_Convolve Vector_Add Vector_Set eee procedure Vector Set var input array 1024 of word size value word Sets size elements of input to value starting from the first element Parameters input pointer to original vector size number of vector elements value value written to the elements var vec2 array 3 of word Vector Set vec2 3 0x4000 size must be gt 0 Length of input is limited by available RAM mikroPascal PRO for dsPICSO 33 and PIC24
142. been found get its modified date Imc Fat Get File Date Modified year month day hour minute UART1 Write Text modified WordToStr year outstr UART1 Write Text outstr ByteToStr month outstr UART1 Write Text outstr WordToStr day outstr VARTI Write Text outstr WordToStr hour outstx UART1 Write Text outstr WordToStr minute outstr VARTI Write Text outstr r get file size fsize Mmc Fat Get File Size LongIntToStr fsize outstr VART Write Line outstr end else begin file was not found signal it UART1 Write 0x55 Delay ms 1000 UART1 Write 0x55 end end UA a a a a al Tries to create a swap file whose size will be at least 100 Sf sectors see Help for details procedure M Create Swap File var i i word begin for i 0 to 511 do B ffer i t i size Mme Fat Get Swap File 5000 mikroE txt 0x20 see help on this function for details if size lt gt 0 then begin LOngIntToStr size err Cxt 7 UART Write Line err txt for i 0 to 4999 do begin Mmc Write Sector size Buffer Inc size UART1 Write end end end MikroElektronika 404 mikroPascal PRO for dsPIC30 33 and PIC24 jp 2eSe Ses e ssee Main Uncomment the function s to test the desired operation s begin err txt 7 FATIG not found file contents XX MMC SD FAT16 library by Anton Rieckert
143. before using this function See HID_Enable retry until success while HID Write writebuff 64 Notes Function call needs to be repeated as long as data is not successfuly sent mikroPascal PRO for dsPICSO 33 and PIC24 HID_Disable Prototype procedure HID Disable Description Disables USB HID communication Parameters None Di Nothing Requires USB HID needs to be enabled before using this function See HID_Enable Notes None OSS USB_Interrupt_Proc Prototype Description This routine is used for servicing various USB bus events Should be called inside USB interrupt routine Nothing Requires Nothing procedure USBlInterrupt iv IVT ADDR _USB1INTERRUPT begin USB Interrupt Proc 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 USB_Polling Proc Prototype 100 microseconds 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 mikoPascal PRO for dsPIC30 33 and PIC24 Gen_Enable Prototype procedure Gen Enable readbuff
144. bit adjusted to appropriate filter registers ECAN FILTER MASK mask register corresponding to filter Valid values ECAN MASK constants See ECAN_MASK constants ECAN FILTER RXBUFF receive buffer corresponding to filter Valid values ECAN RX BUFFER constants See ECAN_RX_BUFFER constants ECAN_ CONFIG FLAGS selects type of messages to filter Valid values ECAN CONFIG XTD MSG and ECAN CONFIG STD MSG See ECAN_CONFIG_FLAGS constants Requires The ECAN routines are supported only by MCUs with the ECAN module Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus The ECAN module must be in Config mode otherwise the function will be ignored See ECANxSetOperationMode set appropriate filter value and message typ ECAN1SetOperationMode _ECAN MODE CONFIG OxFF set CONFIGURATION mode ECAN1 module must be in config mode for filter settings Set id of filter 10 to 3 mask2 receive buffer 7 extended messages ECAN1SetFilter _ECAN FILTER 10 cir ECAN MASK 2 ECAN RX BUFFER 7 ECAN CONFIG XTD MSG ECAN library routine require you to specify the module you want to use To select the desired ECAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of ECAN modules per MCU differs from chip to chip Please read the appropriate datash
145. 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 Interrupt Handling For the sake of interrupt handling convenience new keyword iv is introduced It is used to declare Interrupt Vector Table IVT address for a defined interrupt routine procedure intl iv IVT_ADDR_UIRXINTERRUPT begin asm nop end end Now it is possible to explicitly declare interrupt routine address procedure intl org 0x600 iv IVT_ADDR_U1RXINTERRUPT begin asm nop end end 142 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 For the sake of backward compatibility user may write also procedure intl org IVT ADDR _U1RXINTERRUPT begin asm nop end end which is equivalent to procedure intl iv IVT _ADDR_U1RXINTERRUPT begin asm nop end end It is recommended that interrupts are handled in this way for the sake of better readability of the user projects Interrupt Example Here is a simple example of handling the interrupts from Timer if no other interrupts are allowed a ee S S Sa Interrupt routine procedure TimerliInt iv IVT _ADDR_T1INTERRUPT begin it is necessary to clear manually the interrupt flag IFSO IFSO and S FFF7 clear TMRIIF user code starts here LATB not PORTB invert PORTB user code
146. byte begin i 0 result 1 if n gt 0 then for i 1 to n do result result x end 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 declarationsare optional declaration of variables and or constants local forthe given procedure Procedure body is a sequence 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 MikroElektronika 200 mikroPascal PRO for dsPIC30 33 and PIC24 Example This example shows how to declare a function which returns a complex type program Example type TCircle record R
147. 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 2 12 p STORE b b and a a is sign extended with the upper byte equal to SFF b becomes 70F4 Bitwise Shift Operators Binary operators shl 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 left 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 2 if all discarded bits are zero This is also true for signed operands if all discarded bits are equal to the sign bit MikroElektronika 219 mikroPascal PRO for dsPICSO 33 and PIC24 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 Boolean Operators Although mikroPascal PRO for dsPIC30 33 and PIC24 does not support boolean type you have Boolean operators at
148. 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 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 ENC247600 module The ENC247600 module should be properly cofigured by the means of SPI Ethernet 243600 Init routine multicast traffic will be enabled MULTICAST 5 0x20 CRC check flag When set packets with invalid CRC field SPI Ethernet 243600 CRC will be discarded a a EC ote PC 7 0x80 MAC Unicast traffic receive filter flag When set MAC _SPI_ Ethernet _24j600_ unicast traffic will be enabled UNICAST Ethernet module has to be initialized See SPI_Ethernet_24j600_Init SPI Ethernet 243600 Enable _ SPI Ethernet 24j600_ CRCor_SPI Ethernet 24j600_ UNICAST enable CRC checking and Unicast traffic 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_ broadcast traffic will be enabled BROADCAST Advanced filtering available in the ENC247600 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
149. code insert a delay after each PORTB Bx 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 in this way READ LATB is read STORE Data is stored inside a temporary internal register in the MCU otore reau vaiue 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 Se Er rn are Write c modified value aaa O j Discharged capacitor Charging capacitor MikroElektronika 115 mikroPascal PRO for dsPIC30 33 and PIC24 The second line LATB B1 1 will be decoded 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 Actual voltage levels on MCU pins are no longe
150. computers cell phones game consoles PDA s etc USB Library contains HID routines that support HID 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 dsPIC30 33 and PIC24 Tools USB HID Terminal The
151. connected to the CAN bus CAN must be in Config mode otherwise the function will be ignored See CANxSetOperationMode CAN library routine require you to specify the module you want to use To use the desired CAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of CAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library set required baud rate and sampling rules var can _ config flags word CAN1SetOperationMode _CAN MODE CONFIG OxFF set CONFIGURATION mode CAN1 module must be in config mode for baud rate settings can_config flags CAN CONFIG SAMPLE THRICE amp Form value to be used CAN CONFIG PHSEG2 PRG ON amp with CAN1SetBaudRate CAN CONFIG STD MSG amp CAN CONFIG DBL BUFFER ON amp CAN CONFIG MATCH MSG TYPE amp CAN CONFIG LINE FILTER OFF CAN1SetBaudRate 1 3 3 3 1 can_config flags set the CAN1 module baud rate 249 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 CANxSetMask Prototype procedure CANxSetMask CAN MASK word val longint CAN CONFIG FLAGS word Description Function sets mask for advanced filtering of messages Given value is bit adjusted to appropriate buffer mask registers Parameters CAN MASK CAN module mask number Valid values CAN MASK constants See CAN_MASK constants val mask register va
152. correspond to prescaler postscaler lt 1 1 1 4 1 16 1 64 gt and lt 1 1 1 2 oy eles Returns Calculated timer period The dsPIC30 33 MCU must have the Motor Control PWM module Initializes the PWM module at 5KHz complementary pin pair output output enabled on pins 41 11 no clock prescale and no clock postscale var duty 50 word duty 50 PWM1 Mc Ipit 5000 1 Ox0F 0 Number of PWM modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library PWM library routines require you to specify the module you want to use To use the desired PWM module simply change the letter x in the routine prototype for a number from 1 to 2 436 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 PWMx_Mc_Set_Duty Prototype procedure PWM1 Mc Set Duty duty channel word For dsPIC 33FJ MCUs that have PWM2 module procedure PWM2 Mc Set Duty duty word The function changes PWM duty ratio Parameters duty PWM duty ratio Valid values 0 to timer period returned by the PWMx_Mc_Init function channel number of PWM channel to change duty to Nothing Requires The dsPIC30 33 MCU must have the Motor Control PWM module The PWM module needs to be initalized See the PWMx_Mc_Init function Set duty ratio to 50 at channel 1 PWM1 Mc _Init 5000 1 F 0 PWM1_Mc_Set_Duty 32767 1 Number of PWM modules per MCU differs from chip to chip Pleas
153. 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 CAN library routines require you to specify the module you want to use To use the desired CAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of CAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Library Routines CANxSetOperationMode CANxGetOperationMode CANxInitialize CANxSetBaudRate CANxSetMask CANxSetFilter CANxRead CANxWrite MikroElektronika 246 mikroPascal PRO for dsPICSO 33 and PIC24 CANxSetOperationMode Prototype procedure CANxSetOperationMode mode WAIT word Sets the CAN module to requested mode Parameters mode CAN module operation mode Valid values CAN OP MODE constants See CAN_OP_MODE constants WAIT CAN mode switching verification request If WAIT 0 the call is non blocking The function does not verify if the CAN module is switched to requested mode or not Caller must use CANxGetOperationMode to verify correct operation mode before performing mode specific operation If WAIT 0 the callis blocking the function won t return until the requested mode is set
154. dsPIC30F4013 oab sab IPO denovz2c 109 mikroPascal PRO for dsPIC30 33 and PIC24 15 Finally click on the Debugger gt Program MPLAB IDE v8 36 Output Fie Edit view Project Doe mg Build Version Control Find Target Device asriU sur Reading ICD Product IC Running ICD Self Test Passed MPLAB ICD 2 ready for n Programming Target validating configuration Erasing Part Programming Program Loading DebugExecuti Programming DebugEx Programming Debug Ve Verifying Program Memory Debug Executive Debug Vector verity Succeeded Programming Configurati Config Memory Verifying configuration me Verity Succeeded Debugger Programmer Tools Configure Window Help SAE Select Tool Clear Memory gt Run Animate ialt Step Into Step Over step Out Reset Breakpoints Advanced Breakpoint MPLAB ICD 2 Setup Wizard Program Read Read EEPROM Abort Operation Connect Download ICD2 Operating System Settings Connecting to debug executive Programming succeeded 02 Sep 2009 15 05 43 MPLAB ICD 2 ready for next operation rare RISE 710 dsPIC30F4013 oab sab IPO denov2c MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 16 Now you can start debugging the code by clicking Step Over button P on the Debug toolbar or by pressing F8 M MPLAB IDE v8 36 C WART mbas DR T
155. 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 COC Fo foon reao Le oxo Device rternal use ony neverta ond File creation flag If file does not exist and this flag is set a 7 0x80 ied z 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 MIKROO0O7 TXT OxA0O Notes Long File Names LFN are not supported MikroElektronika 394 mikroPascal PR
156. f Remove File From Project Build Ctrl F9 amp mE Programmer Fil Set As Preview Image Ctri Alt P MikroElektronika 16 mikroPascal PRO for dsPICSO 33 and PIC24 Once you have added the image it will appear in the Image Preview Window EI t te 48849191d immenses oor DTE seem 1884910ld tt ii ee te n hep os eae ae Mate em Mate foe pe 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 dsPIC30 33 and PIC24 Help File Toolbar Edit Toolbar Advanced Edit Toolbar Find Toolbar Project Toolbar Build Toolbar Debug Toolbar Styles Toolbar Tools Toolbar View Toolbar Layout Toolbar Help Toolbar 11 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 File Toolbar Ag File Toolbar is a standard toolbar with the following options eon o o O Opens a new editor window Open source file for editing or image file for viewing re Save changes for active window Save changes in all opened windows Edit Toolbar Edit Toolbar is a standard toolbar with the following options ee o o A Undo
157. 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 r squared routine call pi r squared res pi r squared routine call end end Variables and dsPIC30 33 and PIC24 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 for dsPIC30 33 and PIC24 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 dsPIC30 33 and PIC24 automatically declares relevant registers as global variables of volatile word see SFR for details 197 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 o
158. for dsPIC30 33 and PIC24 Time_epochToDate Prototype procedure Time epochToDate e longint var ts TimeStruct ts time and date structure for storing conversion output fRetums Nothing SS 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 t1 is the same as t2 and result is negative if t1 is after t2 Parameters t1 time and date structure the first comparison parameter t2 time and date structure second comparison parameter Parameters None i E Returns Time difference in seconds as a signed long var tsl ts2 TimeStruct Giff longint how many seconds between these two dates contained in tsl and ts2 buffers aiff Time dateDiff tsl ts2 mikoPascal PRO for dsPIC30 33 and PIC24 Library Example Demonstration of Time library routines usage for time calculations in UNIX time format Copy Code To Clipboard program Time Demo simple time structure type TimeStruct record ss byte j 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
159. 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 PartialImage 10 12 10 15 image 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 TFT Image Jpeg 0 0 image MikroElektronika 603 mikroPascal PRO for dsPICSO 33 and PIC24 TFT_RGBToColor16bit Prototype function TFT RGBToColorl6 bit rgb red rgb green rgb blue byte gt 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 color16 TFT_Image_J
160. i Led_Cma 64 for i 0 i lt 7 i Led_Chr_CP character i Led_Cma _LCD_RETURN_HOME Led Chr pos row pos char 0 Copy Code To Clipboard MikroElektronika 94 mikroPascal PRO for dsPIC30 33 and PIC24 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 clicking the Seven Segment Editor Icon ele from Tools toolbar Seven Segment Editor Common cathode 113 pa UDP Terminal The mikroPascal PRO for dsPIC30 33 and PIC24 includes the UDP Terminal You can launch it from the drop down menu Tools gt UDP Terminal MikroElektronika UDP Terminal pSettings IP Address Port 192 168 020 025 Connect O i Send Append ECR LE m mikroElektronika a Send as typing Send as number mikroElektronika mikroElektronika MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 USART Terminal The mikroPascal PRO for dsPIC 30 33 and PIC 24 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 I
161. in the MCU PORTS REGISTER Discharged i N aaa a capacitor Discharged capacitor MikroElektronika 173 mikroPascal PRO for dsPIC30 33 and PIC24 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 bo mel Write modified value Discharged Charai 00000000 c arging T capacitor 00000000 T capacitor The second line PORTB B1 1 will be decoded 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 Read from REGISTER pins j 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 REGISTER Write CEES OAS REGISTER modified d value peep a i gt lolol fololayfo 2s 00000000 Discharging I capacitor 00000010 AR j premis 174 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 To correct the problem in the
162. 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 Glcd needs to be initialized for SP communication see SPI_Glcd_Init routine Draw a line ee pie 0 0 and 20 30 SPI Glcd_Line 0 i 3 Rows Now 522 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_Glcd_V_Line Prototype procedure SPI Glcd V Line y start y end x pos color byte 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 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 SPI_Glcd_H_Line Saad dais procedure SPI Gled 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 pa
163. lt tr gt lt script gt war striai 492 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 latre 904 for 2 0p i lt 4sa h i str lt tr gt lt td bgcolor yellow gt LED i lt td gt if PORTD amp 1 lt lt i strt lt td bgcolor red gt ON else strt lt td bgcolor cccccc gt OFF strt lt td gt lt td gt lt a href t tit gt Toggle lt a gt lt td gt lt tr gt document write str lt script gt 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 var getRequest array 15 of byte HTTP request buffer dyna array 30 of char buffer for dynamic response httpCounter word counter of HTTP requests LERELEEREERE REEL AREREEAE REEL ELE EE REREAD EEE user defined functions 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 I function SPI Ethernet UserTCP var remoteHost array 4 of byte rem
164. mikroElektronika SPI Ethernet _24j600_putString buffer put a RAM string into ENC24J600 buffer SPI_Ethernet_24j600_putConstString Prototype function SPI Ethernet 243600 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 ENC247600 write pointer WRPT 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 243600 getByte byte Description This is MAC module routine It fetches a byte from address pointed to by current ENC247600 read pointer ERDPT Byte read from ENC247600 RAM Requires Ethernet module has to be initialized See SPI_Ethernet_24j600_Init var buffer byte Ethernet 243600 getByte read a byte from ENC24J600 buffer 508 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_Ethernet_24j600_getBytes Prototype procedure SPI Ethernet 24j600 getBytes ptr byte addr word n word Description This is MAC module routine I
165. 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 tsisa 2 0 4 tsl mn 7 tsl hh 17 tsl md i 23 tsl mo 5 tsl yy 2006 gt what is the epoch of the date in ts a epoch Time dateToEpoch tsl epoch 1148404020 1 what date is epoch 1234567890 epoch 1234567890 Time epochToDate epoch ts2 7i 8288 q 30 gt fi eseon 2 gt 31 3 Af tS2 Oh 2 23 3 ts2 ma 13 7 82 08 2 43 Ji s2 mo 2 2 5 i ts2 yy r 2009 4 es how much seconds between this two dates I diff Time dateDiff tsl ts2 diff 86163870 end MikroElektronika 683 mikroPascal PRO for dsPIC30 33 and PIC24 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 IL as with unix C time yy word year Y2K compliant from 1892 to 2038 end mikoPascal PRO for dsPIC30 33 and PIC24 Trigon Library The mikroPascal PRO for dsPIC30 33 and PIC24 provides a set of library functions for floating point math handling See also Predefined Globals and Constants for the list o
166. module needs to be initialized See SPI_T6963C_Config routine enable text displaying SPI_T6963C text 1 SPI_T6963C_cursor Prototype procedure SPI T6963C cursor n word Set cursor on off n on off parameter Valid values 0 set cursor off and 1 set cursor on Toshiba Gicd module needs to be initialized See SPI_T6963C_Config routine set cursor on SPI T6963C cursor 1 560 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_T6963C_cursor_blink Prototype procedure SPI 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 r Dingng Toshiba Glcd module needs to be initialized See SPI_T6963C_Config routine enable cursor blinking SPL T6963C cursor Dilink 1 7 Notes None oo Library Example The following drawing demo tests advanced routines of the SPI T6963C Glcd library Hardware configurations in this example are made for the EasydsPIC4A board and dsPIC30F4013 Copy Code To Clipboard program SPI T6963C_ 240x128 uses Lib SPIT6963C Const var Port Expander module connections SPExpanderRST sbit at LATFO bit for writing to output pin always use latch PIC18 family SPExpanderCsS gt sbit at LATF1 bit for writing to output pin always use latch PIC18 family SPExpanderRST Direction sbit at TRISFO bit SPExpanderC
167. naming conflicts between field identifiers and other variables MikroElektronika 211 mikroPascal PRO for dsPIC30 33 and PIC24 Note In mikroPascal PRO for dsPIC30 33 and PIC24 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 Dot type TDot record x y real end Each Dot contains two fields x and y coordinates Memory is allocated when you instantiate the structure like this var m n TDot This variable declaration creates two instances of Dot called m and n A field can be of the 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 members like this T 0 0 r circlel radius 3 circlel center x 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 212 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Types Conversions Conversion of variab
168. needs to be initialized See SPI_T6963C scorer routine ea SPI_1T6963C_writeCommand SPI_T6963C CURSOR POINTER SE 548 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_T6963C_setPtr Prototype procedure SPI T6963C_setPtr p word c byte Sets the memory pointer p for command p Parameters p address where command should be written c command to be written Toshiba Gicd module needs to be initialized See SP _T6963C_Config routine _T6963C_ setPtr SPI_T6963C grHomeAddr start SPI_T6963C_ADDRE TER SET SPI_T6963C_waitReady Rems Nothing OOOO Example 521 r6963 waieneady7 OOS moes noe OOOO SPI_T6963C_fill Asak aa procedure SPI 1T6963C 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 Rems Noting SSCS Example 51 r69630 11 0x39 0x00FE 080007 O O OOO O OoOO Moss fne OOS MikroElektronika 549 mikroPascal PRO for dsPIC30 33 and PIC24 SPI_T6963C_dot Prototype procedure SPI T6963C_dot x y integer color byte Writes a char in the current 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
169. of a local label specified by label name The goto line can come before or after the label 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 You can use goto to break out from any level of nested control structures Never jump into a loop or other structured statement since this can have unpredictable effects Use of goto statement is generally discouraged as practically every algorithm can be realized without it resulting in legible structured programs One possible application of goto statement is breaking out from deeply nested control structures for ce d6 begin for do begin if disaster then goto Error end end Error error handling code MikroElektronika 230 mikoPascal PRO for dsPIC30 33 and PIC24 asm Statement mikroPascal PRO for dsPIC30 33 and PIC24 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 dsPIC30 33 and PIC24 are registers e g INTCON PORTB WREG GIE etc
170. 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_Font to specify the font for display if no font is specified then default Font Glcd 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 Notes For x axis and page layout explanation see schematic at the bottom of this page 359 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Glcd_Image Prototype procedure 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 dsPIC30 33 and PIC24 pointer to const and pointer to RAM equivalency Glcd needs to be initialized see Glcd_Init routine Draw image my_image on Glcd Glcd_Image my_ image Use the mikroPascal PRO for dsPIC30 33 and PIC24 integrated Glcd Bitmap Editor Tools gt Gled Bitmap Editor to convert image to a constant array suitable for displaying on Glcd Glcd_Partiallmage Prototype procedure Glcd PartialImage x left y top width height picture width picture height word const image i byte 7 Displays a partial area of the image on a desired location Parameters x left x coordinate of the desired location upper left coordinate y_
171. of this page Library Routines Sound_Init Sound_Play Sound_Init Prototype 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 Prototype 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 MikroElektronika 463 mikroPascal PRO for dsPICSO 33 and PIC24 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 Tonel begin Sound Play 659 end procedure Tone2 begin Sound Play 698 end procedure Tone3 begin Sound Play 784 end procedure Melody begin Tonel Tone2 Tonel Tone2 Tonel Tone2 Tonel Tone2 Tonel Tone2 Tone3 Tone3 end procedure ToneA begin Sound Play 880 end procedure ToneC b
172. one with most free space and is set by the compiler by analyzing program memory pages This qualifier is set as default by the compiler if no other qualifier is used Far Memory Qualifier 1 Data Memory Objects The qualifier far is used to denote that a variable will not be in near data space i e the variable can be located anywhere in data memory This qualifier is set as default by the compiler if no other qualifier is used 2 Program Memory Objects The qualifier far is used to denote that a constant can be allocated anywhere in the program memory in the page pointed to by PSVPAG register Location of object based on memory qualifiers Qualifier Memory Data Memory Program Memory First 8 kB of RAM In default page Anywhere in RAM In page pointed to PSVPAG register Example var i char far memory qualifier is set variable i can allocated somewhere in data memory var j char near near memory qualifier is set variable j will be allocated in the first 8kB of data memory const k longint 10000 near memory qualifier is set constant k will be allocated in the default memory page Related topics dsPIC Memory Organization dsPIC Memory Type Specifiers 172 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 behav
173. 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 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 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 opera
174. rounded down to the nearest integer Example re 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 Prototype _ Prototype function ldexp valu newexp integer real Function pe the result of O the floating point number num by 2 raised to the power n i e EAA T x wam res function log x real real Seema Po returns the natural logarithm of x i e Log x log 10 res 2 302585E mikroPascal PRO for dsPICSO 33 and PIC24 log10 ie function log10 x real real Eerie returns the base 10 logarithm of x i e Log x 1log10 100 res 2 000000 modf Erotonne function modf val real var iptr real real Returns argument va1 split to the fractional part function return val and integer part in number iptr es modf 6 25 iptr res 0 25 iptr 6 00 pow Prototype function pow x real y real real Description Function returns the value of x raised to the power y i e x If x is negative the function will automatically cast y into unsigned long res pow 10 5 res 9 999984e 4 sin iiai a function sin arg real real Function returns
175. 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 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 Lee SPI_Glcd_ Box Prototype procedure SPI Glcd Box x upper left y_upper left x bottom right y bottom fight 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 Glcd needs to be initialized for SP communication see SPI_Glcd_lInit routine Draw a box between dots 5 15 and 20 40 SPI Glcd_ Box 5 15 20 40 1 Notes None SSCS MikroElektronika 529 mikroPascal PRO for dsPICSO 33 and PIC24 SPI_Glcd_ Circle Prototype procedure SPI Glcd_Circle x_center y center radius integer color byte Description Draws a circle on Glcd Parameters x center x coordinate of
176. 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 ENC243600 module The ENC24J600 module should be properly cofigured by the means of SPI_Ethernet_24j600_Init routine 004 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_Ethernet_24j600_Disable Prototype procedure SPI Ethernet _24j600 Disable disFlt word 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 Description This is MAC module routine This routine disables appropriate network traffic on the ENC247600 module by the means of it s receive filters unicast multicast broadcast crc Specific type of network constants see the table below can be ORed to form a ppropriate input value disF1t network traffic receive filter flags Each bit corresponds to the appropriate network traffic CRC check flag When set CRC check will be disabled ae a Ns and packets with invalid CRC field will be accepted KA a T pao unicast traffic will be disabled MAC Unicast traffic receive filter flag When set MAC Parameters receive filter 0 MAC Broadcast t
177. routines Gled_Fill Gled_Dot Gled_Line Gled_V_Line Glced_H_Line Gled_Rectangle Glcd_Rectangle_Round_Edges Glcd_Rectangle_Round_Edges_ Fill Glcd_Box Glcd_Circle Gled_Circle_Fill Gled_Set_Font Gled_Write_Char Gled_Write_Text Glcd_Image Glcd_Partiallmage Gled_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 GLC GLC GLC LC LC LC LC LC LC LC LC LC DO Data pin O D1 Data pin 1 D2 Data pin 2 D3 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 UUGVUUCUUUU UO OU on 349 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Requires EN Enable signal pin RST Reset signal pin DO Direction Direction of the Data pin 0 D1 Direction Direction of the Data pin 1 D2 Direction Direction of the Data pin 2 D3 Direction Direction of the Data pin 3 D4 Direction Direction of the Data pin 4 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 D CS2 Direction Direc
178. size that is to be erased is different from the one that can be written with this function This function is used as a part of the Flash write sequence therefore the FLASH_Write_Init function must be called before this one This function can be called several times before commiting the actual write to Flash operation FLASH_ Write_DoWrite This depends on the organization of the RTSP module for the certain dsPIC30 Please consult the Datasheet for particular dsPIC30 on this subject const iArr array 8 of word var ptr odata word ptr data iArr FLASH Write Init 0x006100 ptr data FLASH Write Loadlatch4 LASH Write Loadlatch4 LASH Write DoWrite MikroElektronika 340 mikroPascal PRO for dsPIC30 33 and PIC24 FLASH_Write_Loadlatch4_Compact Prototype procedure FLASH Write Loadlatch4 Compact Description Loads the current RTSP write latch with data 4 instructions 8 addresses 12 bytes The data is filled in the compact mode Requires The block to be written to must be erased first either from the user code FLASH_Erase32 or during the programming of MCU Please note that block size that is to be erased is different from the one that can be written with this function This function is used as a part of the Flash write sequence therefore the FLASH_Write_Init function must be called before this one This function can be called several times before committing actual write to F
179. storing received data in the following 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 set to 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 as 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_lInit 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 MikroElektronika 443 mikroPascal PRO for dsPICSO 33 and PIC24 Library Example The example demonstrates working with the dsPIC 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
180. the Slave The received data is displayed on 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 EasydsPIC4A board and dsPIC30F4013 Copy Code To Clipboard program RS485 Master Example var dat array 10 of byte buffer for receving sending messages ip J byte cnt Longinti set transcieve pin set transcieve pin direction var rs485 rxtx pin rs485 rxtx pin direction sbit at RF2 bit sbit at TRISF2 bit Interrupt routine procedure interrupt org IVT_ADDR_U2RXINTERRUPT begin RS485Master Receive dat U2RXIF bit 0 end ensure interrupt not pending begin cnt 0 ADPCFG OXFFFF PORTB PORTD TRISB TRISD r r r Oooog r UART2_ Init 9600 initialize UART2 module Delay ms 100 RS485Master Init initialize MCU as Master dat 0 OxAA dat 1 OxF0 dat 2 lt Ox0F dat 4 lt 09 ensure that message received flag is 0 dat 5 lt 0 ensure that error flag is 0 dat 6 0 RS485Master Send dat 1 160 URXISEL1 U2STA bit 0 URXISEL1 U2STA bit 0 NSTDIS bit 1 no nesting of interrupts U2RXIF bit 0 ensure interrupt not pending U2RXIE_ bit 1 enable intterupt MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 while TRUE do begin upon completed valid m
181. the registration form select your distributor and click the Submit button If you choose work offline registering method following window will be opened bh 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 Filip Jankovic ADDRESS Enter your address INVOICE Enter invoice Filip Jankovic Address invoice number EA Copy to clipboard SEND Cancel Fill out the registration form select your distributor and click the Submit button This will start your e 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 spe
182. the search The function returns an index of the matching character in s1 If s1 contains no characters from s2 the function returns OxF FFF txt mikroElektronika txt_sub mikr res i strpbrk txt_sub txt strrchr Prototype function strrchr var s string ch byte word 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 0xFFFF mikroElektronika res strrchr txt k returns the index of the k character of the MEXE string Prototype procedure ltrim var astring string The procedure trims the leading spaces of the string mikrol ltrim txt trims the leading 2 spaces of the txt string mikroPascal PRO for dsPICSO 33 and PIC24 rtrim Prototype procedure rtrim var astring string The procedure trims the trailing spaces of the string mikroE rerim txt trims the trailing 2 spaces of the txt string and adds terminating null character to the result strappendpre Prototype procedure strappendpre letter char var sl string The procedure appends character at the beginning of the string txt ikrok strappendpre m txt adds letter m at the beginning of the txt st
183. the sine of in radians The return value is from 1 to 1 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 2 If the value of x is too large if overflow ae the function fails Example res sinh PI 2 res 2 301296 ae function sqrt x real real Function returns the non negative square root of x Example re tan PI 4 res 0 999998 688 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 canes the mikroPascal PRO for dsPIC30 33 and PIC24 tan PI 4 res 0 999998 tanh eee function tanh real real Function returns the tangent of x defined mathematically as sinh x cosh x Example re tanh PI 4 ves 0 655793 MikroElektronika 689 mikroPascal PRO for dsPIC30 33 and PIC24 Trigonometry Library The mikroPascal PRO for dsPIC30 33 and PIC24 implements fundamental trigonometry functions These functions are implemented as look up tables Trigonometry 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 si
184. 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 mikroElektronika txt sub q mikr strncpy txt txt_sub 4 copies first 4 characters form the string txt_ sub to Ext mikroPascal PRO for dsPICSO 33 and PIC24 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 character 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 mikroElektronika Ext sub v 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 1 en characters of the strings s1 and s2 and returns a value indicating their relationship Meaning sl less than s2 sl equal to s2 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 1en words mikroElektronika
185. this page FLASH _Read_Compact Prototype procedure FLASH Read a aia cia longint var write to array 100 of byte NoBytes word Reads required number of ee from the flash memory in the compact mode Parameters address starting address of the FLASH memory block to be read write to starting address of RAM buffer for storing read data NoBytes number of bytes to be read Returns Address of RAM buffer for storing read data Requires OOOO var Buffer array 10 of byte start address longint FLASH Write 0x006500 data start_address 0x6500 FLASH Read start_address Buffer on The user should take care of the address alignment see the explanation at the beginning of this page Library Example In this example written for dsPIC30F4013 various read write tecniques to from the on chip FLASH memory are shown Flash memory is mapped to address space 3 2 meaning every 3 consecutive bytes of Flash have 2 consecutive address locations available That is why mikroE s library allows data to be written to Flash in two ways regular and compact In regular mode which is used for variables that are size of 2 bytes and more the 3rd un addressable byte remains unused In compact mode which can be used for 1 byte sized variables arrays all bytes of flash are being used 345 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Copy Code To Clipboard progr
186. through it We suggest you to consult Projects and Source Files first and then start browsing the examples that you re the most interested in Copyright c 2002 2010 mikroElektronika All rights reserved What do you think about this topic Send us feedback 31 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 What s new in mikroPascal PRO for dsPIC30 33 and PIC24 IDE build 4 60 Command line build 4 60 New features and enhancements in the following areas will boost your productivity by helping you complete many tasks more easily and in less time For a complete version history of mikroPascal PRO for dsPIC30 33 and PIC24 visit the following link http www mikroe com download eng documents compilers mikropascal pro dspic version_history txt Compiler Changes IDE Changes Compiler Changes Fixed Optimization issues in specific cases when destination variable is in Rx space IDE Changes Fixed Compiler version is not visible in caption if no projects are open Parameter assistant ignores commas when switching to another parameter Occasional lost of configuration flags when swithing between projets Improper display of RAM memory usage in statistics Improved Communication to programmer concerning supported chips License Key Request form MikroElektronika 32 mikroPascal PRO for dsPICSO 33 and PIC24 Software License Agreement mikroElektronika Associates License Statement and
187. time for a single instruction The X and Y data space boundary is fixed for any given device When not doing DSP instructions the memory is all treated as a single block of X memory 168 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 DMA RAM Every dsPIC33F device contains a portion of dual ported DMA RAM located at the end of Y data space Direct Memory Access DMA is a very efficient mechanism of copying data between peripheral SFRs and buffers or variables stored in RAM with minimal CPU intervention The DMA controller can automatically copy entire blocks of data without requiring the user software to read or write the peripheral Special Function Registers SFRs every time a peripheral interrupt occurs The DMA controller uses a dedicated bus for data transfers and therefore does not steal cycles from the code execution flow of the CPU To exploit the DMA capability the corresponding user buffers or variables must be located in DMA RAM Unimplemented Memory Space The last segment of data RAM space is not implemented but can be mapped into program space for Program Space Visibility This allows program memory to be read as though it were in data RAM Notes Boundaries between memory spaces are device specific Please refer to the appropriate datasheet for details Memory spaces are not shown to scale Please refer to the appropriate datasheet for details There are seven memory type specifiers that can be us
188. two message formats Standard format with 11 identifier bits and Extended format with 29 identifier bits ECAN message format and DMA RAM buffer definiton can be found in the ECan _Defs mpas header file located in the ECAN project folder Read this file carefully and make appropriate adjustments for mcu in use Also if a new project is to be created this file has to be copied adjusted and included into the project via include pragma directive with corresponding Search Path updating Important ECAN buffers are located in DMA RAM so two DMA channels are used for message transfer one for each direction ECAN gt DMA RAM DMA RAM gt ECAN See the ECANxDmaChannellnit routine Consult CAN standard about CAN bus termination resistance CAN library routines require you to specify the module you want to use To select the desired CAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of CAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Library Routines ECANxDmaChannellnit ECANxSetOperationMode ECANxGetOperationMode ECANxInitialize ECANxSelectTxBuffers ECANxFilterDisable ECANxFilterEnable ECANxSetBufferSize ECANxSetBaudRate ECANxSetMask ECANxSetFilter ECANxRead ECANxWrite MikroElektronika 298 mikroPascal PRO for dsPICSO 33 and PIC24 ECANxDmaChannellnit Protot
189. 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 311 mikoPascal PRO for dsPIC30 33 and PIC24 Moving text for i 0 to 3 do begin Move text to Led Cmd LCD SHIFT RIGHT Move Delay end while TRUI begin for i 0 to 6 do begin ea do Endless loop Move text to Led Cmd LCD SHIFT LEFT Move _ Delay end for i 0 to 6 do begin r Move text to Led Cmd LCD SHIFT RIGHT Move_Delay r the right 4 times the left 7 times the right 7 times end end end a N rdo 7 RDI 2 A oO amp LCD 2X16 Lcd HW connection MikroElektronika 318 mikroPascal PRO for dsPICSO 33 and PIC24 Manchester Code Library The mikroPascal PRO for dsPIC30 33 and PIC24 provides a library for handling Manchester coded signals The Manchester code is a code in which data and clock signals are combined to form a single self synchronizing data stream each encoded bit contains a transition at the midpoint of a bit period the direction of transition determines whether the bit is O or 1 the second half is the true bit value and the first half is the complement of the true bit value as shown in the figure below Man
190. where y is 0 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 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 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 oo o foa o greater than or equal lt less than or equal Relational 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 at5 gt c 1 0 e Z a 5 gt ec 1 0 e MikroElektronika 211 mikroPascal PRO for dsPICSO 33 and PIC24 Bitwise Operators Use bitwise operators to modify individual bits of numerical operands Bitwise operators associate from left to right The only exception is the bitwise complement operator not which as sociates 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 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
191. 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 attr file creation and attributes flags Each bit corresponds to the appropriate file attribute 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 MikroElektronika 290 mikroPascal PRO for dsPICSO 33 and PIC24 Le oao Doves riemal use ony never ound on ak 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 bi Bit mask Description po oot Read Only O 0 otherwise CF card and CF library must be initialized for file operations See Cf_Fat_Init Try to create a swap file with arch
192. word data array 8 of byte msg id longint ECAN1SetOperationMode _ECAN MODE NORMAL OxFF set NORMAL mode ECANI1 module must be in a mode in which receiving is possible clear message flags msg rcvd ECAN1Read msg_ id data data len rx flags then ECAN library routine require you to specify the module you want to use To select the desired ECAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of ECAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 307 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 ECANxWrite Prototype function ECANxWrite id longint var Data array 8 of byte DataLen ECAN TX MSG FLAGS word word Description If at least one empty Transmit Buffer is found the function sends message in the queue for transmission Parameters id ECAN message identifier Valid values all 11 or 29 bit values depending on message type standard or extended Data data to be sent DataLen data length Valid values 0 8 ECAN TX MSG FLAGS message flags Valid values ECAN TX MSG FLAGS constants See ECAN_ X_MSG_FLAGS constants 0 if all Transmit Buffers are busy OxFFFF if at least one Transmit Buffer is empty and available for transmition Requires The ECAN routines are supported only by MCUs with the ECAN module Microcontr
193. 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 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 text GLCD LIBRARY DE 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 yl y coordinate of the line end pcolor color parameter Valid values T6963C_BLACK and T6963C_WHITE a eS line 0 0 239 127 T6963C WHITE Notes None CS 574 MikroElektronika miko
194. you can make the routine public i e visible outside of unit Prototypes must match the declarations exactly 195 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 type for each variable is mandatory Syntax for variable declaration is var identifier list type Here identifier list is acomma 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 Jy 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 calc
195. 0x1E PLLFBDbits PLLDIV Ox1E CLKDIV CLKDIV and OxFF3F CLKDIVbits PLLPOST 1 CLKDIV CLKDIV or 0x00C0 AD1IPCFGH OxFFFF ZZ AD1PCFGL OxFFFF all ports digital I O AD2PCFGL OxFFFF Clear Interrupt Flags IFSO 0 IFS1 0 IFS2 0 MikroElektronika 313 mikoPascal PRO for dsPIC30 33 and PIC24 XTD_ MSG IFS3 0 IFS4 0 Enable ECAN1 Interrupt IEC2 C1IE 2 1 enable ECAN1 interrupts C1lINTE TBIE 1 enable ECAN1 tx interrupt C1INTE RBIE 1 enable ECAN1 rx interrupt PORTB 0 clear PORTB TRISB 0 set PORTB as output for received message data displaying Can Init Flags 0 Can_Send Flags 0 clear flags Can_Rev_Flags 0 ZZ Can Send Flags ECAN TX PRIORITY 0 and form value to be used _ECAN TX _XTD FRAME and with CANSendMessage ECAN TX NO RTR FRAME Can_Init Flags _ECAN CONFIG SAMPLE THRICE and form value to be used ECAN CONFIG PHSEG2 PRG ON and with CANInitialize ECAN CONFIG XTD MSG and ECAN CONFIG MATCH MSG TYPE and ECAN CONFIG LINE FILTER OFF RxTx Data 0 9 set initial data to be sent ECAN1DmaChannelInit 0 1 ECANIRxTxRAMBuffer init dma channel 0 for dma to ECAN peripheral transfer ECAN1DmaChannelInit 2 0 ECANIRxTxRAMBuffer init dma channel 2 for ECAN peripheral to dma transfer ECAN1Initialize 1 3 3 3 1 Can_Init Flags
196. 0x5134 Ox9DOE Ox471D Ox9592 Ox3C57 Ox8F1D Ox30FC Ox89BE 022528 0x8583 0xX18F9 Ox8276 Ox0C8C Ox809E 0x0000 Ox8000 OxF374 Ox809E OxE707 0x8276 OxDAD8 0x8583 OxCFO4 Ox89BE OxC3A9 Ox8F1D OxB8E3 0x9592 OxAECC Ox9DOE OxA57E OxXA5S7E Ox9DOE OxAECC 0x9592 OxB8E3 Ox8F1D OxC3A9 Ox89BE OxCF04 0x8583 OxDAD8 0x8276 OxE707 Ox809E OxF374 TwiddleCoeff_128 const TwiddleCoeff 128 array 128 of word Ox7FFF 0x0000 Ox7FD9 OxF9B8 Ox7F62 OxF374 Ox7E9D OxED38 Ox7D8A OxE707 Ox7C2A OxEOE6 Ox7A7D OxDAD8 0x7885 OxD4E1 0x7642 OxCFO04 Ox73B6 0xC946 0x70E3 OxC3A9 Ox6DCA OxBE32 Ox6A6E OxB8E3 0x66D0 OxB3C0O 0x62F2 OxAECC Ox5ED7 OxAAOA Ox5A82 OxAS7E Ox55F6 0xA129 0x5134 Ox9DOE 0x4C40 0x9930 Ox471D 0x9592 Ox41CE 0x9236 0x3C57 Ox8F1D Ox36BA 0x8C4A Ox30FC Ox89BE Ox2B1F 0x877B 0x2528 0x8583 Ox1F1A 0x83D6 Ox18F9 0x8276 0x12C8 0x8163 Ox0C8C Ox809E 0x0648 0x8027 0x0000 O0x8000 OxF9B8 0x8027 OxF374 Ox809E OxED38 0x8163 OxE707 0x8276 OxEOE6 0x83D6 OxDAD8 0x8583 OxD4E1 0x877B OxCFO4 Ox89BE 0xC946 Ox8C4A OxC3A9 Ox8F1D OxBE32 0x9236 OxB8E3 0x9592 0xB3C0 0x9930 OxAECC Ox9DOE OXxAAOA 0xA129 OxAS7E OxAS7E OxA129 OxAAOA Ox9DOE OxAECC 0x9930 OxB3CO 0x9592 OxB8E3 0x9236 OxBE32 Ox8F1D 0xC3A9 Ox8C4A 0xC946 Ox89BE OxCFO04 0x877B OxD4E1 0x8583 OxDAD8 Ox83D6 OxEOE6 0x8276 OxE707 0x8163 OxED38 Ox809E OxF374 0x8027 Ox
197. 1 161 Single Static Assignment Optimization 162 Introduction 162 Proper Coding Recommendations 163 Asm code and SSA optimization 164 Debugging Notes 164 Warning Messages Enhancement 164 Common Object File Format COFF 165 COFF File Format 165 COFF File Generation 165 CHAPTER 7 167 dsPIC30 33 and PIC24 Specifics 167 Types Efficiency 168 Nested Calls Limitations 168 Limits of Indirect Approach Through PSV 168 Limits of Pointer to Function 168 Variable constant and routine alignment 168 dsPIC Memory Organization 169 Program Memory ROM 169 Data Memory RAM 170 SFR Memory Space 170 X and Y Data RAM 170 DMA RAM 171 Unimplemented Memory Space 171 Memory Type Specifiers 172 code 172 data 172 rx 172 sfr 172 xdata 173 ydata 173 dma 173 Memory Type Qualifiers 174 Near Memory Qualifier 174 Far Memory Qualifier 174 Read Modify Write Problem 175 CHAPTER 8 179 mikroPascal PRO for dsPIC30 33 and PIC24 Language Reference 179 Lexical Elements Overview 181 Whitespace 182 Newline Character 182 Whitespace in Strings 182 Comments 183 MikroElektronika 1 mikoPascal PRO for dsPIC30 33 and PIC24 Tokens Token Extraction Example Literals Integer Literals Floating Point Literals Character Literals String Literals Keywords Identifiers Case Sensitivity Uniqueness and Scope Identifier Examples Punctuators Brackets Parentheses Comma Semicolon Colon Dot Program Organization Organization of Main Module Organi
198. 1 2 write erase 1 pen size i 1 while TRUE do begin if TP Press Detect lt gt 0 then begin After a PRESS is detected read X Y and convert it to 128x64 space if TP_Get_Coordinates x_coord y coord 0 then begin if x_ coord lt 31 and y coord lt 8 then begin Glcd_Fill 0 Pen Menu Gled Rectangle 41 0 52 9 1 3 Glcd_Box 45 3 48 6 1 Gled Rectangle 63 0 70 7 1 7 Glcd_ Box 66 3 67 4 1 Gled Rectangle 80 0 86 6 1 7 Gled Dot 83 3 1 7 Gled V Line 0 7 0 1 7 Gled Write Text clear msg 1 0 0 Gled_V_Line 0 7 97 1 7 612 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 if write erase then Gled Write Text erase msg 98 0 0 else Gled Write Text write msg 98 0 0 end If write erase is pressed if x_coord gt 96 and y coord lt 8 then begin if write erase then begin write erase 0 Glcd_ Write Text write msg 98 0 0 Delay ms 500 end else begin write erase i L Gled Write Text erase msg 98 0 0 Delay ms 500 end end If pen size is selected if x_coord gt 41 and x coord lt 52 and y coord lt 9 then pen size 3 if x_coord gt 63 and x coord lt 70 and y coord lt 7 then pen size 7 27 if x_coord gt 80 and x coord lt 86 and y coord lt 6 then pen size i 1 if y coord lt 11 then continue case pen size of 1 if x coord gt 0 and y coo
199. 1 number of the first vector elements numElemsV2 number of the second vector elements dest result vector Nothing Requires Nothing var vecl array 3 of word vConDest2 array 10 of word Vector Convolve vecl vecl vConDest2 3 3 WO W7 used not restored W8 W10 saved used restored AccuA used not restored CORCON saved used restored Vector_Add Prototype procedure Vector Add var dest vl v2 array 256 of word Description Function calculates vector addition dstV n srcV1 n srcV2 n n e 0 numElems 1 Parameters v1 first vector v2 second vector numElemsV1 number of vector s elements dest result vector Nothing Requires Nothing var vecl array 3 of vec2 array 3 of vecDest gt array 3 of Vector Add vecDest vecl v WO W4 used not restored AccuA used not restored CORCON saved used restored MikroElektronika 649 mikroPascal PRO for dsPICSO 33 and PIC24 Matrix Library Matrices Library mikroPascal PRO for dsPIC30 33 and PIC24 includes a library for operating and working with matrices All routines work with fractional Q15 format Library Routines Matrix_Transpose Matrix_Subtract Matrix_Scale Matrix_Multiply Matrix_Add Matrix_Transpose Prototype procedure Matrix Transpose var src dest array 1024 of word numRows numCols word Description Function does matrix transposition
200. 10 shr 4 10 month and Ox0F Transform month end aaa a Output values to LCD procedure Display Time begin Led Chr 1 6 day 10 48 Print tens digit of day variable Led Chr 1 7 day mod 10 48 Print oness digit of day variable Led Chr 1 9 month 10 48 Led Chr 1 10 month mod 10 48 Led Chr 1 15 year 57 Print year vaiable 9 start from year 2009 Led Chr 2 6 hours 10 48 Led Chr 2 7 hours mod 10 48 Led Chr 2 9 minutes 10 48 Led Chr 2 10 minutes mod 10 48 Led Chr 2 12 seconds 10 48 Led Chr 2 13 seconds mod 10 48 end OD AA Performs project wide init procedure Init Main begin ADPCFG OxFFFF initialize AN pins as digital Soft 12 Tnit ji i Led Init dof Led Cmd LCD CLEAR Led Cmd LCD CURSOR OFF ff Led Out 1 1 Date if Led Che 1 ep ir bed Chr Ly dys hy Led Out 2 1 Times yi Led Che 2 8 ana Led Ona 2 11 i j7 Led Out 1 12 200 end a Main procedure begin Delay ms 1000 Init Main ii while TRUE begin Read Time Transform Time Display Time end end do is Initialize Soft I2C communication Initialize LCD Clear LCD display Turn cursor off Prepare and output static text on LCD Perform initialization Endless loop Read time from RTC PCF8583 Format date and time Prepare and display on LCD 454 mikoPascal PR
201. 2 lt byte a array 10 of byte array a containing 10 elements of type byte begin ptrl a 4 ptr2 a 2 if ptrl ptr2 then won t be executed as 4 is not equal to 2 if ptrl gt pte2 then sss will be executed as 4 is greater than 2 if ptr1 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 pointed to by ptrl is greater to the value pointed to by ptr2 end MikroElektronika 209 mikroPascal PRO for dsPICSO 33 and PIC24 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 t ype advances the pointer 50 bytes in memory For example var a array 10 of byte array a containing 10 elements of type byte ptr byte pointer to byte beg
202. 2 Dit Library Routines Soft_I2C_Init Soft_I2C_Start Soft_I2C_Read Soft_I2C_Write Soft_I2C_Stop Soft_l2C_Break MikroElektronika 449 mikroPascal PRO for dsPICSO 33 and PIC24 Soft_I2C_Init FRetums Nong OOOO SSS Requires Global variables Soft 12C_ Scl Soft I C clock line Soft _12C_Sda Soft I C data line Soft _I2C_ Scl_ Pin Direction Direction of the Soft I C clock pin Soft _12C Sda_ Pin Direction Direction of the Soft l C data pin must be defined before using this function Software I2C connections var Soft I2C Scl 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 biG End Software I2C connections Soft I2C Init 7 Soft_I2C_Start FRetums Nong OOOO SSS Software I C must be configured before using this function See Soft_I2C_Init routine Issue START signal Sore I2C Start 450 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 ack 0 not acknowledge signal will be sent after reading otherwise the acknowledge signal will be sent One byte from the Slave Requires Soft C must be configured before using this function See Soft_I2C_Init routine Also START signal needs to
203. 2 Init Advanced 2400 2 1 1 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 4 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 UARTx_Data_Ready il 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 vead data if ready if UART1 Data Ready 1 then receive UART1 Read module simply change the letter x in the routine prototype for a number from 1 to 4 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library B UART library routines require you to specify the module you want to use To select the desired UART mikroPascal PRO for dsPIC30 33 and PIC24 UARTx_Tx_Idle Use the function to test if the transmit shift register is empty or not 1 if the data has been transmitted 0 otherwise Requires Routine requires at leas
204. 24 PWMx_Mc_Init Prototype function PWMx Mc Init freq hz pair output mode enable output x clock_ prescale output_postscale word word Description Initializes the Motor Control PWM module with duty ratio 0 The function calculates timer period writes it to the MCU s PTPER register and returns it as the function result Parameters freq _ hz PWM frequency in Hz refer to device datasheet for correct values in respect with Fosc pair output mode output mode for output pin pairs 1 independent 0 complementary If pair output mode BO is equal to 1 then PWM channels PWM1L and PWM1H will be independent If pair output mode B1 is equal to 0 then PWM channels PWM2L and PWM2H will be complementary If pair output _mode Bn is equal to 1 then PWM channels PWM n 1 L and PWM n 1 H will be independent If pair output mode Bn is equal to 0 then PWM channels PWM n 1 L and PWM n 1 H will be complementary enable output x bits lt 7 0 gt are enabling corresponding PWM channels lt PWM4H PWM3H PWM2H PWM1H PWM4L PWM3L PWM2L PWMLL gt If bit value is equal to 0 then corresponding PWM channel is disabled pin is standard 1 0 If bit value is equal to 1 then corresponding PWM channel is enabled pin is PWM output For detalied explanation consult the Motor Control PWM Module section in device datasheet clock prescale output postscale PWMclock prescaler postscaler settings Values lt 0 3 gt and lt 0 15 gt
205. 24 mikroPascal PRO for dsPICSO 33 and PIC24 If Statement Use the keyword i to implement a conditional statement The syntax of the i statement has the following form if expression then statementl else statement2 If expression evaluates to true then statement1 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 nearest 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 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 valu
206. 30 33 and PIC24 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 in all projects gouge i Description using Keypad Library var keypadPort word sfr external Keypad Port var keypadPort byte at PORTB var keypadPort Direction word sfr var keypadPort Direction byte at external Keypad Port TRISE Library Routines Keypad_Init Keypad_Key_Press Keypad_Key_Click Keypad_Init Rems Noting OOO Requires Global variable keypadPort Keypad port must be defined before using this function Keypad module connections var keypadPort 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 369 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 Prototype Description Call to Keypad Key Click is a blocking call the function waits until some key is pressed and released When released the functi
207. 3700 DATA Direction sbit at byte sfr external pins PORTD D 3700_CS sbit at LATC4 bit var 5S1D13700_WR_Direction Direction of the Write pin 3700 WR Direction sbit sfr external eee TRISC2_bit var 1D13700_RD Direction Direction of the Read pin D13700_RD_ Direction sbit sfr external vee pin TRISC1_ bit var 1D13700 AO Direction Direction of the System Address var S1D13700 AO Direction pin TRISCO bit sbit sfr external var 51D13700 RES Direction Direction of the Reset pin var S1D13700_RES Direction sbit at sbit sfr external iia pin TRISC3 bit var 1D13700_CS Direction Direction of the Chip select pin var S1D13700_CS_ Direction sbit sfr external ee IP pin TRISC4 bit 321 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Library Routines 1D13700_Init 1D13700_Write_Command 1D13700_Write_Parameter 1D13700_Read_Parameter 1D13700_Fill 1D13700_GrFill 1D13700_TxtFill 1D13700_Display_GrLayer 1D13700_Display_TxtLayer 1D13700_Set_Cursor 1D13700_Display_Cursor 1D13700_Write_Char 1D13700_Write_Text 1D13700_Dot 1D13700_Line 1D13700_H_Line 1D13700_V_Line 1D13700_Rectangle 1D13700_Box 1D13700_Rectangle_Round_Edges 1D13700_Rectangle_Round_Edges_Fill 1D13700_Circle 1D13700_Circle_Fill 1D13700_Image 1D13700_Partiallmage MikroElektronika 322 mikroPascal PRO fo
208. 3C WHITE T6963C_circle 120 64 110 T6963C_WHITE T6963C_circle 120 64 130 T6963C_WHITE T6963C_sprite 76 4 einstein 88 119 Draw a sprite T6963C_setGrPanel 1 Select other graphic panel T6963C_image mikroE 240x128 bmp Draw an image SENDIF while TRUE do Endless loop begin Eg If RB8 is pressed toggle the display between graphic panel 0 and graphic 1 7 if RB8 bit lt gt 0 then begin T6963C graphics 1 TOIGIC ext 0 7 Delay ms 300 end mikroPascal PRO for dsPIC30 33 and PIC24 Tf RB9 is pressed display only graphic panel IFDEF COMPLETE EXAMPLE else if RB9 bit lt gt 0 then begin Inc panel panel panel and 1 T6963C setPtr T6963C grMemSize T6963C_ txtMemSize HOME ADDRESS_SET Delay ms 300 end SENDIF Tf RB10 is pressed display only text panel ai else if RB10 bit lt gt 0 then begin T6963C_ graphics 0 T6963C_ text 1 Delay ms 300 end Tf RB11 is pressed display text and graphic panels J 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 else if RB12 bit lt gt 0 then begin Tne ours 2 if curs 3 then curs 0 case curs of 0 nO cursor TE963E cursor 0 1 begin blinking cursor T696SC Cursor 1y panel T6963C_ GRAPHIC MikroElekt
209. 4 S1D13700_Write Text Prototype procedure S1D13700 Write Text var str string x y word mode byte Nothing Description 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 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 San LATO eU ERR ROR In this mode the text and graphics data are combined via the logical exclusive OR S1p13700 OURRIAY AND The text and graphic data shown on display are combined via the logical AND function Glcd module needs to be initialized See the S1D13700_Init routine Eram S1D13700 Write Text EPSON LIBRARY DE 0 1D13700 OVERLAY OR 1D13700_Dot 1D13700_OVERLAY_OR Prototype procedure S1D13700 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 1D13700_BLACK Black color 1D13700_ WHITE White color Glcd module needs to be initialized See the S1D13700_Init routine eae 1D13700 Dot 50 50 S1D13700 WHITE 329 MikroElektronika mikoP
210. 429 Library Routines 429 Ps2_Config 430 Ps2_Key_Read 430 Special Function Keys 431 Library Example 432 HW Connection 433 PWM Library 433 Library Routines 433 PWM_lInit 434 PWM_Set_Duty 434 PWM_ Start 435 PWM_Stop 435 Library Example 435 HW Connection 437 PWM Motor Control Library 437 Library Routines 437 PWMx_Mc_Init 438 PWMx_Mc_Set_Duty 439 PWMx_Mc_ Start 439 PWMx_Mc_Stop 440 HW Connection 441 RS 485 Library 441 Library Dependency Tree 442 External dependencies of RS 485 Library 442 Library Routines 442 RS485Master_Init 442 RS485Master_Receive 443 MikroElektronika 1 mikoPascal PRO for dsPIC30 33 and PIC24 RS485Master_Send 443 RS485Slave_Init 444 RS485Slave_Receive 445 RS485Slave_Send 445 Library Example 446 HW Connection 449 Message format and CRC calculations 450 Software C Library 451 External dependencies of Software 1 C Library 451 Library Routines 451 Soft_I2C_Init 452 Soft_l2C_Start 452 Soft_I2C_Read 453 Soft_I2C_Write 453 Soft_l2C_Stop 453 Soft_I2C_Break 454 Library Example 455 Software SPI Library 457 External dependencies of Software SPI Library 457 Library Routines 457 Soft_SPI_Init 458 Soft_SPl_Read 458 Soft_SPI_Write 459 Library Example 459 Software UART Library 461 Library Routines 461 Soft_UART_Init 461 Soft _UART_Read 462 Soft_UART_Write 462 Soft_UART_Break 463 Library Example 464 Sound Library 465 Library Routines 465 Sound_Init 465 Sound_Play 465 Library Example 466 HW Connection
211. 468 SPI Library 469 Library Routines 469 SPIx_Init 470 SPIx_Init_Advanced 471 SPIx_Read 473 SPIx_Write 473 SPI_Set_Active 474 Library Example 474 HW Connection 475 MikroElektronika 18 mikroPascal PRO for dsPICSO 33 and PIC24 SPI Ethernet Library 476 Library Dependency Tree 476 External dependencies of SPI Ethernet Library 477 Library Routines 477 SPI_Ethernet_lInit 478 SPI_Ethernet_Enable 480 SPI_Ethernet_Disable 481 SPI_Ethernet_doPacket 482 SPI_Ethernet_putByte 482 SPI_Ethernet_putBytes 483 SPI_Ethernet_putConstBytes 483 SPI_Ethernet_putString 484 SPI_Ethernet_putConstString 484 SPI_Ethernet_getByte 484 SPI_Ethernet_getBytes 485 SPI_Ethernet_UserTCP 485 SPI_Ethernet_UserUDP 486 SPI_Ethernet_setUserHandlers 486 SPI_Ethernet_getlpAddress 487 SPI_Ethernet_getGwlpAddress 487 SPI_Ethernet_getDnslpAddress 488 SPI_Ethernet_getlpMask 488 SPI_Ethernet_confNetwork 489 SPI_Ethernet_arpResolve 490 SPI_Ethernet_sendUDP 490 SPI_Ethernet_dnsResolve 491 SPI_Ethernet_initDHCP 492 SPI_Ethernet_doDHCPLeaseTime 492 SPI_Ethernet_renewDHCP 493 Library Example 493 HW Connection 500 SPI Ethernet ENC24J600 Library 501 Library Dependency Tree 501 External dependencies of SPI Ethernet ENC24J600 Library 502 Library Routines 503 SPI_Ethernet_24j600_Init 504 SPI_Ethernet_24j600_ Enable 506 SPI_Ethernet_24j600_Disable 507 SPI_Ethernet_24j600_doPacket 508 SPI_Ethernet_24j600_putByte 508 SPI_Ethernet_24j600_putBytes 509 SPI_Ethernet_24j600_p
212. 5 UART External dependencies of RS 485 Library The following variable must be defined De s ristion 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 Library Routines RS485Master_Init RS485Master_Receive RS485Master_Send RS485Slave_Init RS485Slave_Receive RS485Slave_Send RS485Master_Init Rems Nothing O OOOO Requires Global variables RS485 rxtx pin this pinis 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 440 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 RS485Master_Receive Prototype procedure RS485Master Receive var data array of byte Description Receive
213. 55 255 255 255 255 255 255 255 255 255 255 128 0 0 0 0 0 0 O O O O O O 0 0 0 0 0 O O O O O 1 128 0 0 0 0 Oo Oo 0 GO 0O 0 0 0 0 MikroElektronika 92 mikroPascal PRO for dsPICSO 33 and PIC24 HID Terminal The mikroPascal PRO for dsP IC30 33 and PIC24 includes the HID communication terminal for USB communication You can launch it from the drop down menu Tools gt HID Terminal Terminal Descriptor HID Devices ABBAHOME ABBAHOME mikroE HID Librar Dell Premium USB Optical Mouse Info in HID Read Write Test Communication HID Read Write Test Send 7 Append CR V Send as Typing I Append LF I7 Send as Number Format ASCI C HEX C DEC Clear MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Lcd Custom Character mikroPascal PRO for dsPIC30 33 and PIC24 includes the Lcd Custom Character Output is mikroPascal PRO for dsPIC30 33 and PIC24 compatible code You can launch it from the drop down menu Tools gt Lcd Custom Character MikroElektronika LCD Custom Char Generator B 5x10 Save Load Fillall Clearall Invert Preview Font size 5x7 cursor line D 5x10 cursor line CGRAM address Char Char data row mikroC PRO mikroPascal PRO mikroBasic PRO const char character 0 4 2 31 2 4 0 0 void CustomChar char pos_row char pos_char char
214. 63C 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 Constr 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 C D RD Library Dependency Tree m Port_Expander SPI T6963C Gica 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
215. 661 Library Dependency Tree 661 Library Routines 661 ByteToStr 662 ShortToStr 662 WordToStr 663 IntToStr 663 LongintToStr 664 LongWordToStr 664 FloatToStr 665 WordToStrWithZeros 666 IntToStrWithZeros 666 LongWordToStrWithZeros 667 LongIntToStrWithZeros 667 ByteToHex 668 ShortToHex 668 WordToHex 669 IntTtoHex 669 LongWordToHex 670 LongIntToHex 670 StrTolnt 671 StrToWord 671 Bcd2Dec 671 Dec2Bcd 672 Bcd2Dec16 672 Dec2Bcd16 672 Setjmp Library 673 Library Routines 673 Setjmp 673 Longjmp 673 Library Example 674 String Library 675 Library Functions 675 memchr 675 memcmp 676 memcmp 676 MikroElektronika 26 mikroPascal PRO for dsPICSO 33 and PIC24 memcpy 676 memmove 677 memset 677 strcat 677 strcat2 678 strchr 678 strcmp 678 strcpy 679 strlen 679 strncat 679 strncpy 679 strspn 680 strncmp 680 strstr 680 strcspn 681 strpbrk 681 strrchr 681 Itrim 681 rtrim 682 strappendpre 682 strappendsuf 682 length 682 Time Library 683 Library Routines 683 Time_dateToEpoch 683 Time_epochToDate 684 Time_dateDiff 684 Library Example 685 TimeStruct type definition 686 Trigon Library 687 Library Routines 687 acos 687 asin 687 atan 688 atan2 688 ceil 688 cos 688 cosh 688 eval_poly 688 exp 689 fabs 689 floor 689 frexp 689 Idexp 689 log 689 log10 690 MikroElektronika 21 mikoPascal PRO for dsPIC30 33 and PIC24 modf pow sin sinh sqrt tan tanh Trigonometry Library Library Routines sinE3 cosE3
216. 81F80 07FF6D B1006F 208810 781F80 200050 781F80 200020 lt US gt xmy lt BELL gt o gt MikroElektronika 134 mikroPascal PRO for dsPIC30 33 and PIC24 Software Simulator Debugger Options Debugger Options at Function Toolbar Description Key Icon Executes the current program line then halts If the executed program line Step Into calls another routine the debugger steps into the routine and halts after executing the first instruction within it Executes all remaining program lines within the subroutine The debugger Step Out halts immediately upon exiting the subroutine this option is provided with the PIC18 microcontroller family but not with the PIC16 family Executes the program until reaching the cursor position Ctrl F8 2am negate Gesabpadwe Toggle breakpoints option sets new breakpoints or removes those already F5 set at the current cursor position D EARI Executes the current program line then halts If the executed program line Step Over calls another routine the debugger will not step into it The whole routine will F8 be executed and the debugger halts at the first instruction following the call Related topics Run Menu Debug Toolbar 135 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 CHAPTER 6 mikroPascal PRO for dsPIC30 33 and PIC24 Specifics The following topics cover the specifics of mikroPascal PRO for dsPIC30 33 and PIC24 compiler Pr
217. 831 Web www mikroe com E mail office mikroe com MikroElektronika 34 mikroPascal PRO for dsPICSO 33 and PIC24 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 www mikroe com en compilers mikroPascal PRO dspic download htm 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 dsPIC30 33 and PIC24 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 dsPIC30 33 and PIC24 is always available for downloading from our website It is a fully functional software with the mikrolCD in circuit Debugger all the libraries examples and comprehensive help included The o
218. 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 mikoPascal PRO for dsPIC30 33 and PIC24 WOD SOJHILUMOIIJO Je SN JOE UOD 0 3e S y JOU OP sjesodoid sseuisng 10 S SUILUOD suoijsenb ue ney noA J yoddns tewoo aou MMM a we ye 38491 INOA pejd se jd uoewoyu jeuonyippe pasu ucenie sonposd no Jo hae YUM swisiqoid gulps Sole Bish ase nod yl WOT S0J4ILUMMM 12 eusqem Ino PSIA aseeid eoapcid ina ace 240 weej o fem noA o Q1Y OM d3ad3g Wa YO4 SNOILNTOS JYVMCYVH ANY JYYMLJOS
219. BUFFER 11 word 11 ECAN RX BUFFER 12 word 12 ECAN RX BUFFER 13 word 13 ECAN RX BUFFER 14 word 14 ECAN RX BUFFER 15 word 15 MikroElektronika 312 mikroPascal PRO for dsPICSO 33 and PIC24 Library Example The example demonstrates ECAN protocol The 1st 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 The 1st node then does the same and sends incremented data back to the 2nd node etc Code for the first ECAN node Copy Code To Clipboard program ECan lst uses ECAN Defs var Can Init Flags Can Send Flags Can Revy Flags word can flags Rx Data _Len word received data length in bytes RxTx Data array 8 of byte can rx tx data buffer Msg Revd word reception flag Rx_ID longint const ID list longint 12111 const ID 2nd longint 3 node IDs procedure CliInterrupt org 0x005A ECAN event iterrupt begin IFS2 C1IF 0 clear ECAN interrupt flag if C1INTF TBIF lt gt 0 then was it tx interrupt C1INTF TBIF 0 if yes clear tx interrupt flag if C1lINTF RBIF lt gt 0 then was it rx interrupt C1LINTF RBIF 0 if yes clear rx interrupt flag end begin Set PLL Fosc Fin PLLPRE PLLDIV PLLPOST 10MHZ 2 32 4 20MHz refer the family datasheet for more details CLKDIV CLKDIV and OxFFEO CLKDIVbits PLLPRE 0 PLLFBD
220. C Library The I C full master 1 C module is available with a number of the dsPIC30 33 and PIC24 MCU models The mikroPascal PRO for dsPIC30 33 and PIC24 provides a library which supports the master C mode Important IC library routines require you to specify the module you want to use To select the desired 1 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 Library Routines 12Cx_Init 12Cx_Start I2Cx_Restart 12Cx_ls_Idle 12Cx_Read 12Cx_Write 12Cx_Stop 12Cx_Init Prototype procedure 12Cx Init scl longint Description Configures and initializes the desired I C module with default settings This function enables the 1 C module by setting the I2CEN bit The rest of the bits in 1 C control register remains unchanged Default initialization after reset of 1 C module is continue operation in IDLE mode IPMI mode disabled 7 bit slave address slew rate control enabled general call address disabled software or receive clock stretching disabled scl requested serial clock rate MCU with the C module Initialize the I2C1 module with clock rate of 100000 E2C1 Init 100000 Refer to the MCU s datasheet for correct values of the scl in respect with Fosc IC library routines require you to specify the module
221. CE 2000 6 REAL ICE 7 PICkit 2 8 MPLAB ICD 3 2 Starter Ki Step Into Step Over Step Out Reset Breakpoints Stopwatch Complex Breakpoints Stimulus Profile Clear Code Coverage Refresh PM Settings dsPIC30F4013 oab sab IPO dcnovzc mikoPascal PRO for dsPIC30 33 and PIC24 7 Now you can start debugging the code by clicking Step Over button P on the Debug toolbar or by pressing F8 M MPLAB IDE v8 36 C WART mbas DER T Fie Edit View Project Debugger Programmer Tools Configure Window Help 8 x Ose AR SASAE d iotr EEO Re HwWBP 1 U sw mikroBasic PRO for dsPIC30 33 and PIC24 http wow mikroe com en compilers mikrobasic dspic NOTES Close pots RF3 TX and RFZ RX at J9 and J8 respectively board specific program UARTL dim uart_rd as byte main ADPCFG OxFFFF Configure AN pins as digital UART1_Init 9600 Initialize UART module at 3600 bps Delay_ms 100 Wait for UART module to stabilize ULMODE ALTIO un comment this line to have Rx and Tx pins on their alternate locations This is used to free the pins for other module UART1 Write Text Start UART1_Write 10 UART1_Write 13 while TRUE Endless loop if UART1_Data_Ready lt gt 0 then If data is received uart_rd UART1_Read read the received data UART1_ Write uart_rd and send data via UART end if dsPIC30F4013 gab sab IPO denovzc Rel
222. CU s datasheet ECAN Module PHSEG1 as defined in MCU s datasheet ECAN Module PHSEG2 as defined in MCU s datasheet ECAN Module PROPSEG as defined in MCU s datasheet ECAN Module ECAN CONFIG FLAGS ECAN module configuration flags Each bit corresponds to the appropriate ECAN module parameter Should be formed out of predefined ECAN flag constants See ECAN_ CONFIG_FLAGS constants The ECAN routines are supported only by MCUs with the ECAN module Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus initialize the ECAN1 module with appropriate baud rate and message acceptance flags along with the sampling rules var ecan config flags word ecan_ config flags ECAN CONFIG SAMPLE THRICE and Form value to be used ECAN CONFIG PHSEG2 PRG ON and with ECANInitialize ECAN CONFIG XTD MSG and ECAN CONFIG MATCH MSG TYPE and ECAN CONFIG LINE FILTER OFF ECAN1Initialize 1 1 ecan config flags initialize the ECAN1 module F B ECAN mode NORMAL will be set on exit ECAN library routine require you to specify the module you want to use To select the desired ECAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of ECAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 301 MikroElektronika mikoPasc
223. C_WHITE es Re Example SPI_1T6963C box 0 119 239 127 SPI _T6963C WHITE ates Nowe MikroElektronika 553 mikroPascal PRO for dsPICSO 33 and PIC24 SPI_T6963C_circle Prototype procedure SPI _T6963C_circle x integer r gt longint pcolor lt 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 Toshiba Glcd module needs to be initialized See SPI_T6963C a routine SPI_T6963C_circle 120 64 110 SPI _T6963C WHITE SPI_T6963C_circle_fill Prototype procedure SPI 1T6963C 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 pcolor color parameter Valid values SPI_T6963C_BLACK and SPI_T6963C_WHITE ews pong o oU Example SPI _T6963C circle fill1 120 64 110 SPI _16963C WHITE ees SPI_T6963C_image Prototype procedure SPI T6963C_image pic const byte Displays bitmap on Glcd pic image to be displayed Bitmap array can be located in both code and RAM memory due to the mikroPascal PRO for dsPIC30 33 and PIC24 pointer to const and pointer to RAM equivalency Toshiba Glcd module needs to be initialized See SPI_T6963C_Config routine Exa
224. Clear Timerl overflow interrupt flag end begin try Soft _12C Init with blocking prevention mechanism IPCO IPCO or 0x1000 Interrupt priority level 1 TITHE bit 1 Enable Timerl interrupts TICON 0x8030 Timerl ON internal clock FCY prescaler 2256 Soft T2C Imith TIIE bre x 03 Disable Timerl interrupts end Interrupts should be disabled before using Software C routines again see note at the top of this page 452 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Library Example The example demonstrates use of the Software I C Library The dsPIC30 33 or PIC24 MCU is connected SCL SDA pins to PCF8583 RTC real time clock Program sends date time to RTC Copy Code To Clipboard program var sec RTC_Read onds minutes z Hours Software I2C connections var Sof Sof t 120 Sel t T2c Sda Soft I2C Scl Direction Soft_I2C Sda Direction End Software I2C connections LCD module connections var LC var LC var LC var LC var LC var LC var LC var LC RS sbit at EN sbit at D4 sbit at D5 sbit at D6 sbit at D7 sbit at RS Direction EN Direction var LC var LC var LC var LC frei icic D4 Direction D5 Direction D6 Direction D7 Direction sbit sbit sbit sbit sbit sbit day month year byte Global date time variables sbit at RF3 bit sbit at RF2 bit sbit
225. D4 Direct external var GLCD D5 Direct external var GLCD D6 Direct external var GLCD D7 Direct external 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 ore GEF Direction of the Data 1 pin abit Direction of the Data 2 pin Sbit sfr Direction of the Data 3 pin Direction of the Data 4 pin Direction of the Data 5 pin Direction of the Data 6 pin 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 Sarr GEE Direction of the Enable pin SPIE SEE Direction of the Reset pin var RI var TRI var GLCD RISBA bit GLCD_DO Direction SBO bit GECD DI Direction SB1 bit D2 Direction Direc tion tion tion _Direction GLCD_CS1_Direction SB4 bit GLCD_CS2_Direction SB5 bit GLCD RS Direction FO bit GLCD_RW_Direction F1 bit GLCD_EN Direction F4 bit GLCD_RST Direction PS Dit MikroElektronika mikroPascal PRO for dsPICSO 33 and PIC24 Library Routines Basic routines Gled_Init Glcd_Set_Side Gled_Set_X Glced_Set_Page Glcd_Read_Data Gled_Write_Data Advanced
226. DI sbit at RB1 OBIE GLCD D0 sbit at RBO bit GLCD D7_ Dirretton sbit at TRISD3 bit GLCD_D6 Direction sbit at TRISD2 bit GLCD DS Direction sbit at TRISD1 bit GLCD_D4 Direction sbit at TRISDO bit GLCD_D3 Direction sbit at TRISB3 bit GLCD_D2 Direction sbit at TRISB2 bit GLCD D1 Direction sbit at TRISBI bit GLCD D Direction sbit at TRISBO bit var GLCD CSI sbit at LATB4 bit GLCD_CS2 Sbit at LATB5 bit GLCD RS sbit at LATFO bit GLCD RW sbit at LATFI1 bit GLCD EN sbit at LATF4 bit GLCD RST gt sbit at LATF5 bit var GLOD CS1_ Direction sbit at TRISB4 bit 610 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 GLCD_CS2 Direction sbit at TRISBS bit GLCD RS Direction sbit at TRISFO bit GLCD RW Direction sbit at TRISF1 bit GLCD EN Direction sbit at TRISF4 bit GLCD RST Direction sbit at TRISF5S bit End Gled module connections Touch Panel module connections var DriveA t 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 var write erase bit pen size 2 byte x coord y coord word write msg clear msg erase msg array 5 of char GLCD menu messages procedure Initialize begin ADPCFG OxFF3F set AN6 and AN7 channel pins as analog DriveA Direction 0 Set DriveA pin as output DriveB Direction
227. DPT location Parameters ptr buffer for storing bytes read from ENC28760 RAM addr ENC28760 RAM start address Valid values 0 8192 n number of bytes to be read Nothing Requires Ethernet module has to be initialized See SPI_Ethernet_Init var buffer array 16 of byte SPI Ethernet _getBytes buffer 0x100 16 read 16 bytes starting from address 0x100 SPI_Ethernet_UserTCP Prototype function SPI Ethernet UserTCP var remoteHost array 4 of byte remotePort localPort reqhLength 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 clients TCP port localPort port to which the request is sent regLength 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 re
228. Debug Windows 132 Debug Windows 132 Breakpoints Window 132 Watch Values Window 132 RAM Window 134 Stopwatch Window 134 EEPROM Watch Window 135 Code Watch Window 136 Software Simulator Debugger Options 137 Debugger Options 137 CHAPTER 6 138 mikroPascal PRO for dsPIC30 33 and PIC24 Specifics 138 GOTO Table 139 Predefined Globals and Constants 140 Predefined project level defines 140 Accessing Individual Bits 141 sbit type 142 at keyword 143 bit type 143 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Interrupts 144 Function Calls from Interrupt 144 Interrupt Handling 144 Interrupt Example 145 Linker Directives 146 Directive absolute 146 Directive org 146 Directive orgall 147 Built in Routines 148 Lo 149 Hi 149 Higher 150 Highest 150 LoWord 151 HiWord 151 Inc 152 Dec 152 Chr 152 Ord 153 SetBit 153 ClearBit 153 TestBit 154 Delay_us 154 Delay_ms 154 Vdelay_ms 155 VDelay_advanced_ms 155 Delay_Cyc 156 Delay_Cyc_Long 156 Clock_kHz 156 Clock_MHz 157 Get_Fosc_kHz 157 Get_Fosc_Per_Cyc 157 Reset 158 ClrWdt 158 DisableContextSaving 158 SetFuncCall 159 SetOrg 159 GetDateTime 160 DoGetVersion 160 Code Optimization 161 Constant folding 161 Constant propagation 161 Copy propagation 161 Value numbering 161 Dead code ellimination 161 Stack allocation 161 MikroElektronika 6 mikroPascal PRO for dsPIC30 33 and PIC24 Local vars optimization Better code generation and local optimization 16
229. 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 Nothing Requires The corresponding MCU ports must be appropriately initialized for CF card See Cf_Init disable compact flash None Cf Disable 281 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 Gf Read Tnzt 990 1 Cf_Read_Byte pointers These pointers will be autoicremented upon reading Returns Retums a byte read from Compact Flash sectorbufen SCSCSC C S SCS Requires The corresponding MCU ports must be appropriately initialized for CF c
230. 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 606 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 TP_Init Prototype procedure TP Init display 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 ADC Tait Initalize ADC module TP Tnce 128 A Initialize touch panel dimensions 128x64 TP_Set_ADC_Threshold Set custom ADC threshold value call this function after TP_Init threshold custom ADC threshold value TP_Init has to be called before using this routine TP Set _ADC_ Threshold 3900 Set touch panel ADC threshold ote p MikroElektronika 607 mikroPascal PRO for dsPICSO 33 and PIC24 TP_Press_Detect Detects if the touch panel has been pressed if touch panel is pressed 0 otherwise Requires Global variables DriveA DriveA DriveB DriveB DriveA Direction Direction of DriveA pi
231. ED 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 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
232. EEPROM Write Block address longint var dat array 100 of word Writes one EEPROM row 16 words block of data Parameters address starting address of the EEPROM memory block to be written data data block to be written Requires It is the user s responsibility to maintain proper address alignment In this case address has to be a multiply of 32 which is the size in bytes of one row of MCU s EEPROM memory Specified memory block will be erased before writing starts This routine is not applicable to the 24FO04KA201 and 24F16KA102 family of MCUs due to the architecture specifics var wrAddr longint data string 16 wrAddr Ox7FFC20 data mikroElektronika EEPROM Write Block wrAddr data Library Example This project demonstrates usage of EEPROM library functions for dsPIC30F4013 Each EEPROM 16 bit location can be written to individually or in 16 word blocks which is somewhat faster than the former If Writing in blocks EEPROM data start address must be a multiply of 16 Please read Help for more details on the library functions Copy Code To Clipboard program Eeprom var eeData i word eeAddr dword dArr array 16 of word 319 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 begin ADPCFG OxFFFF Disable analog inputs TRISB 0 PORTB as output LATB OxFFFF eeAddr 0x7FFC00 Start addre
233. ER CAN RX FILTER _CAN RX DBL BUFF buffered CAN CAN RX INVA RX OVERFLO CAN _ RX _ XTD FRA CAN RX _RTR_FRA BITS gir U amp WN e W LIDI H a SG T R word word word word word word word word word word word word 0x07 Use 0x00 0x01 0x02 0x03 0x04 0205 0x08 Set 0x10 Set 0x20 Set 0x40 Set this to access filter bits if Overflowed else cleared if invalid else cleared if XTD message else cleared if RTR message else cleared 0x80 Set if this message was hardware double You may use bitwise and to adjust the appropriate flags For example Copy Code To Clipboard if MsgFlag and _CAN RX OV begin ERF LOW lt gt 0 then Receiver overflow has occurred We have lost our previous message end CAN_MASK Constants CAN MASK constants define mask codes Function CANxSetMask expects one of these as its argument Copy Code To Clipboard const _CAN_MASK B1 CAN _ MASK B2 word word MikroElektronika 296 mikroPascal PRO for dsPICSO 33 and PIC24 CAN_FILTER Constants CAN FILTER constants define filter codes Function CANxSetFilter expects one of these as its argument Copy Code To Clipboard const CAN FILTER Bl Fl CAN FILTER Bl F2 CAN FILTER B2 F1 CAN FILTER B2 F CAN FILTER B2 F CAN FILTER B2 F4 Library Example
234. ERFLOW begin Receiver overflow has occurred We have lost our previous message end CANSPI_MASK Constants 07 Use S00 01 02 S037 04 S05 08 Set 10 Set 20 Set 40 Set 80 Set lt gt 0 then this to access filter bits if Overflowed else cleared if invalid else cleared if XTD message else cleared if RTR message else cleared if this message was hardware double For example The CANSPI_ MASK constants define mask codes Function CANSP SetMask expects one of these as it s argument Copy Code To Clipboard const _CANSPI_ MASK Bl _CANSPI_MASK B2 CANSPI_FILTER Constants byte byte The CANSPI FILTER constants define filter codes Functions CANSPI SetFilter expects one of these as it s argument Copy Code To Clipboard const CANSPI FILT Bl F1 z po CANSPI FILTER BL F2 CANSPI FILT ti zo B2 F1 zj CANSPI FILTER B2 F2 CANSPI_ FILT B2 F3 zj ve _CANSPI_FILTER B2 F4 byte byte byte byte byte byte ob WN MikroElektronika 212 mikroPascal PRO for dsPIC30 33 and PIC24 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 th
235. Ethernet_24j600_getBytes SPI_Ethernet_24j600_UserTCP SPI_Ethernet_24j600_UserUDP SPI_Ethernet_24j600_setUserHandlers 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 501 mikroPascal PRO for dsPICSO 33 and PIC24 SPI_Ethernet_24j600_Init Prototype Description Parameters procedure SPI Ethernet 24 600 Init mac byte ip byte fullDuplex configuration This is MAC module routine It initializes ENC247600 controller This function is internally splited into 2 parts to help linker when coming short of memory ENC24J600 controller settings parameters not mentioned here are set to default receive buffer start address 0x0000 receive buffer end address 0x19AD transmit buffer start address 0x19AE transmit buffer end address Ox1 FFF 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
236. Expander Write PortA 0 counter Inc counter Initialize SPI module used with PortExpander Initialize Port Expander Set Expander s PORTA to be output Set Expander s PORTB to be input Set pull ups to all of the Expander s PORTB Endless loop Write i to expander s PORTA PORTB Expander Read PortB 0 Read expander s PORTB and write it to LEDs Delay ms 100 end end MikroElektronika 425 mikroPascal PRO for dsPIC30 33 and PIC24 HW Connection OSCILLATOR LOYOIdSP vec PORTB vee PORTA Port Expander HW connection 426 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 PS 2 Library The mikroPascal PRO for dsPIC30 33 and PIC24 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 Descriotion in all projects using PS 2 Library P external PS2 Clock bit fr n g i piia ee ici S PS 2 Clock line var PS2 Clock sbi
237. F9B8 TwiddleCoeff_256 const TwiddleCoeff 256 array 256 of word Ox7FFF O0x0000 Ox7FF6 OxFCDC Ox7FD9 OxF9B8 Ox7FA7 OxF695 Ox7F62 OxF374 Ox7FOA OxF055 O0x7E9D OxED38 Ox7E1E OxEA1E Ox7D8A OxE707 Ox7CE4 OxE3F4 0x7C2A OxEOE6 0Ox7B5D OxDDDC Ox7A7D OxDAD8 0x798A OxD7D9 0x7885 OxD4E1 027760 OxDI1EF Ox 642 OxCr04 Ox7505 OxCe21 Ox 73B6 0xC946 Ox7 255 OxC673 Ox70E3 OxC3A9 Ox6F5F OxCOE9 Ox6DCA OxBE32 0x6C24 OxBB85 Ox6A6E OxB8E3 O0x68A7 OxB64C 0x66D0 0xB3C0 0x64E9 0xB140 Ox62F2 OxAECC Ox60EC OxAC65 Ox5ED7 OxAAOA Ox5CB4 OxA7BD Ox5A82 OxAS7E 0x5843 OxA34C 0Ox55F6 0xA129 0x539B Ox9F14 0x5134 Ox9DOE Ox4ECO 0x9B17 0x4C40 0x9930 Ox49B4 0x9759 Ox471D 0x9592 0x447B 0x93DC Ox41CE 0x9236 Ox3F17 Ox90Al1 0Ox3C57 Ox8F1D 0x398D Ox8DAB Ox36BA Ox8C4A Ox33DF Ox8AFB Ox30FC Ox89BE 0x2E11 0x8894 Ox2B1F 0x877B 0x2827 0x8676 022528 0x8583 O0x2224 Ox84A3 Ox FIA Ox8306 OxlCOC Ox83ic mikroPascal PRO for dsPIC30 33 and PIC24 Ox18F9 Ox0C8C 0x0000 OxF374 OxE707 OxDAD8 OxCFO04 OxC3A9 OxB8E3 OxAECC OxA5S7E Ox9DOE 0x9592 Ox8F1D 0x89BE 0295893 0x8276 0x809E 0x8276 0x809E 0x8000 Ox809E Ox8276 0x8583 Ox89BE Ox8FLD 0x9592 Ox9DOE OxA5S7E OxAECC OxB8E3 OxC3A9 OxCFO04 OxDAD8 OxE70T7 OxF374 TwiddleCoeff_512 const TwiddleCoeff 512 array 512 of word Ox7FEF Ox7FD9
238. FILTER word val longint CAN CONFIG FLAGS word Description Function sets message filter Given value is bit adjusted to appropriate buffer mask registers Parameters CAN FILTER CAN module filter number Valid values CAN _ FILTER constants See CAN_FILTER constants val filter register value This value is bit adjusted to appropriate filter registers CAN CONFIG FLAGS selects type of message to filter Valid values CAN CONFIG STD MSG and CAN CONFIG XTD MSG See CAN_CONFIG_FLAGS constants Requires MCU with the CAN module MCU must be connected to the CAN transceiver MCP2551 or similar which is connected to the CAN bus CAN must be in Config mode otherwise the function will be ignored See CANxSetOperationMode set appropriate filter value and message type CAN1SetOperationMode _CAN MODE CONFIG OxFF set CONFIGURATION mode CAN1 module must be in config mode for filter settings Set id of filter B1 F1 to 3 CAN1SetFilter CAN FILTER Bl F1 3 CAN CONFIG XTD MSG CAN library routine require you to specify the module you want to use To use the desired CAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of CAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 251 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 CANxRead Prototype functio
239. Fie Edit view Project Debugger Programmer Tools Configure Window Help ot x mS SASAE 2 vu PRePHRO R e HweP iu mikroBasic PRO for dsPIC30 33 and PICZ4 http wow mikroe com en compilers mikrobasic dspic NOTES Close pots RF3 TX and RFZ RX at J9 and J8 respectively board specific tos program UARTL dim uart_rd as byte B main ADPCFG OxFFFF Configure AN pins as digital UART1_Init 9600 Initialize UART module at 9600 bps Delay_ms 100 Wait for UART module to stabilize ULMODE ALTIO 1 cun comment this line to have Rx and Tx pins on their alternate locations This is used to free the pins for other module UART1_ Write Text Start UART1_Write 10 UART1_Write 13 while TRUE Endless loop if UART1_Data_Ready lt gt 0 then If data is received uart_rd UART1_Read read the received data UARTl_Write uart_rd and send data via UART end if dsPIC30F4013 oab sab IPO denovzc Related topics COFF File Using MPLAB Simulator Using MPLAB Simulator Note It is assumed that MPLAB is previously installed 1 First of all start mikroPascal PRO for dsPIC30 33 and PIC24 Help and open the desired project In this example UART project for EasydsPIC4A board and dsPIC30F4013 will be opened 2 Open Tools gt Options gt Output settings and check the Generate COFF file option and click the OK button 3 After that compile the project by pressing Ctrl F9
240. G2 PROPSEG CAN CONFIG FLAGS word Description Initializes the CAN module The internal dsPIC30F CAN 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 is set to Normal Filter and mask registers IDs are set to zero Filter and mask message frame type is set according to CAN CONFIG FLAGS value SAM SEG2PHTS WAKFIL and DBEN bits are set according to CAN CONFIG FLAGS value 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 CAN CONFIG FLAGS is formed from predefined constants See CAN_CONFIG_FLAGS constants Requires MCU with the CAN module MCU must be connected to the CAN transceiver MCP2551 or similar which is connected to the CAN bus initialize the CAN1 module with appropriate baud rate and message acceptance flags along with the sampling rules var can config flags word can _ config flags _CAN_ CONFIG SAMPLE THRICE amp Form value to be used CAN CONFIG PHSEG2 PRG ON amp with CAN1Initialize CAN CONFIG STD MSG amp CAN CONFIG DBL BUFFER ON amp CAN CONFIG MATCH MSG TYPE amp CAN CONFIG LINE FILTER
241. GrLayer 328 1D13700_Display_TxtLayer 329 1D13700_Set_Cursor 329 1D13700_Display_Cursor 330 1D13700_Write_Char 330 1D13700_Write_Text 331 1D13700_Dot 331 1D13700_Line 332 1D13700_H_Line 332 1D13700_V_Line 333 1D13700_Rectangle 333 1D13700_Box 334 1D13700_Rectangle_Round_Edges 334 1D13700_Rectangle_Round_Edges Fill 335 1D13700_ Circle 335 1D13700_Circle_Fill 336 1D13700_Image 336 1D13700_Partiallmage 337 Flash Memory Library 338 13 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 dsPIC30 338 PIC24 and dsPIC33 338 24F04KA201 and 24F16KA102 Family Specifics 339 Library Routines 339 dsPIC30 Functions 339 PIC24 and dsPIC33 Functions 339 dsPIC30 Functions 340 FLASH_Erase32 340 FLASH_Write_Block 340 FLASH_Write_Compact 341 FLASH_Write_Init 341 FLASH_Write_Loadlatch4 342 FLASH_Write_Loadlatch4_Compact 343 FLASH_Write_DoWrite 344 FLASH_Read4 344 FLASH_Read4_Compact 345 PIC24 and dsPIC33 Functions 345 FLASH_Erase 345 FLASH_Write 346 FLASH_Write_Compact 346 FLASH_Read 347 FLASH_Read_Compact 347 Library Example 347 Graphic Lcd Library 349 External dependencies of Graphic Lcd Library 349 External dependencies of Graphic Lcd Library 350 Library Routines 351 Glcd_Init 351 Glcd_Set_Side 353 Glcd_Set_X 353 Glcd_Set_Page 353 Glcd_Read_Data 354 Glcd_Write_Data 354 Glcd_Fill 355 Glcd_Dot 355 Glcd_Line 355 Glcd_V_Line 356 Glcd_H_Line 356 Glcd_Rectangle 357 Glcd_Rectangle_Round_Edges 357 Glcd_Rec
242. IC24 The user can easily add its common typos by entering original typo for example bt 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 Y Enable Auto Complete Wi Key word dow Editor Colors do while ig Auto Correct z for no Auto Complete fors For statement A ftemplate Function header template function int func declaration es f if no ife if no beginfend else no begin end ifes lif else ifs if statement proc void func declaration ptemplate header comment For a project switch switch statement do while mikroPascal PRO for dsPICSO 33 and PIC24 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 a Auto Complete 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
243. IClick OnMouseOver Add Image To Project Add File To Project lt activeComment gt lt Attributes gt lt Url gt www mikroe com lt Url gt lt Image gt lt Image gt lt File gt lt File gt lt Attributes gt lt Events gt lt OnLeftClick gt lt OnLef ftClick gt lt OnRightClick gt lt OnRightClick gt lt OnDb1Click gt lt OnDb1Click gt lt OnMouseOver gt lt OnMouseOver gt lt Events gt lt activeComment gt 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 MikroElektronika 100 mikroPascal PRO for dsPIC30 33 and PIC24 Next file dialog will be opened Images My Recent Documents File name Easy_GSM_GPRS Com Files of type Image Files bmp ipa png C Open as read only My Network 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 Attributes Url ww mikroe com ile Events OnLeftClick Alt N OnRightClick OnDbIClick OnMouseOver Add Image To Pro
244. ITE SPI _T6963C_circle 120 64 110 SPI_T6963C_WHITE SPI_1T6963C_circle 120 64 130 SPI_T6963C_WHITE SPI_T6963C_sprite 76 4 einstein bmp 88 119 Draw a sprite SPI_T6963C_setGrPanel 1 Select other graphic panel SPI_T6963C_image mikroE_ 240x128 bmp Fill the graphic screen with a picture SENDIF while TRUE do Endless loop begin i Tf RB8 is pressed toggle the display between graphic panel 0 and graphic 1 ag if RB8 bit lt gt 0 then begin SPI_T6963C_graphics 1 SPI_T6963C_text 0 Delay ms 300 end mikroPascal PRO for dsPICSO 33 and PIC24 Tf RBI is pressed display only graphic panel Hip SIFDEF COMPLETE EXAMPLE else if RB9 bit lt gt 0 then begin Inc panel panel panel and 1 SPI_T6963C_displayGrPanel panel Delay ms 300 end SENDIF ial Tf RB10 is pressed display only text panel else if RB10 bit lt gt 0 then begin SPI_T6963C_graphics 0 SPI _T6963C_text 1 Delay ms 300 end Tf RB11 is pressed display text and graphic panels else if RB11 bit lt gt 0 then begin SPI T6963C_graphics 1 SPI TO963C text 1 7 Delay ms 300 end If RB12 is pressed change cursor f else if RB12 bit lt gt 0 then begin Inc curs if curs 3 then curs 0 case curs of OF no cursor SPI_T6963C_cursor 0 1 begin blinking cursor SPI Te6963C cursor 1 7 SPI T6963C cursor bli
245. If card is not present initialization may last longer depending on clock speed end end MikroElektronika 296 mikroPascal PRO for dsPIC30 33 and PIC24 HW Connection LODO DOO Oooo EE 8883 388 RDO OSCILLATOR vec dsPIC30F6014A OSC1 CLKI Vdd Fe 38 33 c4 RFa RD7 RD6 RDS RD4 ST RD3 a RD2 E L_ RD1 e ET ry 4 aa sa RDO H Ss m Compact Flash L red Card aa lt an s 10 RF6 29 RFS a e RF4 28 La f SSS IL RFO o i 10K C e vec Pin diagram of CF memory card 297 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 ECAN Library mikroPascal PRO for dsPIC30 33 and PIC24 provides a library driver for working with the dsPIC33FJ and pic24HJ ECAN module ECAN is a very robust protocol that has error detection and signalling self checking and fault confinement Faulty ECAN 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 ECAN supports
246. Init function channel number of PWM channel to change duty to Nothing Requires MCU must have the HW PWM Module PWM channel must be properly initialized See PWM_Init routine Set channel 1 duty ratio to 50 var pwm periodi word PWM Set _ Duty pwm periodi div 2 1 Notes Number of available PWM channels depends on MCU Refer to MCU datasheet for details 432 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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_Dulty 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 procedure PWM Stop disable channel x byte Rets Nong SOS MCU must have the HW PWM Module stop PWM at channel 1 PWM Stop 1 Notes Number of available PWM channels depends on MCU Refer to MCU datasheet for details 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 InitMai
247. MASK 2 ely ECAN CONFIG MATCH MSG TYPE and ECAN CONFIG XTD MSG set all mask3 bits to ones ECAN1SetFilter ECAN FILTER 10 ID 1st ECAN MASK 2 ECAN RX BUFFER 7 ECAN CONFIG XTD_MSG set id of filterl10 to 1st node ID assign buffer7 to filter10 ECAN1SetOperationMode _ECAN MODE NORMAL OxFF set NORMAL mode T while TRUE do begin MikroElektronika 316 mikroPascal PRO for dsPIC30 33 and PIC24 Msg Revd ECAN1Read Rx_ ID RxTx Data Rx Data_Len Can Rcv_ Flags receive message if Rx ID ID 1st and Msg Revd lt gt 0 lt gt 0 then if message received check id begin PORTB RxTx Data 0 id correct output data at PORTB Inc RxTx Data 0 increment received data ECAN1Write ID 2nd RxTx Data 1 Can Send Flags send incremented data back end end end HW Connection nnn DAN POC at CU P GAN That WOU il lt 2 cs pg Shielded 7 T twisigd palr Example of interfacing ECAN transceiver with MCU and bus EEPROM Library EEPROM data memory is available with a number of dsPIC30 family and some PIC24 family MCU s The mikroPascal PRO for dsPIC30 33 and PIC24 includes a library for comfortable work with MCU s internal EEPROM Important Only 24F04KA201 and 24F16KA102 of PIC24 family of MCUs have EEPROM memory Library Routines EEPROM_Erase EEPROM_Erase_Block EEPROM_Read EEPROM_Write EEPROM_Write_Block
248. Master_Example mppds Sources B R5485_Master_Example mpas Binaries Project Level Defines EEPROM File Active Comn E Output Files B Add Project E R5485 63 gt Other Files __ af a add File To Project GF Remove File From Project lt Build Ctrl F9 mE amp Close Project Ctrl K Programmer Fil 15 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Now navigate to the desired image file and simply add it E Project Manager 1 1 R5485_Master_Example mppds Brege eA ti 370 amp RS485_Master_Example mppds i eo Sources 3 RS485_Master_Example mpas B Binaries Project Level Defines Image Files bm fm R5 485 jpg gt EEPROM Files Active Comments Files S E Output Files E RS485_Master_Example hex E Other Files Next right click the added file and choose Set As Preview Image Project Manager 1 1 RS485_Master_Example mppds e je 82 Si ac se 70 Z B RS485_Master_Example mppds S Sources R5485_Master_Example mpas Binaries Project Level Defines Image Files i fh R5_485 jpg EEPROM Fies Bi Save Project Group Active Comments Fi Close Project Ctrl kK S gt Output Files add Project E R5485_Master_ EE komove Project gt Other Files Remove ror GY Add File To Project
249. Media Card Library OneWire Library Peripheral Pin Select Library Port Expander Library PS 2 Library PWM Library PWM Motor 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 ADC Library ADC Analog to Digital Converter module is available with a number of dsPIC30 33 and PIC24 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 MikroElektronika 240 mikroPascal PRO for dsPICSO 33 and PIC24 Library Routines ADCx_Init ADCx_Init_Advanced ADCx_Get_Sample ADCx_Read ADC_Set_Active ADCx_Init Prototype procedure ADCx_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 instruction cycle clock conversion clock 32 Tcy auto sample time 31TAD Requires MCU with built in ADC module ADC lib
250. Mme Fat Rewrite wes 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 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 Notes None OOS Mmc_Fat_Delete Rems Nothing SCSCS SCSCSCSCSCSCSCSCSCSCSCSSS 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 fil Mme Fat _Delete MikroElektronika 396 mikroPascal PRO for dsPIC30 33 and PIC24 Mmc_Fat_Write Prototype procedure Mmc Fat Write var fdata array 512 of byte data_len 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 Mmc_Fat_Write file_contents
251. Motor Control demonstration RS 485 Library RS 485 is a multipoint communication which allows multiple devices to be connected to a single bus mikroPascal PRO for dsPIC30 33 and PIC24 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 MikroElektronika 439 mikroPascal PRO for dsPIC30 33 and PIC24 Library Dependency Tree RS48
252. N 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 CANSP SetOperationMode 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 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 a 1 CANSPI_ CONFIG FLAGS 265 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 CANSPI SetMask Prototype procedure CANSPISetMask CANSPI MASK byte val longint CANSPI_CONFIG_ FLAGS byte D escription 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 CANSPI MASK constants See CANSPI_ MASK constants val mask register value This value is bi
253. NSPIWrite 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 at least one Transmit Buffer is available Requires The CANSPI module must be in mode in which transmission is possible See CANSP SetOperationMode 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 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
254. NxSetBaudRate Prototype procedure ECANxSetBaudRate SJW BRP PHSE EG2 PROPSE ECAN CONFIG FLAGS word Description Sets ECAN module baud rate Due to complexity of the ECAN protocol you can not simply force the bps value Instead use this function when ECAN is in Config mode Refer to datasheet for details SAM SEG2PHTS and WAKFIL bits are set according to the ECAN CONFIG FLAGS value Parameters sJw as defined in MCU s datasheet ECAN Module BRP as defined in MCU s datasheet ECAN Module PHSEG1 as defined in MCU s datasheet ECAN Module PHSEG2 as defined in MCU s datasheet ECAN Module PROPSEG as defined in MCU s datasheet ECAN Module ECAN CONFIG FLAGS ECAN module configuration flags Each bit corresponds to the appropriate CAN module parameter Should be formed out of predefined ECAN flag constants See ECAN_ CONFIG_FLAGS constants Requires The ECAN routines are supported only by MCUs with the ECAN module Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus The ECAN module must be in Config mode otherwise the function will be ignored See ECANxSetOperationMode set required baud rate and sampling rules var ecan config flags word ECAN1SetOperationMode _ECAN MODE CONFIG OxFF set CONFIGURATION mode ECANI1 module mast be in config mode for baud rate settings ecan_ config flags ECAN CONFIG SAMPLE THRICE and Form
255. O for dsPIC30 33 and PIC24 Mmc_Fat_Reset Se 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 Mc Pat R eset 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 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 The file must be opened for reading See Mmc_Fat_Reset var character byte Mme Fat Read character 395 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Mmc_Fat_Rewrite Rems Noting S 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
256. O for dsPIC30 33 and PIC24 Software SPI Library The mikroPascal PRO for dsPIC30 33 and PIC24 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 meee A 5 Description projects using Software SPI Library var SoftSpi_SDI sbit sfr external Data Inline var SoftSpi_ SDI sbit at RF2_ bit var SoftSpi_ SDO sbit sfr external Data Outline var SoftSpi_SDO sbit at LATF3 bit var SoftSpi_ CLK sbit sfr external Clock line var SoftSpi_ CLK sbit at LATF6 bit var SoftSpi_SDI_ Direction sbit sfr Direction of the var SoftSpi_SDI_ Direction sbit external Data In pin TRISE2 bit var SoftSpi_SDO Direction sb
257. OFF CANI Initialize 1 3 3 3 1 can_config flags initialize the CAN1 module CAN mode NORMAL will be set on exit CAN library routine require you to specify the module you want to use To use the desired CAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of CAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 248 mikroPascal PRO for dsPICSO 33 and PIC24 CANxSetBaudRate Prototype procedure CANxSetBaudRate SJW BRP PHSE EG2 PROPSEG CAN CONFIG FLAGS word Description Sets CAN baud rate Due to complexity of the CAN protocol you can not simply force a bps value Instead use this function when CAN is in Config mode Refer to datasheet for details SAM SEG2PHTS and WAKFIL bits are set according to CAN CONFIG FLAGS value Refer to datasheet for details Parameters SJUW 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 Returns CAN CONFIG FLAGS is formed from predefined constants See CAN_CONFIG_FLAGS constants Nothing Requires MCU with the CAN module MCU must be connected to the CAN transceiver MCP2551 or similar which is
258. OperationMode _CAN MODE NORMAL 0xFF set NORMAL mode CAN1 must be in mode in which transmission is possible X PRIORITY 0 and _CAN TX XTD FRAME and CAN TX NO RTR FRAME set message flags CANIWrite msg id data 1 tx flags CAN library routine require you to specify the module you want to use To use the desired CAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of CAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 253 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 CAN Constants There is a number of constants predefined in CAN library To be able to use the library effectively you need to be familiar with these You might want to check the example at the end of the chapter CAN_OP_MODE Constants CAN OP MODE constants define CAN operation mode Function CANxSetOperationMode expects one of these as its argument Copy Code To Clipboard const _CAN MODE BITS word E0 Use this to access opmode bits _CAN MODE NORMAL word 0x01 _CAN MODE SLEEP word 0x02 _CAN MODE LOOP word 0x03 _CAN MODE LISTEN word 0x04 _CAN MODE CONFIG word 0x07 CAN_CONFIG_FLAGS Constants CAN CONFIG FLAGS constants define flags related to CAN module configuration Functions CANxInitialize and CANxSetBaudRate expect one of these or a bitwise com
259. Ox1l0DD OxFCBO 0x0052 const SCALE B 2 const SCALE A 1 var inext word Input buffer index input array BUFFER SIZE of word ydata Input buffer output array BUFFER SIZE of word ydata Output buffer var CurrentValue word CurrentValue IIR _Radix SCALE B SCALE A word COEFF B b coefficients of the filter word COEFF A a coefficients of the filter FILTER ER 1 Filter order 1 word input Input buffer BUFFER SIZE Input buffer length word output Input buffer inext Current sample Input and output samples must be in Y data space MikroElektronika 637 mikroPascal PRO for dsPICSO 33 and PIC24 FFT Library mikroPascal PRO for dsPIC30 33 and PIC24 includes a library for FFT calculation All routines work with fractional Q15 format Library Dependency Tree FFT gt TwiddleFactors Library Routines FFT FFT Prototype procedure FFT log2N word TwiddleFactorsAddress longint var Samples array 1024 of word Description Function applies FFT transformation to input samples input samples must be in Y data space iar j 2 m k n Fikj E f n WN kn WN knj e n k 0 f n array of complex input samples WN TwiddleFactors N 2 M mez The amplitude of current FFT sample is calculated as F k Re k Im2 k Parameters log2N buffer length must be the power of 2 TwiddleFactorsAddress address of c
260. OxAO1C OxAB36 Ox9F14 OxAC65 Ox9EOF OxAD97 OxSDO0E OxAECC 0x9C11 0xB005 0x9B17 0xB140 0xSA22 OxB27F 0x9930 OxB3C0 0x9843 OxB505 0x9759 OxB64C 0x9674 0OxB796 0x9592 OxB8E3 0x94B5 0OxBA33 0x93DC OxBB85 0x9307 OxBCDA 0x9236 OxBE32 0x9169 OxBF8C Ox90A1 OxCOE9 Ox8FDD 0xC248 Ox8F1ID 020329 0x8Eh62 OxC5S0D OxSDAB OxCe73 Ox8CF8 OxC7DB Ox8C4A O0xC946 0x8BA0 OxCAB2 Ox8AFB OxCC21 Ox8A5A OxCD92 Ox89BE OxCF04 0x8927 OxD0O79 0x8894 OxDIEF 0x8805 OxD367 0Ox877B OxD4E1 Ox86F6 OxD65C 0x8676 OxD7D9 Ox85FA 0xD958 0x8583 OxDAD8 0x8511 OxDC59 0x84A3 OxDDDC O0Ox843A OxDF61 0x83D6 OxEOE6 0x8377 OxE26D 0x831C OxE3F4 0x82C6 OxE57D 0x8276 OxE707 0x822A OxE892 0x81E2 OxEA1E O0x81A0 OxEBAB 0x8163 OxED38 0x812A OxEEC6 Ox80F6 OxF055 0x80C8 OxF1E4 Ox809R OxP374 O0x8079 OxF505 023059 OxFC95 Oxe03E OxF827 0x8027 OxF9B8 0x8016 OxFB4A Ox800A OxFCDC 0x8002 OxFE6E MikroElektronika 641 mikroPascal PRO for dsPICSO 33 and PIC24 Bit Reverse Complex Library mikroPascal PRO for dsPIC30 33 and PIC24 includes a Bit Reverse Complex Library for DSP engine All routines work with fractional Q15 format Library Routines BitReverseComplex BitReverseComplex Prototype procedure BitReverseComplex log2N word var ReIm array 1024 of word Description This function does Complex in place Bit Reverse re organization Parameters N buffer length must
261. PI 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 O const SPI Ethernet FULLDUPLEX ie 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 OxA5 myMacAddr 3 0x76 myMacAddr 4 0x19 myMacAddr 5 Ox3SE myIpAddr 0 192 myIpAddr 1 168 myIpAddr 2 1 myIpAddr 3 60 SPIL Inie SPI Ethernet Init myMacAddr myIpAddr SPI_Ethernet_FULLDUPLEX MikroElektronika 47 mikroPascal PRO for dsPICSO 33 and PIC24 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
262. PIC24 USART communication terminal launch it from the drop down menu Tools USART Terminal or simply click the USART Terminal Icon m Copy Code To Clipboard program Soft_UART If error was not detected var error byte counter byte read byte 7 begin ADPCFG OxFFFF TRISB 0x00 signalization PORTB 0 as error Soft UART Init PORTF 2 3 14400 if error gt 0 then begin PORTB error if while TRUE do nop oi end Delay ms 100 for counter z downto A do if begin Soft UART Write counter Delay ms 100 end while TRUE do i begin byte read Soft_UART Read error if error lt gt 0 then PORTB error ff else Soft UART Write byte read Ey end end Auxiliary variables Configure AN pins as digital I O Set PORTB as output error No error 0 Initialize Soft UART at 14400 bps Signalize Init error Stop program Send bytes from z downto A Endless loop Read byte then test error flag If error was detected Signal it on PORTB return byte read 462 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Sound Library The mikroPascal PRO for dsPIC30 33 and PIC24 provides a Sound Library to supply 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
263. PI_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 ENC28 760 write pointer EWRPT location Parameters ptr const string to be written into ENC28760 RAM Number of bytes written into ENC28760 RAM Ethernet module has to be initialized See SP _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 Returns Byte read from ENC28760 RAM Ethernet module has to be initialized See SP _Ethernet_Init var buffer byte Ethernet _getByte read a byte from ENC28J60 buffer 482 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 ENC28760 RAM starting from given address If value of 0xFFFF is passed as the address parameter the reading will start from current ENC28J60 read pointer ER
264. PI_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 456 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 program Soft SPI DAC module connections var Chip Select sbit at LATFO bit SoftSpi CLK sbit at LATF6 bit SoftSpi SDI sbit at RF2 bit SoftSpi SDO sbit at LATF3 bit var Chip Select Direction f sbit at TRISFO bit SoftSpi CLK Direction sbit at TRISF6 bit SoftSpi SDI Direction sbit at TRISF2 bit SoftSpi SDO Direction Sbit at TRISF3 bit End DAC module connections var value word procedure InitMain begin TRISBO bit 1 Set RBO pin as input TRISBI bit 1 Set RB1 pin as input Chip Select 1 Deselect DAC Chip Select Direction 0
265. PRO for dsPIC30 33 and PIC24 T6963C_circle_fill Prototype procedure T6963C Circle fill x integer r longint pcolor word Draws a filled circle on Glcd Parameters x x coordinate of the circle center y y coordinate of the circle center ri radius size pcolor 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 dsPIC30 33 and PIC24 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 gt Gled Bitmap Editor to convert image to a constant array suitable for displaying on Glcd MikroElektronika 977 mikroPascal PRO for dsPICSO 33 and PIC24 T6963C_Partiallmage Prototype procedure T6963C PartialImage 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 l
266. Pascal PRO for dsPIC30 33 and PIC24 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 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 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 BZ 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 160 442 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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
267. Pascal PRO for dsPIC30 33 and PIC24 T6963C_rectangle Prototype procedure 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 yl y coordinate of the lower right rectangle corner pcolor color parameter Valid values T6963C_BLACK and T6963C_WHITE Toshiba Glcd module needs to be initialized See the T6963C_init routine Coral T6963C_rectangle 20 20 219 107 T6963C WHITE cies Ne T6963C_rectangle_round_edges Prototype procedure T6963C rectangle round edges x0 y0 xl yl radius integer pcolor byte Draws a 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 yl y coordinate of the lower right rectangle corner round radius radius of the rounded edge pee 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 20 20 219 107 12 T6963C WHITE MikroElektronika 019 mikroPascal PRO for dsPICSO 33 and PIC24 T6963C_rectangle_round_edges fill Prototype procedure T6963C rectangle round edges fill x0 y0 x1 yl ra
268. Pascal PRO for dsPICSO 33 and PIC24 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 declarations 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
269. Port Expander Library external dependencies MikroElektronika 545 mikroPascal PRO for dsPICSO 33 and PIC24 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_panel Fill SPI_T6963C_grFill SPI_T6963C_txtFill SPI_T6963C_cursor_height SPI_T6963C_graphics SPI_T6963C_text SPI_T6963C_cursor SPI_T6963C_cursor_blink 546 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_T6963C_config Prototype Description Parameters procedure SPI T6963C_config width height fntW word DeviceAddress byte wr rd cd rst 2 byte 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
270. RO for dsPIC30 33 and PIC24 begin ADPCFG OxFFFD PORTB 0 TRISB Oxff ET set PORTB as PORTD 0 TRISD 0 set PORTD as ADC1_ Init httpCounter 0 set mac address 0x00 z 0x14 OxA5 0x76 0x19 Ox3F myMacAddr 0 myMacAddr 1 myMacAddr 2 myMacAddr 3 myMacAddr 4 myMacAddr 5 set IP address myIpAddr 0 myIpAddr 1 myIpAddr 2 myIpAddr 3 set gateway gwIpAddr 0 gwIpAddr 1 gwIpAddr 2 gwIpAddr 3 1923 168 set dns address 192 168 20 z 1 dnsIpAddr 0 dnsIpAddr 1 dnsIpAddr 2 dnsIpAddr 3 set subnet ipMask 0 ipMask 1 ipMask 2 ipMask 3 e e SOF e mask z 205 z 2557 c 255 0 starts ENC28J60 with reset bit on PORTC BO CS DLE on PORTC B1 my MAC amp IP address full duplex all digital but rb10 AN10 input for buttons and adc output MikroElektronika 497 mikroPascal PRO for dsPIC30 33 and PIC24 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 LOW SPI IDLE 2 ACTIVE SPI Ethernet Init myMacAddr myIpAddr _SPI_ Ethernet _FULLDUPLEX init ethernet module SPI Ethernet _setUserHandlers SPI Ethernet UserTCP SPI_ Ethernet _UserUDP set user handlers dhcp will not be used here so use preconfigured addr
271. RO for dsPICSO 33 and PIC24 Dec2Bcd function Dec2Bcd decnum sede byte TRetuns _ GoweredB0Dvawe Nothing var a b byte 22 Dec2Bcd a b equals 34 Bcd2Dec16 function Bcd2Dec16 bcdnum word word ne E var a D word 0x1234 a equals 4660 Bcd2Decl6 a b equals 1234 Dec2Bcd16 ee function Dec2Bcd16 decnum word word COO se var a b word ZIA5 Dec2Bcedl6 a b equals 9029 670 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 invocation 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 set jmp If there has been no such invocation or the function containing the invocation of setjmp has terminated in the
272. Requires CF card and CF library must be initialized for file operations See Cf_Fat_lInit File must be previously assigned See Cf_Fat_Assign var size dword cE Fat_Reset size Cf_Fat_Read Prototype procedure Cf Fat Read var bdata byte Description Reads a byte from currently assigned file opened for ue 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 CE Fat_Read bdata MikroElektronika 286 mikroPascal PRO for dsPICSO 33 and PIC24 Cf_Fat_Rewrite Requires CF card and CF library must be initialized for file operations See Cf_Fat_lInit The file must be previously assigned See Cf_Fat_Assign open file for writing Cf Fat _Rewrite None Cf_Fat_Append Prototype procedure Cf Fat Append Description Opens 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 writing operation will start from there Nothing Requires CF card and CF library must be initialized for file operations See Cf_Fat_lInit File must be previo
273. S Direction Sbit at TRISF1 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 7 begin txtl EINSTEIN WOULD HAVE LIKED mE txt GLCD LIBRARY DEMO WELCOME SDEFINE COMPLETE EXAMPLE comment this line to make simpler smaller example ADPCFG OxFFFF initialize AN pins as digital TRISB8 bit 1 Set RB8 as input TRISBO bit E Set RB9 as input MikroElektronika 561 mikroPascal PRO for dsPIC30 33 and PIC24 TRISB10 bit 1 Set RB10 as input TRISB11 bit 1 Set RB11 as input TRISB12 bit 1 Set RB12 as input init display for 240 pixel width and 128 pixel height 8 bits character width data bus on MCP23S17 portB control bus on MCP23S17 portA bit 2 is WR bit 1 is RD Dat 0 is CD bit 4 1s RST chip enable reverse on 8x8 font internaly set in library If Port Expander Library uses SPI1 module SPI1 Init Initialize SPI module used with PortExpander init display for 240 pixel width and 128 pixel height 8 bits character width data bus on MCP23S17 portB control bus on MCP23S17 portA bit 2 is WR pic ws IRD bit 0 is NCD bit 4 is RST chip enable reverse on 8x8 font internaly set in
274. SO 33 and PIC24 begin x center i 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 dsPIC30 33 and PIC24 treats comments beginning with a s immediately following an opening brace as a compiler directive for example SELSE 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 Directives DEFINE and UNDEFINE Use directive DEF INE to define a conditional 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 UNDEFINE to undefine clear previously defined flag Note Pascal does not support macros directives SDEFINE and SUNDEF INE do not create destroy macros They only provide flags for directive SI FDEF to check against Dir
275. SPI_ MODE CONFIG OxFF set CONFIGURATION mode CANSPISetMask CANSPI MASK Bl1 1 CANSPI CONFIG XTD MSG set all maski bits to ones CANSPISetMask _CANSPI MASK B2 1 CANSPI CONFIG XTD MSG set all mask2 bits to ones 213 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 Revd CANSPIRead Rx_ID RxTx Data Rx Data_Len Can Rcv Flags receive message if Rx_ID ID 2nd and Msg Revd 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 CANSPIWrite 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 Ist gt longint 12111 const ID 2nd longint 3 var Can Init Flags Can Send Flags Can Rev Flags word can flags Rx Data_Len word received data length in bytes RxTx Data array 8 of byte can rx tx data buffer Msg Revd byte reception flag Tx ID Rx_ID dword can rx and
276. See SPI_T6963C_Config routine clear current panel SPI_T6963C_panelFill 0 558 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_T6963C_grFill Rems nom OOOO S Toshiba Glcd module needs to be initialized See SPI_T6963C_Config routine clear current graphic panel SPI T6963C_grFill 0 Notes fno OSS SPI_T6963C_txtFill Rems Noting OOOO S Pompe e E U SPI_T6963C_txtFill 0 moes None OOOO SPI_T6963C_cursor_height Prototype procedure SPI T6963C cursor height n byte Parameters n cursor height Valid values 0 7 Toshiba Gled module needs to be initialized See SPI_T6963C_Config routine Example ser roose cursor pein OO O OOOO OSS moes fn O MikroElektronika 559 mikroPascal PRO for dsPIC30 33 and PIC24 SPI_T6963C_ graphics Prototype procedure SPI T6963C_graphics n word Description Enable disable graphic displaying Parameters n graphic enable disable parameter Valid values 0 disable graphic dispaying and 1 enable graphic displaying Nothing Requires Toshiba Glcd module needs to be initialized See SPI_T6963C_Config routine enable graphic displaying SPI T6963C graphics 1 None 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 Gicd
277. Size ofthe curenty assigned fie in byes SSS 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 i 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 this 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 Also in order to keep backward compatibility
278. T6963C T6963C ctrifs Direction 0 T6963C_ ctrlfs 0 Font Select 8x8 T6963C ctrimd Direction 0 T6963C_ctrimd i 0 Column number select panel 0 L p 03 curs 0 cposx 0 cposy 0 Initialize T6369C T6963C tpit 240 128 8 Enable both graphics and text display at the same time a T6963C_ graphics 1 T6963C text 1 Text messages ey T6963C write text txt 0 0 T6963C_ROM MODE XOR T6963C_write text txtl 0 15 T6963C_ROM MODE XOR Cursor T6963C_cursor height 8 8 pixel height T6963C_set_cursor 0 0 Move cursor to top left T6963C_cursor 0 Cursor off 084 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Draw rectangles T6963C_ rectangle 0 0 239 127 T6963C WHITE T6963C rectangie Z20 20 219 107 T6963C WHITE T6963C_rectangle 40 40 199 87 T6963C_WHITE T6963C rectangle 60 60 179 67 T 963C WHETE 7 Draw a Cross T6963C line 0 0 239 127 T6963C_ WHITE 7 T6963C_ Tine 0 127 239 0 T6963C WHITE i Draw solid boxes T6963C box 0 0 239 8 T6963C_ WHITE T6963C_box 0 119 239 127 T6963C_WHITE SIFDEF COMPLETE EXAMPLE oe Draw circles ay T6963C_circle 120 64 10 T6963C_WHITE T6963C cirele 120 64 30 T6963C WHITE T6963C_circle 120 64 50 T6963C_WHITE T6963C_circle 120 64 70 T6963C_WHITE T6963C_ cirele i20 64 90 T696
279. T6963C_240x128 Ist Other Files B DataSheet_7013eb pdF 696 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 The list of relevant files is stored in the project file extension mppds To add a file to the project click the Add File to Project Icon a or 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 FE or press Delete button on your keyboard Note For inclusion of the module files use the include clause See File Inclusion for more information Project Level Defines Project Level Defines p14 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 DEBUG TEST 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 pid 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 file pld file by right clicking the Project Level Defines node In the source code write the following IFDEF PLD TEST ENDIF There are number of predefined project level defines See predefined pro
280. TFT_Write_Char 596 TFT_Write_Text 596 TFT_Fill_ Screen 597 TFT_Dot 598 TFT_Set_Pen 599 TFT_Set_Brush 600 TFT_Line 602 TFT_H_Line 603 TFT_V_Line 603 TFT_Rectangle 603 TFT_Rectangle_Round_Edges 604 TFT_Circle 604 TFT_Image 604 TFT_Partial_Image 605 TFT_Image_Jpeg 605 TFT_RGBToColor16bit 606 TFT_Color16bittoRGB 606 HW Connection 607 Touch Panel Library 608 Library Dependency Tree 608 External dependencies of Touch Panel Library 608 Library Routines 608 TP_Init 609 TP_Set_ADC_ Threshold 609 TP_Press_ Detect 610 TP_Get_Coordinates 610 TP_Calibrate_Bottom_Left 611 TP_Calibrate Upper Right 611 TP_Get_Calibration_Consts 611 23 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 TP_Set_Calibration_Consts 612 Library Example 612 Touch Panel TFT Library 616 Library Dependency Tree 616 External dependencies of Touch Panel TFT Library 616 Library Routines 616 TP_TFT_Init 617 TP_TFT_Set_ADC_Threshold 617 TP_TFT_Press_Detect 618 TP_TFT_Get_Coordinates 619 TP_TFT_Calibrate_Min 619 TP_TFT_Calibrate_Max 619 TP_TFT_Get_Calibration_Consts 620 TP_TFT_Set_Calibration_Consts 620 HW Connection 621 UART Library 622 Library Routines 622 UARTx_Init 623 UARTx_Init_Advanced 624 UARTx_Data_Ready 625 UARTx_Tx_lIdle 626 UARTx_Read 626 UARTx_Read_ Text 627 UARTx_Write 628 UARTx_Write_Text 628 UART_Set_Active 629 Library Example 630 HW Connection 631 USB Library 632 USB HID Class 632 Library Routines 632 HID_Enable 633 HID_Read
281. UART library implements time based activities so interrupts need to be disabled when using it MikroElektronika 459 mikroPascal PRO for dsPIC30 33 and PIC24 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_lInit 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 Requires Software UART must be initialized before using this function See the Soft_UART_lInit routine Be aware that during 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 0A Write a byte via Soft UART Soft_UART Write some byte The Software UART library impl
282. UART1 Init 9600 delim OK while TRUE do begin if UART1 Data Ready 1 then begin UART1 Read Text txt delim 10 VARTI Write Text txt end end 626 ee oo 2020t i SOSOSOSCSOSCSCSS arte tO mikoPascal PRO for dsPIC30 33 and PIC24 UART_Set_Active Prototype procedure UART Set Active read ptr TUART Rd Ptr write ptr TUART Nr Ptr ready ptr 2 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 UART1 Read UART1 Write UART1 Data Ready UART1 Tx_ Idle set UART1 active RS485Master Send dat 1 160 send message through UART1 UART_ Set Active UART2 Read UART2 Write UART2 Data_Ready UART2 Tx_ Idle set UART2 active RS485Master Send dat 1 160 send through UART2 mikroPascal PRO for dsPIC30 33 and PIC24 Library Example This example
283. UT function while SCK1CM is set only for P24FJ256GA110 Family 255 if peripheral pin mapping was successful PPS Mapping 15 _INPUT _RX2_DT2 Sets pin 15 to be Input and maps RX2 DT2 Input to it PPS Mapping 5 _OUTPUT _TX2 CK2 Sets pin 5 to be Output and maps EUSART2 Asynchronous Transmit Synchronous Clock Output to it Direction Parameters Sets selected pin as input Sets selected pin as output Input Functions 3 MikroElektronika 413 mikroPascal PRO for dsPICSO 33 and PIC24 es Output Functions The NULL function is assigned to all RPn outputs at device Reset and disables the RPn output function Por ouiput Compares i pwomes O 414 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 _SS30UT _SYNCT1 _SYNCI2 _SYNCO _ULRTS _U2RTS _U3RTS _U4RTS _U1TX Worx _U3TX _U4TX _UPDN _UPDN1 _UPDN2 QEI direction UPDN status MikroElektronika M mikroPascal PRO for dsPICSO 33 and PIC24 Port Expander Library mikroPascal PRO for dsP IC30 33 and PIC24 provides a library for communication with the Microchip s Port Expander MCP23S17 via SPI interface Connections of the dsP IC30 33 and PIC24 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 Librar
284. User must initialize appropriate SPI module before using the CANSPI 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 sri 261 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 External dependencies of CANSPI Library The following variables must be defined Description in all projects using CANSPI Library P g external var cCanSpi Rst sbit sfx 3 var CanSpi Rst sbit at LATF1 Reset line A external bit var CanSpi CS Direction sbit Direction of the Chip Select var CanSpi_ CS Direction sbit at sfr external pin TRISFO_bit var CanSpi_ Rst Direction sbit Direction of the Reset pin var CanSpi_ Rst_Direction sbit at sfr external pin TRISFI bit Library Routines CANSPISetOperationMode CANSPIGetOperationMode CANSPIInit CANSP SetBaudRate CANSPISetMask CANSPISetFilter CANSPI Read CANSPI Write CANSP ISetOperationMode 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
285. 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 B Edit Value PORTB 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 131 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 RAM Window The RAM Window is available from the drop down menu View gt Debug Windows gt 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 Led4bit mikroE ikroElektronike EasydsPIC4 lt Stopwatch Window The Software Simulator Stopwatch Window is available from the drop down menu View gt Debug Windows gt 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 o
286. When set CRC check will be disabled and ead packets with invalid CRC field will be accepted Pe exes 7 0x80 MAC Unicast traffic receive filter flag When set MAC unicast sek Sthernee DICAS traffic will be disabled ae Nothing Ethernet module has to be initialized See SP _Ethernet_Init SPI Ethernet Disable _ SPI Ethernet CRC or_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 479 mikroPascal PRO for dsPICSO 33 and PIC24 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 packe
287. 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 ss 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 integer number to be converted output destination string var input integer txt array 6 of char EERTE begin input 4220 THETOStY input Ext txt is 4220 mikroPascal PRO for dsPICSO 33 and PIC24 LongintToStr 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 longint number to be converted output destination string var input longint txt array 11 of char Pf sec begin input 12345678 IntToStr input txt txt as 123456 78 LongWord ToStr Prototype procedure LongWordToStr input dword var ou
288. _ Out 1 1 Card detected i ie Continue Statement You can use the continue statement within loops to skip the cycle continue statement in the for loop moves program counter to the line with keyword for after incrementing the counter continue statement in the while loop moves program counter to the line with loop condition top of the loop continue statement in the repeat loop moves program counter to the line with loop condition bottom of the loop continue jumps here continue jumps here repeat for i do while condition do begin begin begin bea ane sve continue continue continue continue jumps here end end until condition 229 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Exit Statement The exit statement allows you to break out of a routine function or procedure It passes the control to the first statement following the routine call Here is a simple example procedure Procl var error byte begin we re doing something here if error TRUE then exit some code which won t be executed if error is true end Note If breaking out of a function return value will be the value of the local variable result at the moment of exit Goto Statement Use the goto statement to unconditionally jump to a local label for more information refer to Labels Syntax of the goto statement is goto label name This will transfer control to the location
289. _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 mode mode parameter Valid values Valid values SPI_T6963C_ROM_MODE_OR SPI_T6963C 63C_ROM_MODE_TEXT 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 combined via the logical AND TEXT Mode This option is only available when displaying just a text The Text Attribute values are Parameters c char to be written x char position on x axis y char position on y axis ROM_MODE_XOR SPI_T6963C_ROM_MODE_AND and SPI_T69 Mode parameter explanation 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 function stored in the graphic area of display memory For more details see the T6963C datasheet Nothing SPI T6963C write char A 22 23 SPI T6963C ROM MODI E AND Toshiba Glcd module needs to be initialized See SPI_T6963C_Config routine None MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_T6963C_write_tex
290. _Init_Advanced routines SPI Ethernet ENC24J600 module connections var SPI Ethernet 243600_CS gt sbit at RFI bit var SPI Ethernet_24j600_CS_ Direction sbit at TRISFI1 bit var myMacAddr array 6 of byte my MAC address myIpAddr array 4 of byte my IP addr myMacAddr O0 0x00 myMacAddr 1 0x14 myMacAddr 2 OxA5 myMacAddr 3 0x76 myMacAddr 4 0x19 myMacAddr 5 Ox3F myIpAddr 0O 192 myIpAddr 1 168 myIpAddr 2 1 myIpAddr 3 60 SPILL Fave F SPI Ethernet _ 243600 Init myMacAddr myIpAddr SPI Ethernet 24j600 MANUAL NEGOTIATION and SPI Ethernet 243600 FULLDUPLEX and SPI Ethernet _24j600_ SPD100 MikroElektronika 503 mikroPascal PRO for dsPIC30 33 and PIC24 SPI_Ethernet_24j600_Enable Prototype procedure SPI Ethernet 24j600 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 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 2NC243600 module such as Pattern Match Magic Packet and Hash Table
291. _LCD_SHIFT_LEFT Shift display left without changing display data RAM LCD SHIFT RIGHT Shift display right without changing display data RAM 536 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 var text array 16 of char counter byte Port Expander module connections var SPExpanderRST sbit at LATFO bit var SPExpanderCS sbit at LATF1 bit var SPExpanderRST Direction sbit at TRISFO bit var SPExpanderCS Direction sbit at TRISF1 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 text mikroElektronika ADPCFG OxFFFF initialize AN pins as digital SPIL Inne 3 Initialize SPI Spi Led Config 0 Initialize LCD over SPI interface Spi Led Cmd LCD CLEAR Clear display Spi Lcd Cmd LCD CURSOR OFF Turn cursor off Spi Led Out 1 6 mikrok Print text to LCD lst row 6th column Spi ed Che CPC Append gt I Spi_Led_Out 2 1 text Print text to LCD 2nd row Lst column Spi Led Gut 3 1 mikrob Spi Led Out 4 15 mikroE Moving text for counter 0 to 3 do begin Spi Led Cmd LCD SHIFT RIGHT Move
292. _Right_Direction external pin sbit at TRISB11 bit var DriveY Up Direction sbit sfr Direction of the DriveY_Uppin var DriveY_Up Direction sbit external at TRISB12_ bit var DriveY Down Direction sbit sfr el of the DriveY_ Down 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_Calibration_Consts 614 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 ADCL Inte Initalize ADC module TE TFT Init 320 240 13 12 Initialize touch panel TP_TFT_Set_ADC_Threshold eums Re TP_TFT_Init has to be called before using this routine TP TFT Set ADC Threshold 900 Set touch panel ADC threshold ows Re MikroElektronika 615 mikroPascal PRO for dsPICSO 33 and PIC24 TP_TFT_Press_Detect Prot
293. a to them procedure M Create Multiple Files begin for loop2 YB to Z do begin UART1 Write loop2 signal the progress filename 7 loop2 set filename Mmc Fat Set File Date 2005 6 21 10 35 0 Set file date amp time info Mmc_ Fat Assign filename 0xA0 find existing file or create a new one 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 Opens an existing file and rewrites it procedure M Open File Rewrite begin filename 7 Gr 2 Mme Fat Assign filename 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 Set filename for single file tests 0 402 mikroPascal PRO for dsPIC30 33 and PIC24 end fi a a Opens an existing file and appends data to it ZZ and alters the date time stamp procedure M Open File Append begin filename 7 B Mmc_Fat_Assign filename 0 Mme Fat Set File Date 2009 1 23 17 22 0 Mme Fat _Append Prepare file for append file contents for mikroElektronika 2007 Prepare file for append file contents 26 10 Tf LE Mmc Fat Write fi
294. address exceeds 16 bit limit the compiler uses handle 16 bit pointer on GOTO A handle usage is automatic compiler process so there is no need for the user to intervene Variable constant and routine alignment Simple type variables whose size exceeds 1 byte word integer dword longint real are always set to alignment 2 i e are always allocated on even address Derived types and constant aggregates whose at least one element exceeds size of 1 byte are set to alignment 2 Routines are always set to aligment 2 166 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 dsPIC Memory Organization The dsPIC microcontroller s memory is divided into Program Memory and Data Memory Program Memory ROM is used for permanent saving program being executed while Data Memory RAM is used for temporarily storing and keeping intermediate results and variables Program Memory ROM Program Memory ROM is used for permanent saving program code being executed and it is divided into several sections as on the picture below The size of these sections is device dependant The program memory map is divided into the User Memory Space and Configuration Memory Space The User Memory Space contains the Reset vector interrupt vector tables program memory and data EEPROM memory dsPIC30 family and some PIC24 family MCU s The Configuration Memory Space contains non volatile configuration bits for setting device options and the devic
295. age 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 SPIL Tnrt initialize SPI1 module CANSPLIInit 1 3 3 3 1 CANSPE Init Flags ff initialize CANSPI Notes CANSPI mode NORMAL will be set on exit MikroElektronika 264 mikroPascal PRO for dsPICSO 33 and PIC24 CANSP SetBaudRate 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 CA
296. age Text 1 mPDsPic exe DBG pP30F4013 MSF GC Y DL 011111114 fo80 N C Program Files Mikroelektronik 132 Compilation Started 1015 Hint Compiling unit C Program Files Mikroelektronika mikroPascal PRO For dsPIC Examples Developme 1010 Hint Unit UART mpas has been recompiled 133 Compiled Successfully 138 All files Compiled in 15 ms 1143 Used RX bytes 32 100 Free RX bytes 0 0 1143 Static RAM bytes 41 Dynamic RAM bytes 2038 1143 Used ROM bytes 820 3 Free ROM bytes 31948 97 144 Project Linked Successfully 1004 COFF file successfully generated Linked in 610 ms Project UART mppds completed 1032 ms Finished successfully 24 Nov 2009 11 40 01 Uh o a oooooogm o mAN 4 Generated COFF file will be created in the project folder with the cof extension Related topics Using MPLAB ICD 2 Debugger Using MPLAB Simulator 164 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 CHAPTER 7 dsPIC30 33 and PIC24 Specifics In order to get the most from the mikroPascal PRO for dsPIC30 33 and PIC24 compiler the user should be familiar with certain aspects of dsPIC30 33 and PIC24 MCU This knowledge is not essential but it can provide a better understanding of the dsPIC30 33 and PIC24 s capabilities and limitations and their impact on the code writing as well MikroElektronika 165 mikroPascal PRO for dsPICSO 33 and PIC24 Types Efficiency
297. al PRO for dsPIC30 33 and PIC24 ECANxSelectTxBuffers Prototype function ECANxSelectTxBuffers txselect word word The function designates the ECAN module s transmit buffers Parameters txselect transmit buffer select By setting bits in the txselect lower byte corresponding buffers are enabled for transmition The ECAN module supports up to 8 transmit buffers Also by clearing bits in the txselect lower byte corresponding buffers are enabled for reception 0 if input parameter is valid OxF FFF if input parameter is invalid Requires The ECAN routines are supported only by MCUs with the ECAN module Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus The ECAN module must be initialized See the ECANxInitialize routine Buffers 0 and 2 are enabled for transmition ECAN1SelectTxBuffers 0x0005 at ECAN library routine require you to specify the module you want to use To select the desired ECAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of ECAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library ECANxFilterDisable Prototype procedure ECANxFilterDisable fltdis word The function disables receive filters Parameters flt dis filter disable selection parameter Each bit corresponds to appropriate filter By setting bit the corresponding fi
298. al PRO for dsPICSO 33 and PIC24 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_lssue_ID_Command 219 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Cf_Init PRetuns Nong OOOO Requires Global variables CF Data Port Compact Flash data port CF_RDY Ready signal line E Write enable signal line E Output enable signal line D1 Chip detect signal line _CE1 Enable signal line CF_A2 Address pin 2 CF_A1 Address pin 1 CF_A0 Address pin 0 CF RDY direction Direction of the Ready pin direction Direction of the Write enable pin E direction Direction of the Output enable pin D1 direction Direction of the Chip detect pin 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_ AO direction Direction of the Address 0 pin must be defined before using this function
299. als 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 register desired register rbit desired bit Rems nons OOS Example ClearBit PORTC 7 Clear RC7 Moes noe SS yy MikroElektronika 151 mikroPascal PRO for dsPIC30 33 and PIC24 TestBit Prototype function TestBit register rbit byte byte Description Function tests if the bit rbit 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 Sf 1 if RE2 is set otherwise 0 Delay_us 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 co
300. am Flash Test var WriteWordArr WriteByteArr ReadByteArr ReadWordArr array 8 array 32 array 40 array 20 pw word pb byte i word temp byte begin Initialize arrays byte of word of byte of byte of word WriteWordArr 0 WriteWordArr 1 m WriteWordArr 2 i WriteWordArr 3 ki WriteWordArr 4 xr WriteWordArr 5 o WriteWordArr 6 EB WriteWordArr 7 r Sha WriteByteArr 0 m WriteByteArr 1 i WriteByteArr 2 k WriteByteArr 3 ipie WriteByteArr 4 o WriteByteArr 5 E WriteByteArr 6 l WriteByteArr 7 ie WriteByteArr 8 k WriteByteArr 9 t WriteByteArr 10 r WriteByteArr 11 woy WriteByteArr 12 n WriteByteArr 13 i WriteByteArr 14 k WriteByteArr 15 al WriteByteArr 16 WriteByteArr 17 F WriteByteArr 18 1 WriteByteArr 19 Val WriteByteArr 20 s WriteByteArr 21 h WriteByteArr 22 WriteByteArr 23 Yel WriteByteArr 24 x WriteByteArr 25 a WriteByteArr 26 m WriteByteArr 27 m Y LA plz WriteByteArr 28 1 WriteByteArr 29 e WriteByteArr 30 WriteByteArr 31 i 0 pb WriteByteArr erase the block first FLASH Erase32 0x006000 pb Wri
301. an 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 mikroElektronika txt sub r mikro res memcmp txt txt_sub 16 returns 69 which is ASCII code of the first differing character letter E 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 7 mikr memcpy txt 4 txt_sub 4 string txt will be populated with the first 4 characters of the txt sub string beginning from the 4th character 674 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 memmove Prototype procedure memmove pl p2 byte nn word Description The fu
302. ander Write Byte ModuleAddress RegAddress Data byte Routine writes a byte to Port Expander Parameters Modul ecAddress Port Expander hardware address see schematic at the bottom of this page RegAddress Port Expander s internal register address Data data to be written Port Expander must be initialized See Expander_Init Write a byte to the Port Expander s register Expander Write Byte 0 1 FF Expander_Read_PortA Prototype 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 Expander Read PortA MikroElektronika 419 mikroPascal PRO for dsPICSO 33 and PIC24 Expander_Read_PortB Prototype function Expa nder Read _PortB ModuleAddress byte byte The function reads byte from Port Expander s PortB 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 s
303. aning of object in object oriented programming Identifiers can contain letters from a to z and A to Z the underscore character restriction is that the first character must be a letter or an underscore and digits from 0 to 9 The only Case Sensitivity mikroPascal PRO for dsPIC30 33 and PIC24 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 dat2string SUM3 _vtext and here are some invalid identifiers 7temp NO cannot begin with a numeral Shigher NO cannot contain special characters XOF NO cannot match reserved word 423 0704 NO cannot contain special characters dot Punctuators The mikroPascal PRO for dsPIC30 33 and PIC24 punctuators also known as separators are Brackets Parentheses Comma Semicolon Colon Dot MikroElektronika 188 mikroPascal PRO for dsPICSO 33 and PIC24 Brackets Brackets indicate single and multidimensional array subscripts var alphabet array 1 30 of byte Ly alphabet 3 c For
304. ap 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 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 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 attr f
305. ar var L 7 var L var L var 1 var i End of 1D13700 module connections init display for 320 pixel width 240 pixel height S 1D13700 Init 320 240 sbit at TRISC2 bit sbit at TRISC1 bit sbit at TRISCO bit sbit at TRISC3 bit sbit at TRISC4 bit 323 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 1D13700_Write_Command Prototype procedure 1D13700 Write Command command byte Description Writes a command to S1D13700 controller Parameters command command to be issued 91913700 6 RrcAT Cursor moves right after write to display SS memory s1p13700 CS DEPT Cursor moves left after write to display memory eiDiadod cs UP Cursor moves up after write to display memory 1D13700 CS DOWN Cursor moves down after write to display memory Selects the gray se i in bits per pixel 1D13700_MEMWRITE Write to display memory 1D13700_MEMREAD Read from display memory Gled module needs to be initialized See the S1D13700_Init routine Turn the display on S 1D13700 Write Command S1D13700 DISP ON S MikroElektronika 324 mikroPascal PRO for dsPICSO 33 and PIC24 1D13700_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
306. ar 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 Editor ASCII Chart EEPROM Editor Filter Designer Graphic Lcd Bitmap Editor HID Terminal 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 112 MikroElektronika mikroPascal PRO for dsPICSO 33 and PIC24 Metacharacters Iterators 112 Metacharacters Alternatives 113 Metacharacters Subexpressions 113 Metacharacters Backreferences 113 Keyboard Shortcuts 114 CHAPTER 3 116 mikroPascal PRO for dsPIC30 33 and PIC24 Command Line Options 116 CHAPTER 4 118 mikrolCD In Circuit Debugger 118 Introduction 118 mikrolCD Debugger Options 120 Debugger Options 120 mikrolCD Debugger Example 121 mikrolCD Debugger Windows 125 Debug Windows 125 Breakpoints Window 125 Watch Values Window 125 RAM Window 127 Stopwatch Window 127 EEPROM Watch Window 128 Code Watch Window 129 CHAPTER 5 130 Software Simulator Overview 130 Software Simulator 131 Software Simulator
307. ard 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_ 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 Cf Write TInat 590 1 MikroElektronika 282 mikroPascal PRO for dsPICSO 33 and PIC24 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 Parameters data_ byte to be written Nothing 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
308. ascal PRO for dsPIC30 33 and PIC24 1D13700_Line Prototype procedure 1D13700 Line x0 y0 xl yl word pcolor byte Description 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 1D13700_ BLACK Black color S 1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700_Init routine 1D13700 Line 0 0 239 127 S1D13700 WHITER 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 1D13700_ BLACK Black color 1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700_Init routine 1D13700 Line 0 0 239 127 S1D13700 WHITE MikroElektronika 330 mikroPascal PRO for dsPIC30 33 and PIC24 S1D13700_V_Line Prototype procedure S 1D13700 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 c
309. ascal PRO for dsPIC30 33 and PIC24 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 holding 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 MikroElektronika 489 mikroPascal PRO for dsPIC30 33 an
310. ascal PRO for dsPIC30 33 and PIC24 You may use bitwise and to form config word out of these values For example Copy Code To Clipboard init ECAN CONFIG SAMPLE THRICE and ECAN CONFIG PHSEG2 PRG ON and ECAN CONFIG STD MSG and ECAN CONFIG MATCH MSG TYPE and ECAN CONFIG LINE FILTER OFF ECANIInitialize 1 I 3 3 1 init initialize ECANI1 ECAN_TX_MSG_FLAGS Constants ECAN TX MSG FLAGS are flags related to transmission of ECAN message The routine ECANxWrite expect one of these or a bitwise combination as their argument const _ECAN_TX PRIORITY BITS word 0x03 _ECAN_TX PRIORITY 0 word OxFC XXXXXX00 _ECAN_TX PRIORITY 1 word 0xFD XXXXXX01 _ECAN TX PRIORITY 2 word OxFE XXXXXX10 _ECAN TX PRIORITY 3 word OxFF XXXXXX11 ECAN TX FRAME BIT word 0x08 _ECAN_TX STD FRAME word OxFF XXXXX1XX _ECAN_ TX _XTD_FRAME word 0xF7 XXXXXOXX _ECAN_ TX _RTR_BIT word 0x40 ECAN TX NO RTR_FRAME word OxFF X1XXXXXX ECAN_TX_RTR_FRAME word OxBF XOXXXXXX You may use bitwise and to adjust the appropriate flags For example Copy Code To Clipboard form value to be used with CANSendMessage send_config ECAN TX PRIORITY 0 and ECAN TX XTD_FRAME and ECAN TX NO RTR FRAME ECAN1SendMessage id data 1 send_config ECAN_RX_MSG_FLAGS Constants ECAN RX MSG FLAGS ar
311. at 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 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 format and initialize the FAT library if Cf Fat _QuickFormat mikroE 0 then begin end MikroElektronika 284 mikroPascal PRO for dsPICSO 33 and PIC24 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 wil
312. ated as awora 65y Requires Glcd needs to be initialized see Glcd_Init routine Glcd side x axis position and page should be set first See functions Glced_Set_Side Glcd_Set_X and Glcd_Set_Page 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 var data_ byte Glcd_Read_Data data_ Glcd_Read_ Data Glcd_Write_Data Prototype procedure Glcd Write Data data_ byte 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 Glced_Set_Side Glcd_Set_X and Glcd_Set_Page var data_ byte Gled Write Data data_ MikroElektronika 392 mikroPascal PRO for dsPICSO 33 and PIC24 Glcd_Fill Prototype procedure Glcd Fill pattern byte Description Fills Glcd memory with the byte pattern To clear the Gled screen use Glcd Fill 0 To fill the screen meee use Glcd_ Fill 0xFF E E ame e e Gled Fill 0 Glcd_Dot pene 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 Valid values 0 2 Th
313. ated topics COFF File Using MPLAB ICD 2 Debugger mikroPascal PRO for dsPICSO 33 and PIC24 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 gt User Accounts gt 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 they 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 a
314. ation 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 baa j SFFOF i e Jj i becomes SOF higher byte SFF is lost MikroElektronika 213 mikroPascal PRO for dsPICSO 33 and PIC24 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 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 p c lt L a i 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 TBytePtr var a b cc byte dd word begin a 241 b 128 ce i a t bi equals 113 cc word a b equals 113 dd a bi e
315. ators 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 at least 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 one 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 MikroElektronika 110 mikroPascal PRO for dsPIC30 33 and PIC24 Examples count r B matches strings like counter countelkjdflkj9r and countr count r matches strings like counter countelkjdflkj9r but not countr count r matches strings like counter countar and countr but not
316. ayed 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 Glcd needs to be initialized for SPI communication see SPI_Glcd_lInit 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 Glod Partiallimage l0 12 10 15 16 32 image Use the mikroPascal PRO for dsPIC30 33 and PIC24 integrated Glcd Bitmap Editor Tools gt Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd MikroElektronika 929 mikroPascal PRO for dsPIC30 33 and PIC24 Library Example The example demonstrates how to communicate to KSO108 Glcd via the SPI module using serial to parallel convertor MCP23S17 Copy Code To Clipboard program SPI Glcd 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 someText array 20 of char counter byte procedure Delay2S begin Delay ms 2000 end begin SDEFINE COMPLETE EXAMPLE comment this line to make simpler smaller example ADPCFG OxFFFF If Port Expander Library uses SPI1 module f ana SPIL Imai Initialize SPI module used with Por
317. before utilizing this library Not all MCUs support advanced configuration Please read the appropriate datasheet before utilizing this library MikroElektronika 242 mikroPascal PRO for dsPICSO 33 and PIC24 ADCx_Get_Sample 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 10 bit or 12 bit depending on selected mode by ADCx_Init_Advanced or MCU 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 ADC library routines require you to specify the module you want to use To select the desired ADC module simply change the letter x in the routine prototype for a number from 1 to 2 Before using the function be sure to configure the appropriate TRISx bits to designate pins as inputs var adc value word adc value ADC1 Get _Sample 10 read analog value from ADC1 module channel 10 Number of ADC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 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 ADCx_Read function ADCx Read channel word word The function initializes enab
318. bination as their argument Copy Code To Clipboard const _CAN CONFIG DEFAULT word OxFF f 41111111 CAN CONFIG PHSEG2 PRG BIT word 0x01 CAN CONFIG PHSEG2 PRG ON word OxFF XXXXXXX1 CAN CONFIG PHSEG2 PRG OFF word OxFE XXXXXXXO CAN CONFIG LINE FILTER BIT word 0x02 CAN CONFIG LINE FILTER ON word OxFF AI XXXXXX1X CAN CONFIG LINE FILTER OFF word OxFD XXXXXXOX CAN CONFIG SAMPLE BIT word 0x04 CAN CONFIG SAMPLE ONCE word OxFF ZZ XXXXX1XX _CAN CONFIG SAMPLE THRICE word OxFB XXXXXOXX CAN CONFIG MSG TYPE BIT word 0x08 CAN CONFIG STD MSG word OxFF IL BERRIES CAN CONFIG XTD MSG word OxF7 XXXXOXXX CAN CONFIG DBL BUFFER BIT word 0x10 CAN CONFIG DBL BUFFER ON word OxFF ff BXRIRKAX CAN CONFIG DBL BUFFER OFF word OxEF XXXOXXXX MikroElektronika 254 mikroPascal PRO for dsPIC30 33 and PIC24 CAN CONFIG MATCH TYPE BIT word 0x20 CAN CONFIG ALL VALID MSG word OxDF XXOXXXXX CAN CONFIG MATCH MSG TYPE word OxFF XX1XXXXX You may use bitwise and to form config byte out of these values For example Copy Code To Clipboard init CAN CONFIG SAMPLE THRICE and CAN CONFIG PHSEG2 PRG ON and CAN CONFIG STD MSG and CAN CONFIG DBL BUFFER ON and CAN CONFIG
319. bit at TRISFO bit CD command data signal direction var T6963C_ ctrirst_ 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 ctrlfis sbit at LATF6 bit FS signal var T6963C ctrimd sbit at LATF5 bit MD signal var T6963C_ctrice Direction sbit at TRISF3 bit CE signal direction var T6963C_ctrlfs Direction sbit at TRISF6 bit FS signal direction var T6963C_ ctrlimd Direction sbit at TRISF5S bit MD signal direction End T6963C module connections var panel byte current panel i 2 word general purpose register curs byte cursor visibility Cposx cposy word cursor x y position MikroElektronika 583 mikroPascal PRO for dsPIC30 33 and PIC24 txtcols byte number of text coloms ExE EXEL sexing 29 begin txtl EINSTEIN WOULD HAVE LIKED mE EXE GLCD LIBRARY DEMO WELCOME DEFINE COMPLETE EXAMPLE comment this line to make simpler smaller example ADPCFG OxFFFF initialize AN pins as digital TRISB8 bit 1 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 T6963C ctrice Direction i 0 T6963C_ctrice 0 Enable
320. bsence of parentheses these rules resolve the grouping of expressions with operators of equal precedence 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 Tonersnds Rese addition byte short word integer byte short word integer longint dword real longint dword real subtraction 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 rounds down to byte short word integer byte short word integer nearest integer longint dword longint dword modulus returns the remain byte short word integer byte short word integer der of integer division cannot Longint dword longint dword be used with floating points division floating point byte short word integer real longint dword real 216 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 gener ate code But in case of implicit division by zero x div y
321. 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 This function reurs size ofacivefie nbytes SSCS 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 file size Mme Fat Get File Size 399 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Mmc_Fat_Get_Swap _ File Prototype function Mmc 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 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 sw
322. cal PRO for dsPICSO 33 and PIC24 Run Run Menu Options Run Menu is used to debug and test compiled code on a software or harware level Start Debugger F9 Stop Debugger Ctrl F2 Run Pause Debugger F6 Step Into Pee Step Over Fe Step Out Ctrl F8 Run To Cursor F4 i Jump To Interrupt F2 Toggle Breakpoint F5 Clear Breakpoints Shift Ctrl F5 Disassembly mode Alt D a es eiptiom SOS Related topics Keyboard shortcuts Debug Toolbar 49 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 4lt C Ascii Chart EEPROM Editor Export Code To HTML Filter Designer Tool GLCD Bitmap Editor HID Terminal LCD Custom Character Seven Segment Editor UDP Terminal USART Terminal Ctrl T Options F12 Ber ooo Related topics Keyboard shortcuts Tools Toolbar MikroElektronika 50 mikroPascal PRO for dsPICSO 33 and PIC24 Help Help Menu Options Help Fi Migration Document Check For Updates mikroElektronika Support Forums mikroElektronika Web Page How To Register About pep o Description Cd Related topics Keyboard shortcuts H
323. cd Library var LCD RS sbit sfr external Register Select line var LCD RS sbit at var LCD EN sbit sfr external Enable line D EN sbit a var LCD D7 sbit sfr external Data 7 line var D D7 sbit at var LCD D6 sbit sfr external Data6 line D D6 sbita CD DS sbit sfr external Data 5 line D D5 sbit at CD_D4 sbit sfr external Data 4 line D D4 sbit a LCD RS Direction Sbit sfr Direction Register Select direction pin S Moio E var LCD EN Direction sbit p 2 Enable direction pin external var LCD D7 Direction it r r S Data 7 direction pin external var LCD D6 Direction it n S a Data 6 direction pin external var LCD D5 Direction iti RE Data 5 direction pin external a var LCD D4 Direction it i r LCD Data 4 direction pin Library Routines Led_Init Led_Out Lcd_Out_Cp Led_Chr Led_Chr_Cp Led_Cmd 373 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Led_Init Returns Nothing S O 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 LCD EN Enable signal pin LC _ 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 D
324. cd Library mikroPascal PRO for dsPIC30 33 and PIC24 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 External dependencies of Graphic Lcd Library Glcd Glcd_Fonts 34 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 External dependencies of Graphic Lcd Library The following variables must be defined in all projects using Graphic Lcd Library var GL C var GLCD _ D6 sbit sfr external var GL D7 sbit sfr external Data 7 line Description example D DO sbit sfr external Data 0 line LCD_DO at C7 CD by var GLCD CS1 sbit sfr external Chip Select 1 line var GLCD CS1 sbit at LATB4 bit var GLCD CS2 sbit sfr external Chip Select 2 line var GLCD CS2 sbit at LATB5 bit var GLC var GL D RS sbit sfr external Register select line var GLCD RS sbit at LATFO bit D RW sbit sfr external Read Write line var GLCD RW sbit at LATF1 bit C var GLCD EN sbit sfr external Enable line var GLCD EN sbit at LATF4 bit var GLCD_RST sbit sfr external var GLCD RST sbit at LATF5 bit it sfr ar Sar Direction of the Data 0 pin var GLCD DO Direction external var GLCD D1 Direction external var GLCD D2 Direction sfr external var GLCD D3 Direction external var GLCD
325. ceived 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_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 483 mikroPascal PRO for dsPICSO 33 and PIC24 SPI_Ethernet_UserUDP Prototype function SPI Ethernet UserUDP var remoteHost array 4 of byte remotePort destPort reqhLength 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 destPort 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
326. chester RF_Send_Byte format St1 St2 Ctr B7 B6 B5 B4 B3 B2 B1 BO Bi phase coding gi 1 0 2 4ms Example of transmission 11000100011 Important The Manchester receive routines are blocking calls Man Receive Init and Man Synchro This means that MCU will wait until the task has been performed e g byte is received synchronization achieved etc Manchester code library implements time based activities so interrupts need to be disabled when using it External dependencies of Manchester Code Library The following variables must be defined in all De crivtion projects using Manchester Code Library P var MANRXPIN sbit sfr external var MANRXPIN sbit at RFO bit var MANTXPIN sbit sfr external var MANTXPIN sbit at LATF1_ bit var MANRXPIN Direction sbit sfr Direction of the Receive pin 2 MANRXPIN Direction sbit at external pin TRISFO bit var MANTXPIN Direction sbit sfr Direction of the Transmit var MANTXPIN Direction sbit at external pin TRISF1_ bit 3 9 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Library Routines Man_Receive_Init Man_Receive Man_Send_Init Man_Send Man_Synchro Man_Break The following routines are for the internal use by compiler only Manchester_0 Manchester_1 Manchester_Out Man_Receive_Init Prototype function Man Receive Init word order to retrieve baud rate out of the incomin
327. cial 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 0 pressed is set to 1 if the key is pressed and 0 if it is released 1 if reading of a key from the keyboard was successful 0 ifno 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 if value 13 and special 1 then break until 0 1 428 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 je joo C C 2 3 C ee C o C C C CA Ee 2 33 jaa C MikroElektronika 429 mikroPascal PRO for dsPIC30 33 and PIC24 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 RBO bit PS2 Clock sbit at RBI bit PS2 Data Direction sbit at TRISBO bit PS2 Clock Direction sbit at TRISB1 bit
328. cified 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 dsPIC30 33 and PIC24 at the time of activation 3 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 MikroElektronika 38 ikroPascal PRO for dsPIC30 33 and PIC24 CHAPTER 2 mikroPascal PRO for dsPIC30 33 and PIC24 Environment mikoPascal PRO for dsPIC30 33 and PIC24 Main Menu Options Available Main Menu options are z File im a cr Project EE IT T a Related topics Keyboard shortcuts Toolbars MikroElektronika 40 mikroPascal PRO for dsPICSO 33 and PIC24 File File Menu Options The File menu is the main entry point for manipulation with the source files LI New Unit Ctrl N Open Cctrl O Recent Files gt Save Ctrl 5 Save As Close Ctrl F4 Close All Shift Ctrl F4 Print Preview Print
329. con trom Tools toolbar p Send mikroElektronika Send Repeat sending y Repeat sending every ort ASCII d New Line Send ASCII Supp Append New es Foota a Send as typing Send from file C iiaiai mikroElektronika Connected to COM1 MikroElektronika 96 mikroPascal PRO for dsPICSO 33 and PIC24 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 fora GSM GPSR module which is 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 ImageTo Project Add
330. cond matrix va mxl array 6 of word mx2 array 6 of word mx3 array 6 of word Matrix Add mx1l mx2 mxDest 2 3 WO W4 used not restored AccuA used not restored CORCON saved used restored numRows1 numCols2 lt 214 MikroElektronika 653 mikroPascal PRO for dsPICSO 33 and PIC24 Miscellaneous Libraries Button Library Conversions Library C Type 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 654 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Button Prototype function Button var port word 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 255 if the pin was in the active state for given period 0 otherwise program Button Test Parameters port button port address pin button pin time debouncing period in milliseconds active state determines what is considered as active state Valid values
331. countelkj9r counte 2 r matches string counteer counte 2 x matches strings like counteer counteeer counteeer etc counte 2 3 x 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 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 im
332. ction sbit CFP Cel direction sbit CF_A2 direction sbit CF Al direction sbit CF A0 direction sbit end of cf pinout const LINE LEN 37 var err txt string 20 file contents filename string 14 character loop loop2 i size byte byte longint Buffer array 512 of byte string LINE LEN for for for for for for writing writing writing writing writing writing at TRISB7 bit at TRISB6 bit at TRISB5 bit at TRISB4 bit at TRISB3 bit at TRISB2 bit at TRISB1 bit at TRISBO bit File names to to to to to to latch latch use use always always output output pin pin latch latch latch latch always always always always output output output output use use use use pin pin pin pin MikroElektronika 292 mikroPascal PRO for dsPIC30 33 and PIC24 UART write text and new line carriage return procedure UART1 Write Line var uart_text begin UART1 Write Text uart_text UART1 Write 13 UART1 Write 10 end Creates new file and writes some 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 90 do begin UART1_Write file _contents 0 loop div 10 48 file contents 1 loop mod 10 48 gL OF line feed string data to it Set file da
333. cy Tree 535 External dependencies of SPI Lcd Library 535 MikroElektronika 20 mikroPascal PRO for dsPICSO 33 and PIC24 Library Routines 535 SPI_Lcd_Config 536 SPI_Lced_Out 536 SPI_Lcd_Out_Cp 537 SPI_Led_Chr 537 SPI_Lcd_Chr_Cp 537 SPI_Lcd_Cmd 538 Available SPI Lcd Commands 538 Library Example 539 Default Pin Configuration 539 SPI Lcd8 8 bit interface Library 541 Library Dependency Tree 541 External dependencies of SPI Lcd Library 541 Library Routines 541 SPI_Lcd8_ Config 542 SPI_Lcd8_Out 542 SPI_Lcd8_Out_Cp 543 SPI_Lced8_ Chr 543 SPI_Lcd8_Chr_Cp 543 SPI_Lcd8_Cmd 544 Available SPI Lcd8 Commands 544 Library Example 545 SPI T6963C Graphic Lcd Library 547 Library Dependency Tree 547 External dependencies of SPI T6963C Graphic Lcd Library 547 Library Routines 548 SPI_T6963C_config 549 SPI_T6963C_writeData 550 SPI_T6963C_writeCommand 550 SPI_T6963C_setPtr 551 SPI_T6963C_waitReady 551 SPI_T6963C_fill 551 SPI_T6963C_dot 552 SPI_T6963C_write_char 552 SPI_T6963C_write_text 553 SPI_T6963C_line 553 SPI_T6963C_rectangle 554 SPI_T6963C_rectangle_round_edges 554 SPI_T6963C_rectangle_round_edges_fill 555 SPI_T6963C_box 555 SPI_T6963C_circle 556 SPI_T6963C_circle_fill 556 SPI_T6963C_image 556 SPI_T6963C_Partiallmage 557 SPI_T6963C_sprite 557 SPI_T6963C_set_cursor 558 2 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_T6963C_clearBit 558 SPI_T6963C_setBit 558 SPI_T6963C_negBit 559 SPI_T6963C_displayGrPan
334. d form value to be used CAN CONFIG PHSEG2 PRG ON and with CANInitialize CAN CONFIG XTD MSG and CAN CONFIG DBL BUFFER ON and CAN CONFIG MATCH MSG TYPE and CAN CONFIG LINE FILTER OFF CAN1Initialize 1 3 3 3 1 Can_Init Flags initialize CAN CAN1SetOperationMode _CAN MODE CONFIG OxFF set CONFIGURATION mode BJ CAN1SetMask _CAN MASK B1 i CAN CONFIG MATCH MSG TYPI set all maskl bits to ones CAN1SetMask _CAN MASK B2 CAN CONFIG MATCH MSG TYPE and CAN CONFIG XTD MSG set all mask2 bits to ones CAN1SetFilter CAN FILTER Bl F1 ID 1st CAN CONFIG XTD MSG set id of filter Bi Fl to ist node ID and CAN CONFIG XTD MSG CAN1SetOperationMode _CAN MODE NORMAL OxFF set NORMAL mode while TRUE do begin Msg Revd CAN1Read Rx_ ID RxTx Data Rx Data Len Can Rev Flags if Rx_ID ID 1st and Msg Revd lt gt 0 lt gt 0 then begin PORTB RxTx Data 0 output data at PORTB RxTx Data Q i RxTx Datal0 1 CANI1Write ID 2nd RxTx Data 1 Can Send Flags send incremented data back end end end 259 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 HW Connection CAN RX of MCU CAN TX of MCU MCP2551 Shielded u twisted pair i Example of interfacing CAN transceiver with MCU and CAN bus MikroElektronika 260 mikroPascal PRO for dsPICSO 33 and PIC24 CANSPI Library
335. d end 516 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 t0 t7 will toggle RDO to RD7 bit and return HTML main page all other requests return also HTML main page HW Connection LOvOldsP MikroElektronika 517 mikroPascal PRO for dsPICSO 33 and PIC24 SPI Graphic Lcd Library mikroPascal PRO for dsPIC30 33 and PIC 24 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 Important When using this library with dsPIC33 and PIC24 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 SP modules it is possib
336. d else begin UART Write Line err txt Note Cf Fat Init tries to initialize a card more than once If card is not present initialization may last longer depending on clock speed end end 405 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 HW Connection OSCILLATOR MMC CS LOvOldsPp MMC SD CARD Pin diagram of MMC memory card MikroElektronika 406 mikoPascal PRO for dsPIC30 33 and PIC24 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
337. d PIC24 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_getDnslpAddress 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 SP _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
338. d Port Expander module connections If Port Expander Library uses SPI1 module SPIT Init Initialize SPI module used with PortExpander SPI Lede Config 0 intialize Lcd in 8bit mode Via SPI SPI_Lced8_Out Prototype procedure SPI Lcd8 Out row column byte var text string Description 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 Nothing Requires 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 Leds Ouc l 2 Helio 7 None 540 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_Lcd8 Out_Cp Sadda procedure SPI Lcd8 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 Lcd needs to be initialized for SP communication see SPI_Lcd8_Config routine Write text Here at current cursor position SPI Lede Out Cp Here SPI_Lod8_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 writin
339. d msg_ id data data_len rx _flags then begin end CAN library routine require you to specify the module you want to use To use the desired CAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of CAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 252 mikroPascal PRO for dsPICSO 33 and PIC24 CANxWrite Prototype function CANxWrite id longint var data array 1 of byte dataLen CAN TX MSG FLAGS word word 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 CAN RX MSG FLAGS message flags Valid values CAN TX MSG FLAGS constants See CAN_TX_ MSG_FLAGS constants 0 if all Transmit Buffers are busy OxFFFF if at least one Transmit Buffer is available Requires MCU with the CAN module MCU must be connected to the CAN transceiver MCP2551 or similar which is connected to the CAN bus CAN must be in Config mode otherwise the function will be ignored See CANxSetOperationMode send message extended CAN message with appropriate ID and data var tx flags word data array 8 of byte msg id longint CAN1Set
340. d radius radius of the rounded edge TFT module needs to be initialized See the TFT_Init routine Example 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 eae 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 2 it will double the image TFT module needs to be initialized See the TFT_Init routine Example TFT Image 0 0 image 1 602 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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
341. d 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 ENC28J60 module The ENC28J60 module should be properly cofigured by the means of SPI_Ethernet_Init routine 418 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_Ethernet_Disable Prototype procedure SPI_Ethernet Disable disFlt byte Description This is MAC module routine This routine disables appropriate network traffic on the ENC2 8760 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 disF1t network traffic receive filter flags Each bit corresponds to the appropriate network traffic receive filter MAC Broadcast traffic receive filter flag When set MAC _SPI_Ethernet_ broadcast traffic will be disabled BROADCAST 1 Ox MAC Multicast traffic receive filter flag When set MAC _SPI_Ethernet_ multicast traffic will be disabled MULTICAST CRC check flag
342. dToStr ADC1 Get _Sample 0 dyna tmp var ANO result result SPI Ethernet _putString tmp result result SPI Ethernet putString dyna tmp i pa 7 E result result SPI Ethernet _putString tmp add AN3 value to reply WordToStr ADC1 Get _Sample 1 dyna tmp var AN1 result result SPI Ethernet _putString tmp result result SPI Ethernet putString dyna tmp i 3 7 7 result result SPI Ethernet putString tmp add PORTB value buttons to reply tmp var PORTB result result SPI Ethernet_putString tmp WordToStr PORTB dyna result result SPI Ethernet putString dyna tmp o j result result SPI Ethernet putString tmp 494 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 add PORTD value LEDs to reply tmp var PORTD result z result SPI_Ethernet_putString tmp WordToStr PORTD dyna result i result SPI_Ethernet_putString dyna tmp r result result SPI_Ethernet_putString tmp add HTTP requests counter to reply WordToStr httpCounter dyna tmp var REQ 1a result result SPI_Ethernet_putString tmp result result SPI_Ethernet_putString dyna tmp Vets result result SPI_Ethernet_putString tmp end else if getRequest 5 t then if request path name starts with t toggle PORTD LED bit numb
343. de for the second ECAN node Copy Code To Clipboard program ECAN 2nd uses ECan Defs var Can Init Flags Can Send Flags Can Rev Flags word can flags Rx Data_Len word received data length in bytes RxTx Data array 8 of byte can rx tx data buffer Msg Revd word reception flag Re ID longint can rx and tx ID const ID lst longint 12111 const ID 2nd longint 3 node IDs procedure CliInterrupt org 0x005A ECAN event iterrupt begin TPS2 Cllr 04 clear ECAN interrupt flag if C1lINTF TBIF lt gt 0 then was it tx interrupt C1LINTF TBIF 0 if yes clear tx interrupt flag if C1lINTF RBIF lt gt 0 then was it rx interrupt C1INTF RBIF 0 if yes clear rx interrupt flag end begin Set PLL Fosc Fin PLLPRE PLLDIV PLLPOST 10MHz 2 32 4 20MHz refer the family datasheet for more details CLKDIV CLKDIV and OxFFEO CLKDIVbits PLLPRE 0 PLLFBD 0x1E PLLFBDbits PLLDIV Ox1E CLKDIV CLKDIV and OxFF3F CLKDIVbits PLLPOST 1 CLKDIV CLKDIV or 0x00CO AD1PCFGH OxFFFF ZK AD1PCFGL OxFFFF all ports digital I O AD2PCFGL OxFFFF Th 315 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Clear Interrupt Flags IFSO 0 IFS1 OF IFS2 0 0 0 IFS3 IFS4 r f Enable ECAN1 Interrupt THC2 C TITE z Ty enable ECAN1 interrupts CLINTE
344. debugging The COFF incorporates symbolic procedure function variable and constant names information line number information breakpoints settings code highlighter and all the necessary information for effective and fast debugging By using COFF it is possible to import and debug code generated by mikroElektronika compilers under Microchip s MPLAB COFF File Generation 1 Start mikroPascal PRO for dsPIC30 33 and PIC24 Help and open the desired project For example UART project for EasydsPIC4A board and dsPIC30F4013 will be opened Look in EasydsPIC4A anc Button My Recent Qld Documents Led Led Blinking Touch Panel File name uant Files of type l mikroPascal Project mppds Cancel Mu Netmork C Open as read only MikroElektronika 163 mikroPascal PRO for dsPIC30 33 and PIC24 2 When the project is opened go to Tools Options Output settings and check the Generate COFF file option and click the OK button Options J Editor Nl Output Settings J Tools V Generate ASM file Y Include HEX opcodes Output Settings Include ROM constants Y Include ROM Addresses VY Generate list file Include debug info V Include source lines in output files Optimization level Four Compiler yrn Case sensitive Dynamic link for string literals Y Build all files as library Messages E Warnings Hints hom N Line Message No Mess
345. declarations type variables declarations var Name Name2 type absolute 0x123 external volatile register sfr labels declarations label procedures declarations procedure procedure name var const ParamName jJtype var const ParamName2 ParamName3 Jtype ilevel 0x123 overload forward local declarations begin end functions declarations function function _name var const ParamName type var const ParamName2 ParamName3 type jJtype ilevel 0x123 overload forward 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 MikroElektronika 192 mikroPascal PRO for dsPICSO 33 and PIC24 Place of declaration Identifier is declared in the declaration of a pro Scope extends from the point where it is declared to the end of the current
346. default name for descriptor file is USBdsc mbas but you may rename it Library Routines HID_Enable HID_Read HID_Write HID_Disable USB_Interrupt_Proc USB_Polling_Proc Gen_Enable Gen_Read Gen_Write 630 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 Enable HID_Enable readbuff writebuff writebuff a This function needs to be called before using other routines of USB HID Library HID_Read Prototype 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 a 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 ee If the data transmitting has failed the function returns 0 Otherwise it returns number of transmitted bytes USB HID needs to be enabled
347. demonstrates simple data exchange via UART If MCU is connected to the PC you can test the example from the mikroPascal PRO for dsPIC30 33 and PIC24 USART communication terminal launch it from the drop down menu Tools gt USART Terminal or simply click the USART Terminal Icon E i Copy Code To Clipboard program UARTI var uart rd byte begin ADPCFG OxFFFF Configure AN pins as digital UART1 Init 19200 Initialize UART module at 9600 bps Delay ms 100 Wait for UART module to stabilize UIMODE ALTIO 1 un comment this line to have Rx and Tx pins on their alternate locations This is used to free the pins for other module namely the SPI UART1 Write Text Start VARTI Write 10 UART1 Write 13 while TRUE do Endless loop begin if UART1 Data _Ready lt gt 0 then TE data is received begin uart_ rd UART1 Read Va read the received data UART1 Write uart_rd and send data via UART end end end mikoPascal PRO for dsPIC30 33 and PIC24 HW Connection SUB D 9p CONNECT Receive MCU TO PC data Rx gt Send PC TO MCU Data Tx sy gt Co CABLE 5 CONNECT SUB D 9p OSCILLATOR osc1 a a a 2 w RS232 HW connection mikroPascal PRO for dsPIC30 33 and PIC24 USB Library Universal Serial Bus USB provides a serial bus standard for connecting a wide variety of devices including
348. determines on which clock edge data is considered to be valid Data is valid on IDLE to ACTIVE transition 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 SPI _PRESCALE SEC 1 _SPI PRESCALE PRI 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 470 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPIx_Read Prototype function SPIx Read data_out word word Reads one word or byte depending on mode set by init routines from the SPI bus data_out dummy data for clock generation see device Datasheet for SPI modules implementation details Returns 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 SPIx_Init_ Advanced routines read a byte from the SPI bus var take buffer byte take SPI1_ Read buffer
349. ding Ow Reset PORTF 6 Onewire reset signal Ow Write PORTF 6 OxCC Issue command SKIP ROM Ow Write PORTF 6 0x44 Issue command CONVERT T Delay _us 120 Ow Reset PORTF 6 Ow Write PORTF 6 OxCC Issue command SKIP ROM Ow Write PORTF 6 OxBE Issue command READ SCRATCHPAD temp Ow _Read PORTF 6 temp Ow _Read PORTF 6 shl 8 temp Format and display result on Lcd Display Temperature temp Delay ms 520 end end 410 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 HW Connection 125 C dsPIC30F6014A x oO ISCIICLKI Vdd LCD 2X16 Example of DS1820 connection MikroElektronika 4i1 mikroPascal PRO for dsPICSO 33 and PIC24 Peripheral Pin Select Library The Peripheral Pin Select library enables user to have more than one digital peripheral multiplexed on a single pin Users may independently map the input and or output of any one of many digital peripherals to any one of these I O pins The peripherals managed by the Peripheral Pin Select library are all digital only peripherals Akey difference between pin select and non pin select peripherals is that pin select peripherals are not associated with a default I O pin The peripheral must always be assigned to a specific I O pin before it can be used In contrast non pin select peripherals are always available on a default pin assuming that the peripheral is active and
350. dius integer peolor 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 yl y coordinate of the lower right rectangle corner round radius radius of the rounded edge pcolor color parameter Valid values T6963C_ BLACK and T6963C_ WHITE Toshiba Glcd module needs to be initialized See the T6963C_init routine T6903C rectangle round edges fill 20 20 219 107 12 Te963C 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 yl y coordinate of the lower right box corner pcolor color parameter Valid values T6963C_BLACK and T6963C_WHITE es peng ere box 0 119 239 127 T6963C_WHITE CE E T6963C_circle Prototype procedure T6963C_ circle integer r longint pcolor word Description 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 T6963C_BLACK and T6963C_WHITE ews Rene ae _circle 120 64 110 T6963C WHITE Notes None 916 MikroElektronika mikoPascal
351. dstM i j srcMUjJ i Parameters src original matrix dest result matrix numRows number of rows in the source matrix numCols number of cols in the source matrix va mxl array 6 mx2 array 6 mx3 array 6 mxDest array 9 of word word word word Matrix _ Transpose mx1l mxDest Notes WO W5 used not restored 650 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Matrix_Subtract numCols word Prototype procedure Matrix Subtract var srcl src2 dest array 1024 of word numRows Description Function does matrix subtraction dstM i j srcM1 i j sreM2 i j Parameters srcl first matrix src2 second matrix dest result matrix numRows number of rows in the source matrix numCols number of cols in the source matrix var mxl array 6 of word mx2 array 6 of word mxDest array 9 of word Matrix Subtract mxl mx2 mxDest 2 3 WO W4 used not restored AccuA used not restored AccuB used not restored CORCON saved used restored Matrix_Scale Prototype procedure Matrix Scale ScaleValue word var srcl array 1024 of word numRows numCols word Description Function does matrix scale dstM i j sclVal srcM i j Parameters ScaleValue scale value srcl original matrix dest result matrix numRows number of rows in the source matrix numCols number of cols in the source matrix var mxl array 6 of word mxDes
352. e ydata This memory specifier allows user to access Y Data memory space Example var y char ydata puts y in ydata memory space dma This memory specifier allows user to access DMA memory space dsPIC33F specific Example var y char dma puts y in DMA memory 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 dsPIC Memory Organization dsPIC Memory Type Qualifiers Accessing individual bits SFRs Constants Functions MikroElektronika 171 mikroPascal PRO for dsPICSO 33 and PIC24 Memory Type Qualifiers In addition to the standard storage qualifiers const volatile the compiler introduces storage qualifiers of near and far Near Memory Qualifier 1 Data Memory Objects The qualifier near is used to denote that a variable is allocated in near data space the first 8 kB of Data memory Such variables can sometimes be accessed more efficiently than variables not allocated or not known to be allocated in near data space If variables are allocated in the near data section the compiler is often able to generate better more compact code than if the variables are not allocated in the near data section 2 Program Memory Objects The qualifier near is used to denote that a constant is allocated in the default program memory page 32kB segment of program memory Default program memory page is the
353. e C Extra Boards SPI Ethernet Eth 2 DemolEth 2_Demo mbpds Time 12 3 2009 11 45 51 AM seem am bror com Used RAM Locations Displays used RAM memory locations and their names B statistics Used RAM Locations Click on Name column header to toggle between Name and Unique Assembler Name mikoPascal PRO for dsPIC30 33 and PIC24 SFR Locations Displays list of used SFR locations W statistics DAR 3 Displays ROM memory space usage in a pie like form H statistics ROM Memory Usage Project Name C Extra Boards SPI EthernetlEth 2 DemolEth 2_Demo mbpds Time 12 3 2009 11 45 51 AM mikroPascal PRO for dsPIC30 33 and PIC24 ROM Memory Constants Displays ROM memory constants and their addresses M statistics Bx ROM Memory Constants Functions Sorts and displays functions in various ways M statistics Functions Sorted By Size Click on column header to sort table by Address Name Unique Assembler Name or Sze mikoPascal PRO for dsPIC30 33 and PIC24 Functions Sorted By Name Chart Sorts and displays functions by their name in the ascending order L 76 bytes fo 2 coytes Functions Sorted By Size Chart Sorts and displays functions by their sizes in a chart like form 10 mikroPascal PRO for dsPIC30 33 and PIC24 Functions Sorted By Addresses Sorts and displays functions by the
354. e Choose this option if you are not connected to Internet You will be guided 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 If you choose work online registering method following page will be opened in your default browser Kamikroklektronka a aah 2 DEVELOPMENT TOOLS I COMPILERS I BOOKS Email officeg mikroe com me 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 Too compilers Accessory Boards Special Offers Easy E Publications Support Project Download Product Name John Smith Address Invoice Ifyou do not specify 2CO Number or invoice number then the license key request must be processed 2CO Number manually which can take longer Sime Email jsmith example com Re enter email smith example com Company Product ID Comment Distributor MikroElektronika v Submit Related Links Products News Forums Distributors About MikroElektronika Legal Information and Privacy Policy Product Archive Contact Us Copyright 1996 2010 MikroBlektronika All rights reserved Al trade and or services marks mentioned are the property of their respective owners MikroElektronika 36 mikroPascal PRO for dsPICSO 33 and PIC24 Fill out
355. e read the appropriate datasheet before utilizing this library PWM library routines require you to specify the module you want to use To use the desired PWM module simply change the letter x in the routine prototype for a number from 1 to 2 PWMx_Mc_ Start FRetums Noting OOOO Requires The dsPIC30 33 MCU must have the Motor Control PWM module The PWM module needs to be initalized See the PWMx_Mc_Init function start the Motor Control PWM1 module PWM1 Mc Start Number of PWM modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library PWM library routines require you to specify the module you want to use To use the desired PWM module simply change the letter x in the routine prototype for a number from 1 to 2 MikroElektronika 437 mikroPascal PRO for dsPICSO 33 and PIC24 PWMx_Mc_Stop Rems Nothing OOOO stop the Motor Control PWM1 module PWM1 Me Stopt Number of PWM modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library PWM library routines require you to specify the module you want to use To use the desired PWM module simply change the letter x in the routine prototype for a number from 1 to 2 Library Example The example changes PWM duty ratio on channel 1 continually If LED is connected to the channel 1 a gradual change of emitted light will be noticeable Copy Code
356. e Character Newline character CR LF is not a whitespace in Pascal and serves as a statement terminator separator In mikroPascal PRO for dsPIC30 33 and PIC24 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 some string mikro foo parses to four tokens including a single string literal token some_string mikro foo r 180 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 dsPIC30
357. e Files mask and Path fields C Program files X Lal ok cancel Go To Line Dialog box that allows the user to specify the line number at which the cursor should be positioned Te L ok an Regular expressions option By checking this box you will be able to advance your search through Regular expressions Search for unsigned x20int S E E Related topics Keyboard shortcuts Edit Toolbar Advanced Edit Toolbar MikroElektronika 44 mikroPascal PRO for dsPICSO 33 and PIC24 View View Menu Options View Menu contains commands for controlling the on screen display of the current project Debug Windows Toolbars Bookmarks Code Explorer Library Manager Macro Editor Messages Project Manager Shift Ctrl Fi1 Project Settings i Routine List Ctrl h Quick Converter Ctrl Q View Image Preview a Assembly Listing Statistics Windows 45 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Show Hide Software Simulator mikrolCD In Circuit Debugger debug windows ac ea SST i ar es The Tools toolbar can easily be customized by adding new tools in Options F12 window Related topics Keyboard shortcuts Integrated Tools Software Simulator MikroElektronika 46 mikroPascal PRO for dsPICSO 33 and PIC24 Project Project Menu Options Project Menu allows
358. e ID locations Program Memory ROM Organization L PIC24 dsPIC30F dsPIC33F Program Memory User Memory Space Configuration Memory Space _ _ Tin a a aS 1 dsPIC33F Program Memory Organization MikroElektronika 167 mikroPascal PRO for dsPICSO 33 and PIC24 Data Memory RAM Data memory consists of SFR Memory Space X and Y Data RAM DMA RAM only for dsPIC33F Family Unimplemented Memory Space Data Memory RAM Organization I i PIC24F PIC24H dsPIC30F dsPIC33F Data Memory Data Memory I Near Data Space Near Data Memory Provides Program Provides Program Space Visibility Space Visibility ee a J BoE a 1 PIC24F Data Memory Organization 2 dsPIC33F Data Memory Organization SFR Memory Space The first 2kB of data memory is allocated to the Special Function Registers SFRs The SFRs are control and status register for core and peripheral functions in the dsPIC X and Y Data RAM Up to 8 kB of data RAM is implemented after the SFRs This is general purpose RAM that can be used for data storage This RAM is split into X and Y memory for dsPIC instructions This allows DSP instructions to support dual operand reads so that data can be fetched from X and Y memory space at the same
359. e 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 Library Dependency Tree eee nD SPI Ethernet String 474 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 External dependencies of SPI Ethernet Library The following variables must be defined in all Description projects using SPI Ethernet Library P var SPI _Ethernet_RST sbit sfr var SPI Ethernet RST gt sbit at external ENG ebresct Pil LATFO bit var SPI_Ethernet_CS Direction sbit Direction of the ENC28J60 chip var SPI_Ethernet_CS Direction sfr external select pin sbit at TRISF1 bit var SPI_Ethernet_RST Direction Direction of the ENC28J60 var SPI Ethernet _RST Direction sbit sfr external reset pin sbit at TRISFO bit The following routines must be defined in all ee Description project using SPI Ethernet Library var SPI Ethernet CS sbit sfr var SPI Bthernpet CS sbit at eberan ENC28J60 chip select pin LATF1 bit function SPI_Ethernet_UserTCP var remoteHost array 4 of byte remotePort word localPort word reqLength word var flags TEthPktFlags word Refer to the library example at the bottom TCP request handler of this page for code implementation function SPI Ethernet _ UserUDP
360. e drop down menu View gt Debug Windows gt 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 20 s Delta 80 881 413 4044 07 ms Stopwatch _2 103 943 273 105197 16 ms Reset To Zero Clock 80 MHz 125 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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
361. e 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 222 MikroElektronika mikroPascal PRO for dsPICSO 33 and PIC24 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 ai b 5 word level general rule left side exception if a then if b 5 exceeds byte rang 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 t
362. e files with paths binary files mcl 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 mikroPascal PRO for dsPICSO 33 and PIC24 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 iy 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 Add project files Click Next to continue Cancel Step One Select the device from the device drop down list New Project Wizard Select the device you want to use Device Name P30F4013 692 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Step Two Enter the oscillator frequency value New Project Wizard 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 mppds Next gt Cancel MikroElektronika 693 mikroPascal PRO for dsPICSO 33 and PIC24 Step Four Add project f
363. e flags related to reception of ECAN message If a particular bit is set then corresponding meaning is TRUE or else it will be FALSE MikroElektronika 310 mikroPascal PRO for dsPIC30 33 and PIC24 const ECAN RX FILTER BITS word 0x000F Use this to access filter bits ECAN RX FILTER 0 word 0x00 filter0 match ECAN RX FILTER 1 word 0x01 filteri match ECAN RX FILTER 2 word 0x02 Li ECAN RX FILTER 3 word 0x03 ECAN RX FILTER 4 word 0x04 ECAN RX FILTER 5 word 0x05 ECAN RX FILTER 6 word 0x06 ECAN RX FILTER 7 word 0x07 ECAN RX FILTER 8 word 0x08 ECAN RX FILTER 9 word 0x09 ECAN RX FILTER 10 word 0x0A ECAN RX FILTER 11 word 0x0B ECAN RX FILTER 12 word 0x0C ECAN RX FILTER 13 word 0x0D ECAN RX FILTER 14 word 0x0E Ld ECAN RX FILTER 15 word 0x0F filter15 match _ECAN RX OVERFLOW word 0x10 Set if Overflowed else cleared _ECAN RX _ INVALID MSG word 0x20 Set if invalid else cleared _ECAN RX_XTD_ FRAME word 0x40 Set if XTD message else cleared _ECAN RX_RTR_FRAME word 0x80 Set if RTR message else cleared You may use bitwise and to extract received message status For example Copy Code To Clipboard if MsgFlag and _ECAN RX OVERFLOW lt gt 0 then begin Receiver overflow has occurred We have lost our previous message end
364. e 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 dsPIC30 33 and PIC24 installation folder or probe the Code Assistant for specific letters CtrltSpace in the Code Editor Predefined project level defines mikroPascal PRO for dsPIC30 33 and PIC24 provides several 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 30F4013 SENDIF Other predefined project level defines are SIFDEF P30 S ENDIF SIFDEF P33 SENDIF SIFDEF P24 SENDIF SIFDEF MIKRO ICD ENDIF Related topics Project Level Defines 138 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Accessing Individual Bits The mikroPascal PRO for dsPIC30 33 and PIC24 allows you to access individual bits of 16 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 2 sbit at SR B1 To access this bit in your code by its name you can write something like this Clear Zero Bit SR Z OF In this way if Zero bit changes its position in the reg
365. e increase current dutyl greater then possible pwm_period2 value current_dutyl 0 reset 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 20 Dec current_dutyl decrement current _dutyl if current _dutyl gt pwm_period2 then if we decrease current dutyl greater then possible pwm period1 value overflow current dutyl pwm _period2 set current duty to max possible value PWM Set Duty current_dutyl 2 end Delay ms 5 slow down change pace a little end end 434 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 HW Connection vec OSCILLATOR UL PWM demonstration PWM Motor Control Library The PWM Motor Control module is available with a number of dsPIC30 33 MCUs mikroPascal PRO for dsPIC30 33 and PIC24 provides a library which simplifies using the PWM Motor Control module Important Number of PWM modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library PWM library routines require you to specify the module you want to use To use the desired PWM module simply change the letter x in the routine prototype for a number from 1 to 2 Library Routines PWMx_Mc_Init PWMx_Mc_Set_Duty PWMx_Mc_Start PWMx_Mc_Stop MikroElektronika 435 mikroPascal PRO for dsPIC30 33 and PIC
366. e initialized See SPI_T6963C_Config routine set bits 0 and 1 on control port SPI_T6963C_setBit 0x03 Notes Noe Oo 556 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_T6963C_negBit Prototype procedure SPI T6963C_ negBit b byte 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 Toshiba Glcd module needs to be initialized See SPI_T6963C_Config routine negate bits 0 and 1 on control port SPI_T6963C_negBit 0x03 SPI_T6963C_displayGrPanel Rems Noting SSCS erm Sa ESEE disptayctorentay O SPI T6963C_displayGrPanel 1 SPI_T6963C_displayTxtPanel Rems Nothing OSS Toshiba Glcd module needs to be initialized See SP _T6963C_Config routine display text panel 1 SPI_T6963C_displayTxtPanel 1 Notes Nowe SOS MikroElektronika 997 mikroPascal PRO for dsPIC30 33 and PIC24 SPI_T6963C_setGrPanel cal eae will be eee at this graphic panel Reems Nong SS Toshiba Glcd module needs to be initialized See SPI_T6963C_Config routine set graphic panel 1 as current graphic panel SPI T6963C secGrPanel 1 SPI_T6963C_setTxtPanel text operations will be ee at this text panel ewe png o ooo set text panel 1 as text aes SPI_T6963C_setTxtPanel Notes None eee SPI_T6963C_panel Fill Rems Nothing SSS Toshiba Gicd module needs to be initialized
367. e is stable message 21 chars long two spaces 2 chars long Or letter 1 char long bad null string O 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 Splicing MikroElektronika 184 mikroPascal PRO for dsPICSO 33 and PIC24 Keywords Keywords are special purpose words which cannot 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 w0 in Editor or refer to Predefined Globals and Constants Here is the alphabetical listing of keywords in mikroPascal PRO for dsPIC30 33 and PIC24 absolute abstract and array as asm assembler at automated bdata begin PiE case cdecl class code compact Const constructor contains data default deprecated destructor dpspid dispinterface giy dma do downto dynamic end except Export exports external far file final finalization finally for T1CON etc Probe the Code Assistant for specific letters Ctrl Space 185 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 forward goto helper idata gt 25 ilevel implem
368. e 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 0p 2J 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 0 white 1 black and 2 inverts each dot Glcd needs to be initialized see Glcd_Init routine Draw a line between dots 0 0 and 20 30 Gled Line 0 0 20 30 1 7 300 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Glcd_V_Line Prototype procedure Gled V Line y start y end x pos color byte 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
369. e prompted to enter new name Active Comments Editor Select Active Comment activeComment Active Comment Actions New Rename Enter new Active Comment Name activeCommentRename Properties S Attributes Url Image File 3 Events OnLeftClick Alt OpenUrl OnRightc OnDbIClick None OnMouseOver PreviewImage www mikroe com Easy_GSM_GPRS ipa lick None Add Image To Project Add File To Project MikroElektronika 104 mikroPascal PRO for dsPIC30 33 and PIC24 Now click again Rename button Now you have renamed your Active Comment in such a way that its filename source code name are changed Vs 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 105 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Export Project This option is very convenient and finds its use in relocating your projects from 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 f
370. e 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 lst gt longint 12111 const ID 2nd longint 3 var Can Init Flags Can Send Flags Can Rcv_ Flags word can flags Rx Data _Len word received data length in bytes RxTx_ Data array 8 of byte can rx tx data buffer Msg Revd 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 LATF1 bit CanSpi Rst_ Direction sbit at TRISF1 bit End CANSPI module connections begin ADPCFG 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 Z 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 Can_Init Flags _CANSPI_ CONFIG SAMPLE THRICE and Form value to be used S SPI CONFIG PHSEG2 PRG ON and with CANSPIInit CANSPI CONFIG XTD MSG and S S PI CONFIG DBL BUFFER ON and PI CONFIG VALID XTD MSG Initialize SPI1 module SPI1 Init CANSPIInitialize 1 3 3 3 1 Can_ Init Flags initialize external CANSPI module CANSPISetOperationMode _CAN
371. e switching verification request If WAIT 0 the call is non blocking The function does not verify if the ECAN module is switched to requested mode or not Caller must use ECANxGetOperationMode to verify correct operation mode before performing mode specific operation If WAIT 0 the call is blocking the function won t return until the requested mode is set and no additional verification is necessary Nothing Requires The ECAN routines are supported only by MCUs with the ECAN module Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus set the ECAN1 module into configuration mode wait inside ECAN1SetOperationMode until this mode is set ECAN1SetOperationMode _ECAN MODE CONFIG OxFF ma ECAN library routine require you to specify the module you want to use To select the desired ECAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of ECAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 299 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 ECANxGetOperationMode Prototype Prototype function ECANxGetOperationMode wordy ssss SsSCid function ECANxGetOperationMode word sssi is s s rY word Description The function returns current operation mode of the ECAN module See ECAN_OP_MODE constants or device data
372. e 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 gt Port Expander SPI Led8 7 L gt Led 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 539 mikroPascal PRO for dsPICSO 33 and PIC24 SPI_Lcd8_Config 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 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 LATF1 bit var SPExpanderRST Direction sbit at TRISFO bit var SPExpanderCS Direction sbit at TRISF1 bit En
373. e_1 statement_1 value_n statement_n else default statement end 225 MikroElektronika mikroPascal PRO for dsPICSO 33 and PIC24 selector isan 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 then default statement in the else clause if there is some is executed Here s a simple example of the case statement case operator of yr gt result nl n2 result nl n2 wp e yesult ni n2 t os 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 Ov opmode 0 1 2 3 4 opmode 1 5p Cp a opmode 2 end In mikroPascal PRO for dsPIC30 33 and PIC24 values in the case statement can be variables too case byte variable of byte varl opmode 0 this will be compiled correctly byte varz opmode 1 avoid this case compiler will parse
374. ecord 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 Get a Record via function call MyCircle CenterX DefineCircle 100 200 30 CenterX 20 Access a Record field via function call Niceccsesies at aineciaeka aerated inceniecied ass red 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 First 2 3 result tmp c end function First a b word word begin 201 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 result a b end begin Volume Second 4 end Functions reentrancy Functions reentrancy is allowed Remember that the dsPIC30 33 and PIC24 have memory limitations that can vary betwe
375. ect 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 LATF1 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 7 ae Initialize SPI module used with PortExpander SPI Gled Init MikroElektronika 519 mikroPascal PRO for dsPIC30 33 and PIC24 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 pos specifies the Glcd side values from 0 to 63 specify the left side 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 p
376. ectives IFDEF IFNDEF ELSE and ENDIF Conditional compilation is carried out by the IFDEF and IFNDEF directives IFDEF tests whether a flag is currently defined and IFNDEF if the flag is not defined i e whether a previous DEF INE directive has been processed for that flag and is still in force 233 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Directives 1FDEF and 1FNDEF are terminated with the ENDIF directive and can have an optional ELSE clause SIFDEF flag lt block of code gt SELSE lt alternate block of code gt SENDIF First 1FDEF checks if flag is defined by means of DEFINE If so only lt block of code gt will be compiled Otherwise lt alternate block of code gt will be compiled ENDIF 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 processed section can contain further conditional clauses nested to any depth each I1FDEF must be matched with a closing ENDIF Here is an example Uncomment the appropriate flag for your application SDEFINE resolution10 SDEFINE resolution12 SIFDEF resolution10 lt code specific to 10 bit resolution gt SELSE SIFDEF resolution12 lt code specific to 12 bit resolution gt SELSE lt default code gt SENDIF SENDIF
377. ed as a PIC with digital signal processing capabilities These are Microchip s first inherent 16 bit data microcontrollers They build on the PIC s existing strengths by offering hardware MAC multiply accumulate barrel shifting bit reversal 16x16 bit multiplication and other digital signal processing operations Having a wide range of application and being also prized for efficiency the dsPIC30 33 and PIC24 MCUs are a natural choice for developing embedded systems mikroPascal PRO for dsPIC30 33 and PIC24 provides a successful match featuring highly advanced IDE broad set of hardware libraries comprehensive documentation and plenty of ready to run examples Features mikroPascal PRO for dsPIC30 33 and PIC24 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 dsPIC30 33 and PIC24 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 mikrolCD In Circuit Debugger Real Time debugging tool to monitor program execution on the hardware level Inspect program flow and debu
378. ed 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 mcl files compiled with or without SSA enabled are fully compatible and can be used and mixed without any restrictions except function pointers 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 MikroElektronika 161 mikroPascal PRO for dsPICSO 33 and PIC24 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 on
379. ed in the place of the call so the call doesn t count against the nested call limit Parameters number input value Returns Returns the highest byte of number bits 24 31 Arguments must be variable of scalar type i e Arithmetic Types and Pointers 0x12345678 tmp Highest d Equals 0x12 148 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 LoWord Prototype function LoWord val longint word Description The function returns low word of val The function does not interpret bit patterns of vai it merely returns 16 bits as found in register Parameters val input value Returns Low word of val bits 15 0 0x12345678 tmp LoWord d Equals 0x5678 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 Returns High word of val bits 31 16 0x12345678 tmp HiWord d Equals 0x1234 MikroElektronika 149 mikroPascal PRO for dsPICSO 33 and PIC24 Inc procedure Inc var par longint fRetums nonn OOOO SSS p 4 Inc p p is now 5 Dec procedure Dec var par longint Rems Nong SSCS p 4 Dec p ZZ p is now 3 Chr Prototype function Chr code_ byte char Description Function returns a character associated wi
380. ed to refer to the data memory rx data code sfr xdata ydata and dma Related topics Accessing individual bits SFRs Memory type specifiers dsPIC Memory Type Qualifiers MikroElektronika 169 mikroPascal PRO for dsPICSO 33 and PIC24 Memory Type Specifiers The mikroPascal PRO for dsPIC30 33 and PIC24 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 The following memory type specifiers can be used code data FX Iki xdata ydata dma code puts txt in program memory const txt ENTER PARAMETER code Description This memory specifier is used when storing variable to the Data RAM puts data_buffer in data ram var data buffer char data Description This memory specifier allows variable to be stored in the working registers space WREGO WREG 15 aoe e ane y in Rx space eae le y chat 2x sfr Description 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 170 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 xdata This memory specifier allows user to access X Data memory space Example var y char xdata puts x in xdata memory spac
381. edefined Globals and Constants Accessing Individual Bits Interrupts Linker Directives Built in Routines Code Optimization Common Object File Format COFF MikroElektronika 136 mikroPascal PRO for dsPIC30 33 and PIC24 GOTO Table If a certain routine is allocated on the address higher than 64kB and can not be accessed directly a GOTO table is created just after the Interrupt Vector Table to enable this routine call GOTO table comprises of addresses of those routines that are allocated on the addresses higher than 64kB So whenever a call is made to a routine which is not directly accessible it jumps to an assigned GOTO table block which contains address of a desired routine From there a GOTO call is generated to that address and the routine is executed Interrupt Vector Table Goto Table Flash Program Memory User Program Addresses higher than 64kB x 137 MikroElektronika mikroPascal PRO for dsPIC30 33 and PIC24 Predefined Globals and Constants To facilitate dsPIC30 33 and PIC24 programming the mikroPascal PRO for dsPIC30 33 and PIC24 implements a number of predefined globals and constants All dsPIC30 33 and PIC24 SFRs are implicitly declared as global variables of volatile word These identifiers have an external linkage and are visible in the entire project When creating a project the mikroPascal PRO for dsPIC30 33 and PIC24 will include an appropriate mpas fil
382. edure 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_0 register adressing slew rate enabled ModuleAddress Port Expander hardware address see schematic at the bottom of this page Requires Global variables SPExpanderCs SPExpanderRST SPExpanderCs _ Chip Select line Reset line 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 SPILI Tart Initialize SPI module used with PortExpander Expander __ Tne 0 4 Initialize Port Expander MikroElektronika At mikroPascal PRO for dsPICSO 33 and PIC24 Expander_Init_Advanced Prototype procedure Expander Init _Advanced var rstPort byte rstPin byte haen byte Description Initializes Port Expander using SPI communication Parameters rst Port Port Expander s res
383. edure SSA_Test this example is consisted of 3 asm instructions Example mpas 34 if y k then 0x0100 0x45000B ADD W10 W11 WO 160 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 0x0102 0x320001 BRA Z L SSA2 L SSA Testo Example mpas 36 nop 0x0104 0x000000 NOP Without SSA enabled sub procedure SSA Test this example is consisted of 5 asm instructions Example mpas 34 if yt k then 0x0102 0x97B8CE MOV W14 8 W1 0x0104 0x57006A SUB W14 10 WO 0x0106 0x408010 ADD W1 WO WO 0x0108 0x320001 BRA Z L SSA2 L SSA Test Example mpas 36 nop 0x010A 0x000000 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 functionl parameters are passed as funct ion2 parameters then parameter order should remain the same procedure f2 a integer b integer procedure fl x integer y integer xoutine calil 2 AV X gt a and y gt b 1 to 1 and 2 to 2 is far more efficient than 2 y x 7 ZZ y gt a and xb 1 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 reserv
384. ee a ea so an J ys eem o renr N Cm A pa w amn DO Foa lt bies sa Dh Smu b wm 0 sanaaa Sonae aaen B oon ed e reer nen wee hers r z se gt dati J ieee wee ee we o aan gt e LT h 2 TAZZI J sr aem apia Oae gt pene yee A cae aoe 0 me ree ooo mm f rue am y anse wet so ane om o7 gt ee te l a oe bakas _ mser eee 4 poy _ mou E int See Ae a 5 m eo epee S aim a _ X n e m gt CISC A iro ron as Doe am m X E La s Sa z a o e a armeg 1am TN ee anapi am oo j a rm ne ee ee ete e om gt we D b W Kea n a gt epee b p e o 2 oo a e mee as re tte me aap eseure 6S Gm we ig gt E ELE TS eos uma me a fe sete the tne 9 tee aame em m gt gt D mem bu os I asm e e papaa sra or u u 8 N am san se tee wan tan C gt ema amore 4 oo te oe M eee om depois B P Son o an oa Owe ow Bee lt vo lt ur eye SS SS sias D on ae enemys i aes lt een e u O aal yl OO eee a nn mikroPascal PRO for dsPIC30 33 and PIC24 IDE MikroElektronika 30 mikroPascal PRO for dsPICSO 33 and PIC24 Introduction to mikroPascal PRO for dsPIC30 33 and PIC24 dsPIC30 33 and PIC24 and mikroPascal PRO for dsPIC30 33 and PIC24 fit together well dsPIC is design
385. eet before utilizing this library MikroElektronika 306 mikroPascal PRO for dsPICSO 33 and PIC24 ECANxRead Prototype D Requires function ECANxRead var id longint var data array 8 of byte var dataLen word var ECAN RX MSG FLAGS word word 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 pointed by the id pointer Message data is retrieved and stored to array pointed by the data pointer Message length is retrieved and stored to location pointed by the dataLen pointer Message flags are retrieved and stored to location pointed by the ECAN RX MSG FLAGS pointer id message identifier address data an array of bytes up to 8 bytes in length dataLen data length address ECAN RX MSG FLAGS message flags address For message receive flags format refer to the ECAN RX MSG FLAGS constants See ECAN_RX_MSG_FLAGS constants 0 if none of Receive Buffers is full OxFFFF if at least one of Receive Buffers is full message received The ECAN routines are supported only by MCUs with the ECAN module Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus The ECAN module must be in a mode in which receiving is possible See ECANxSetOperationMode check the ECAN1 module for received messages If any was received do something var msg _rcvd rx flags data_len
386. eft 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 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 F6963C Partialimage 10 12 10 15 16 32 image Use the integrated Glcd Bitmap Editor menu option Tools gt Gled 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 4 einstein 119 draw a sprite If px and sx parameters are not multiples
387. eger 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 257 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 Example TFT Rectangle 20 20 219 107 MikroElektronika 601 mikroPascal PRO for dsPICSO 33 and PIC24 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 roun
388. egin Sound Play 1046 end procedure ToneE begin Sound Play 1318 end procedure Melody2 var counte begin for co begin To To To r r byte unter neA neC neE 9 Z2a0 3 250 250 3 a Tone3 7 7 n n di tz del Tone3 Tone3 Tone3 a Tone2 74 Frequency Frequency Frequency Plays the P Tonel 659Hz duration 250ms 698Hz duration 250ms 784Hz duration 250ms melody Yellow house Tones used in Melody2 function Plays Melody2 downto 1 do 464 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 end end begin ADPCFG OxFFFF Configure AN pins as digital I O TRISB OxF8 Configure RB7 RB3 as input Sound_Init PORTD 3 Sound _Play 880 1000 while TRUE do endless loop begin if Button PORTB 7 1 1 then If PORTB 7 is pressed play Tonel begin Tonel while RB7 bit lt gt 0 do nop Wait for button to be released end if Button PORTB 6 1 1 then If PORTB 6 is pressed play Tonel begin Tone2 while RB6 bit lt gt 0 do nop Wait for button to be released end if Button PORTB 5 1 1 then If PORTB 5 is pressed play Tonel begin Tone3 while RB5 bit lt gt 0 do nop Wait for button to be released end if Button PORTB 4 1 1 then If PORTB 4 is pressed play Tonel begin Melody2
389. el 559 SPI_T6963C_displayTxtPanel 559 SPI_T6963C_setGrPanel 560 SPI_T6963C_setTxtPanel 560 SPI_T6963C_panelFill 560 SPI_T6963C_grFill 561 SPI_T6963C_txtFill 561 SPI_T6963C_cursor_height 561 SPI_T6963C_graphics 562 SPI_T6963C_text 562 SPI_T6963C_cursor 562 SPI_T6963C_cursor_blink 563 Library Example 563 HW Connection 567 T6963C Graphic Lcd Library 568 Library Dependency Tree 568 External dependencies of T6963C Graphic Lcd Library 569 Library Routines 570 T6963C_init 571 T6963C_writeData 572 T6963C_writeCommand 573 T6963C_setPtr 573 T6963C_waitReady 573 T6963C_fill 574 T6963C_dot 574 T6963C_write_char 575 T6963C_write_text 576 T6963C_line 576 T6963C_rectangle 577 T6963C_rectangle_round_edges 577 T6963C_rectangle_round_edges fill 578 T6963C_box 578 T6963C_circle 578 T6963C_circle_fill 579 T6963C_image 579 T6963C_Partiallmage 580 T6963C_ sprite 580 T6963C_set_cursor 581 T6963C_displayGrPanel 581 T6963C_displayTxtPanel 581 T6963C_setGrPanel 582 T6963C_setTxtPanel 582 T6963C_panel Fill 582 T6963C_grFill 583 MikroElektronika 22 mikroPascal PRO for dsPICSO 33 and PIC24 T6963C_txtFill 583 T6963C_cursor_height 583 T6963C_graphics 584 T6963C_text 584 T6963C_cursor 584 T6963C_cursor_blink 585 Library Example 585 HW Connection 589 TFT Library 590 External dependencies of TFT Library 590 Library Routines 591 TFT_Init 592 TFT_Set_Index 593 TFT_Write_ Command 593 TFT_Write_Data 593 TFT_Set_Active 594 TFT_Set_Font 595
390. ello world on the position 10 inside the page 2 SPE Gled Write Text Hello world 10 2 1 7 Notes For x axis and page layout explanation see schematic at the bottom of this page 928 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 dsPIC30 33 and PIC24 pointer to const and pointer to RAM equivalency Glcd needs to be initialized for SPI communication see SPI_Glcd_lInit routine Draw image my image on Glcd SPI_Glcd_Image my image Use the mikroPascal PRO for dsPIC30 33 and PIC24 integrated Glcd Bitmap Editor Tools gt Gled 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 locations 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 displ
391. elp Toolbar 51 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 mikroPascal PRO for dsPIC30 33 and PIC24 IDE IDE Overview The mikroPascal PRO for dsPIC30 33 and PIC24 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 ee i gee ort LEETE PET EE Hihihi opigierkie gogzgak t fet AFLFEFEFEFE teh i EE Tarere if ESE i BG 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 information messages and errors detected 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 Like in any modern Windows application you may customize the layout of mikroPascal PRO for dsPIC30 33 and PIC24 t
392. ematic at the bottom of this page Data data to be written Nothing Requires Port Expander must be initialized See Expander_lInit 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 Description The function writes byte to Port Expander s PortB Parameters ModulecAddress Port Expander hardware address see schematic at the bottom of this page Data 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 471 mikroPascal PRO for dsPICSO 33 and PIC24 Expander_Write_PortAB Prototype Description Parameters Requires Expander _ Prototype Description Parameters procedure Expander Write PortAB ModuleAddress byte Data word The function writes word to Port Expander s ports ModuleAddress Port Expander hardware address see schematic a
393. ements in creating more complex user defined types The derived types include arrays pointers records 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 than 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 t ype and can be accessed by specifying array name followed by element s index within brackets MikroElektronika 203 mikroPascal PRO for dsPICSO 33 and PIC24 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 7 The number of assigned values must not exceed the specified length The opposite is possible when the tra
394. ements time based activities so interrupts need to be disabled when using it 460 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 TimerliInt org IVT_ADDR_T1IINTERRUPT begin counter 0 if counter gt 20 then begin Soft UART Break counter 0 reset counter end else Inc counter increment counter TIIF bit 0 Clear Timerl overflow interrupt flag end begin if Soft_UART Init PORTF 2 3 14400 0 0 Soft UART Write 0x55 try Soft _UART Read with blocking prevention mechanism IPCO IPCO or 0x1000 Interrupt priority level 1 TLIE bit i 1 Enable Timerl interrupts TICON 0x8030 Timerl ON internal clock FCY prescaler 1 256 datal Soft UART Read amp error TIIE bit 0 Disable Timerl interrupts end The Software UART library implements time based activities so interrupts need to be disabled when using it MikroElektronika 461 mikroPascal PRO for dsPICSO 33 and PIC24 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 dsPIC30 33 and
395. emory Library This library provides routines for accessing microcontroller s internal Flash memory On the dsPIC30 33 and PIC24 Flash memory is mapped to address space 3 2 which means that every 3 consecutive bytes of Flash have 2 consecutive address locations available That is why mikroE s library allows data to be written to flash in two ways regular and compact In the regular mode which is used for word 16 bit variables the 3rd un addressable flash memory byte remains unused In the compact mode which can be used for 1 byte sized variables arrays all flash bytes are being used All dsPIC30 33 and PIC24 MCUs use the RTSP module to perform Read Erase Write operations on Flash memory This together with the internal structure of the Flash imposes certain rules to be followed when working with Flash memory dsPIC30 Erasing can be done only in 32 instructions 64 addresses 96 bytes memory blocks This means that the block start address should be a multiply of 64 i e have 6 lower bits set to zero Data is read and written in 4 instructions 8 addresses 12 bytes blocks This means that the block start address should be a multiply of 8 i e have 3 lower bits set to zero On the dsPIC30s 2 address locations are assigned on every 3 bytes of flash program memory Due to this specific and non one to one address mapping the mikroPascal PRO for dsPIC30 33 and PIC24 offers two sets of Flash handl
396. en purchased and installed license key 718 have bought license for the older version do have to pay license for the new version of the com piler 719 Do your compilers work on Windows Vista Windows 7 719 What does this function procedure routine do 719 try to compile one of the provided examples and nothing happens what is the problem 719 Can get your library sources need to provide all sources with my project 719 Can use code developed in your compilers in commercial purposes Are there some limitations 719 Why does an example provided with your compilers doesn t work 719 Your example works if use the same MCU you did but how to make it work for another MCU 719 need this project finished can you help me 720 Do you have some discount on your compilers development systems for students professors 720 have a question about your compilers which is not listed here Where can find an answer 720 29 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 CHAPTER 1 INTRODUCTION mikroPascal PRO for dsPIC30 33 and PIC 24 is a powerful feature rich development tool for the dsPIC30 33 and PIC24 microcontrollers It is designed to provide the programmer with the easiest possible solution to developing applications for embedded systems without compromising performance or control eo i Lee See es be Dru eect Sons Me gt 2 Be ee a oe eS ee a re cod aor oe 4 gt e
397. en 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 illegal assignments are trapped mikroPascal PRO for dsPIC30 33 and PIC24 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 202 mikoPascal PRO for dsPIC30 33 and PIC24 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 dsPIC30 33 and PIC24 has 16 bits Here is an overview of simple types in mikroPascal PRO for dsPIC30 33 and PIC24 S ES short 127 128 longint 32 bit 2147483648 2147483647 real 32 bit 1 17549435082 10 6 80564774407 10 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 el
398. ends her end MikroElektronika 143 mikroPascal PRO for dsPICSO 33 and PIC24 Linker Directives mikroPascal PRO for dsPIC30 33 and PIC24 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 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 0x32 var x word absolute 0x32 Variable y will occupy 2 words at addresses 0x34 and 0x36 var y longint absolute 0x34 Be careful when using absolute directive as you may overlap two variables by accident For example Variable i will occupy 1 word at address 0x42 var i word absolute 0x42 Variable will occupy 2 words at 0x40 and 0x42 thus changing i changes jj at the same time and vice versa var jj longint absolute 0x40 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 0x800 const MONTHS array 1 12 of byte 31 28 31 30 31 30 31 31
399. ent orientation Left to right gradient orientation Top to bottom gradient orientation gradient color from sets the starting gradient color CL_BLACK Black color MikroElektronika 599 mikroPascal PRO for dsPIC30 33 and PIC24 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 yl 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 initialized See the TFT_Init routine Example TFT Line 0 0 239 127 600 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 TFT H Line 10 50 20 TFT_V_Line Prototype procedure TFT V_Line y start y_end x_pos int
400. entation implements im index inherited Initial igativom inline interface LO is label library message mod name near a nodefault HO object OF on operator OF Org out overload override package packed pascal pdata platform private procedure program property protected public published raise read readonly record register MikroElektronika 186 mikroPascal PRO for dsPIC30 33 and PIC24 reintroduce repeat requires TX safecall sbit sealed BEE sir Shi shir small stdeall stored SCFing threadvar Ee try type unit until uses var Virtual volatile while with write writeonly xdata xor ydata Also mikroPascal PRO for dsPIC30 33 and PIC24 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 dsPIC30 33 and PIC24 Libraries 187 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 with the me
401. ents 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 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 146 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 Returns Lowest 8 bits byte of number bits 7 0 Arguments must be variable of scalar type i e Arithmetic Types and Pointers d 0x12345678 tmp Lo d Equals 0x78 Prototype function Hi number long
402. equests return also HTML main page Main program code program HTTP Demo AP a ee Ei ee A EB ee RAM variables 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 LATFl 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 my IpAddr array 4 of byte my IP address MikroElektronika 491 mikroPascal PRO for dsPIC30 33 and PIC24 gwlipAddr array 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 LP FEREEELE TERETE ENERET EAEC ENNEA ESET AERERERE EERE LEERY AEH ROM constant strings const httpHeader string 30 HTTP 1 1 200 OK 10 Content type f BTTP 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 my const indexPa
403. er that comes after begin bitMask 0 if isdigit getRequest 6 lt gt 0 then if 0 lt bit number lt 9 bits 8 amp 9 does not exist but does not matter begin bitMask getRequest 6 0 convert ASCII to integer bitMask 1 shl bitMask create bit mask PORTD PORTD xor bitMask toggle PORTD with xor operator end end if result 0 then what do to by default begin result SPI Ethernet _putConstString httpHeader HTTP header result result SPI Ethernet _putConstString httpMimeTypeHTML with HTML MIME type result result SPI Ethernet _putConstString indexPage HTML page first part result result SPI_Ethernet_putConstString indexPageZ2 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 g MikroElektronika 495 mikroPascal PRO for dsPIC30 33 and PIC24 function SPI Ethernet UserUDP var remoteHost array 4 of byte remotePort destPort reqlLength word var flags
404. ering 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 result 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 dsPIC specifics mikroPascal PRO for dsPIC30 33 and PIC24 specifics Memory type specifiers MikroElektronika 159 mikroPascal PRO for dsPICSO 33 and PIC24 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
405. es declarations procedure procedure name parameter list local declarations begin end functions declarations function function name parameter list return type local declarations begin end J BK RK RRR AR E A AA A Ok Program body J KR KR KR AR AR AR A A A oo ak A ak k k begin write your code here end 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 KR KR KR AR AR AR a AR A kk ak k k Interface globals J KR KR KR AR AR AR AA A Ak Ok constants declarations const types declarations type variables declarations var Name Name2 type absolute 0x123 external volatile register sfr procedures prototypes procedure procedure name var const ParamName jJtype var const ParamName2 ParamName3 type 191 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 functions prototypes function function _name var const ParamName type var const ParamName2 ParamName3 jJtype type J BK RK RAR AR AR A AR A E A a e E e a e aE e ak E aE k ak k ak A k k k Implementation J BRR KR AR AR AR e AA A A A E A a A aE e k k a k ak k E e k k k implementation constants declarations const types
406. escription 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 nearestiniegen SSCS example clk Clock OOOO Moes None Ooo Get_Fosc_kHz PRetums Decean O oS example clk Gen Fone OOOO Get Fosc 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 s clock per cycle rounded to the nearest integer var clk per cyc word clk per cyc i Get Fose Per Cyec MikroElektronika 155 mikroPascal PRO for dsPIC30 33 and PIC24 Reset Rets Nothing OOOO SS Example Reset Resets the MCU Moes None ClrWat Rems Noting OOOO fexample _ clenat i 77 Clears mor OOOO Moes Noe ooo 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 serv
407. essage receiving fil data 4 is set to 255 Tne ent if dat 5 lt gt 0 then if an error detected signal it PORTD OxAA by setting portd to OxAA if dat 4 lt gt 0 then if message received successfully begin cnt 0 dat 4 0 clear message received flag j dat 3 for i 1 to dat 3 do show data on PORTB PORTB dat i 1 dat 0 dat 0 1 send back to master Delay ms 1 RS485Master Send dat 1 160 end if cnt gt 100000 then if in 100000 poll cycles the answer begin Inc PORTD was not detected signal ent i 0 eA failure of send messag RS485Master Send dat 1 160 if PORTD gt 10 then if sending failed 10 times begin RS485Master Send dat 1 50 J send message on broadcast address end end end end Copy Code To Clipboard program RS485 Slave Example var dat array 20 of byte buffer for receving sending messages Ly J e byte 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 org IVT_ADDR_U2RXINTERRUPT begin RS485Slave Receive dat U2RXIF bit 0 ensure interrupt not pending end begin ADPCFG OxFFFF MikroElektronika 445 mikroPascal PRO for dsPICSO 33 and PIC24 PORTB PORTD TRISB TRISD oooO UART2 Init 9600 Delay _ms 100
408. esses 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 end end HW Connection 498 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 ENC243600 meets all of the IEEE 802 3 specifications applicable to 10Base T and 100Base TX Ethernet It incorporates 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 dsPIC30 33 and PIC24 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 dsPIC30 33 and PIC24 should be clocked by ENC24J600 clock
409. et port rst Pin Port Expander s reset pin haen Port Expander s hardware address Nothing 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 LATFO bit sbit SPExpanderCS at LATF1 bit sbit SPExpanderRST Direction at TRISFO bit sbit SPExpanderCS Direction at TRISF1 bit End Port Expander module connections If Port Expander Library uses SPI1 module SPIL Inte 7 Initialize SPI1 module used with PortExpander Expander Init _Advanced PORTB 0 0 Initialize Port Expander Expander_Read_Byte Prototype function Expander Read Byte ModuleAddress RegAddress byte byte Description The function reads byte from Port Expander Parameters ModulcAddress Port Expander hardware address see schematic at the bottom of this page RegAddress Port Expander s internal register address Port Expander must be initialized See Expander_Init Read a byte from Port Expander s register var read data byte Expander Read Byte 0 1 418 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Expander_Write_Byte Prototype procedure Exp
410. et_Page var data_ byte SPI Gled Write Data data_ SPI_Glcd_Fill Prototype procedure SPI Glcd_ Fill pattern byte Description Fills Glcd memory with byte pattern To clear the Glcd screen use SPI _Glcd Fill 0 To fill the screen completely use SPI Glcd Fill O0xFF pattern byte to fill Glcd memory with Nothing Glcd needs to be initialized for SP communication see SPI_Glcd_Init routine Clear screen SPI Glcd Fill 0 None MikroElektronika 521 mikroPascal PRO for dsPIC30 33 and PIC24 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_lInit 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 SPI_Glcd_Line Prototype procedure SPI 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
411. ewrite 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 MikroElektronika 388 mikroPascal PRO for dsPIC30 33 and PIC24 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 initialized 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 Mmc Chip Select Direction sbit at TRISFO bit MMC module connections Initialize the SPI module SPI1 Init _Advanced _ SPI MASTER SPI amp BIT SPI PRESCALE SI ESCALE PRI 64 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIV until MMC is initialized me Init Reinitialize the SPI module at higher speed change primary prescaler SPIL Init _Advanced _ SPI MASTER SPI 8 BIT SPI PRESCALE SEC 1 SPI PRESCALE PRI 4 SPI SS DISABLE SPI DATA SAMPLE MIDDL PI CLK IDLE HIGH SPI ACTIVE 2 IDL
412. expand collapse complex variables i e struct type variables strings etc by clicking the appropriate button or beside variable name Watch alues AS Ei Gh Select variable from list WREGL PC 0x00028E 9655 99 ms Double clicking a variable or clicking the 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 Edit Value PORTB DER Representation Dec O Hex O Bin O Float O Char L 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 124 mikroPascal PRO for dsPIC30 33 and PIC24 RAM Window The RAM Window is available from the drop down menu View gt Debug Windows gt 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 Led4bit mikroE ikroElektronike EasydsPIC4 lt Stopwatch Window The Software Simulator Stopwatch Window is available from th
413. ext 3X5 CAPITALS ONLY SPI Gled Write Text someText 60 2 2 Delay2s SPL Glod Set Font fontsax7 Dy Tr 32 7 someText 5x7 Font SPI Gled Write Text someText 5 4 2 Delay2s SPI Glcd Set Font FontSystem5x7 v2 5 7 someText 5x7 Font v2 SPI Gled Write Text someText 50 6 2 Delay2s SENDIF end end ip Lf ve 2i tip Lf 32 Clear Glced Choose font Write string Draw box Fill Gled Change font Write string Change font Write string Change font Write string Change font Write string 331 mikroPascal PRO for dsPIC30 33 and PIC24 HW Connection Left side Right side 7 X axis BER ELOYIIdSP SPI Glcd HW connection 932 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI Lcd Library The mikroPascal PRO for dsPIC30 33 and PIC24 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 dsPIC33 and PIC24 family MCUs be aware of their voltage incompatibility with certain number of Lcd modules So additional external power supply for these modules may be requ
414. f constants after the keyword const const constant name f 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 will assume string type MONTHS argay 1 12 of byte 31 28 31 30 31 20 31 31 30 31 30 31 7 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
415. f cycles between the lines where Software Simulator action has started and ended Watch Clock Cycles Time Current Count 2 103 943 273 105 20 s Delta 80 881 413 14044 07 ms Stopwatch _2 103 943 273 105197 16 ms Reset To Zero 80 MikroElektronika 132 mikroPascal PRO for dsPICSO 33 and PIC24 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 x Read EEPROM Write EEPROM FF FF FF FF FF FF FF FF FF FF FF FF FF FF o0 o0 o0 o0 o0 o0 o0 o0 o0 o0 00 an STATUS Idle 133 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Code Watch Window
416. f predefined math constants Library Routines acos asin atan atan2 ceil COS cosh eval_poly exp fabs floor frexp Idexp 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 gt 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 I1 2 and 1 2 inclusive gt asin 0 5 res 5 235987e 1 MikroElektronika 685 mikroPascal PRO for dsPIC30 33 and PIC24 atan Prototype function atan arg real real Description Function computes the arc tangent of parameter f that is the value whose tangent is The return value is in radians between M 2 and 1 2 Se atan 1 0 res 7 853982e 1 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 resul
417. finite impulse response FIR filter is a type of a digital filter whose impulse response the filter s response to a delta function is finite because it settles to zero in a finite number of sample intervals Library Routines FIR_Radix FIR_Radix Prototype function FIR Radix FilterOrder word ptrCoeffs longint BuffLength word ptrinput word Index word word This function applies FIR filter to ptrInput Parameters FilterOrder order of the filter 1 ptrCoeffs pointer to filter coefficients in program memory BuffLength number of input samples ptrinput pointer to input samples Index index of current sample N 1 coef k input N k k 0 with N buffer length k current index const BUFFFER SIZE 32 const FILTER ORDER 20 const COEFF B FILTER ORDER 1 of integer 0x0000 0x0048 0x0133 0x02D3 0x052B 0x0826 OxOBAO Ox0F62 0x1329 Ox1l6AA O0x199A Ox16AA 0x1329 Ox0F62 Ox0BAO 0x0826 0x052B 0x02D3 0x0133 0x0048 0x0000 i var input array BUFFFER SIZE of word ydata Input buffer inext word Input buffer index var CurrentValue word CurrentValue FIR Radix FILTER_ORDER 1 Filter order word COEFF B B coefficients of the filter BUFFFER_ SIZE Input buffer length word input Input buffer inext Current sample Notes Input samples must be in Y data space 636 MikroElektronika
418. 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 SP _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 _setUserHandlers TCPHandler TSPI_ Ethernet _UserTCP 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 request handler Nothing Requires SPI_Ethernet_UserTCP and SPI_Ethernet_UserUDP have to be previously defined SPI Ethernet _setUserHandlers SPI Ethernet _UserTCP 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 484 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_Ethernet_getlpAddress Prototype Prototype function SPI E
419. ftware C communication These routines are hardware independent and can be used with any MCU The Software I C library enables you to use MCU as Master in I C communication Multi master mode is not supported Important This library implements time based activities so interrupts need to be disabled when using Software C All Software C Library functions are blocking call functions they are waiting for 1 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 C library routine has its own counterpart in Hardware I C library except 12C Repeated Start Soft_I2C_Start is used instead of I12C_ Repeated Start Working clock frequency of the Software 1 C is 20kHz External dependencies of Software C Library The following variable must be defined in all Description projects using RS 485 Library P var Soft T2C Sel sbit Sfr r 7 Soft I C Clock line var Soft_I2C_ Scl sbit at RF3_ bit external Soft_I2C_Sd bit fxr r i Hae ear 22s S Soft 12C Data line var Soft I2C Sda sbit at RF2 bit external Soft I2C Scl Direction Direction of the Soft IPC var Soft_I2C_Scl_Direction sbit at external Clock pin TRISES bit Soft_I2C_ Sda Direction Direction of the Soft C var Soft _I2C_Sda_ Direction sbit at external Data pin TRISE
420. 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 function name is automatically created local variable that can be used for returning a value of a function mikroPascal PRO for dsPIC30 33 and PIC24 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 199 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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
421. g executable logic with the integrated Software Simulator Generate COFF Common Object File Format file for software and hardware debugging under Microchip s MPLAB software Use Single Static Assingment 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 dsPIC30 33 and PIC24 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 dsPIC30 33 and PIC24 microcontrollers read carefully the dsPIC Specifics chapter It might give you some useful information on the dsPIC30 33 and PIC24 constraints code portability and good programming practices If you are experienced in Pascal programming you will probably want to consult the mikroPascal PRO for dsPIC30 33 and PIC24 Specifics first For language issues you can always refer to the comprehensive Language Reference A complete list of included libraries is available in the mikroPascal PRO for dsPIC30 33 and PIC24 Libraries If you are not very experienced in Pascal programming don t panic mikroPascal PRO for dsPIC30 33 and PIC24 provides plenty of examples making it easy for you to go quickly
422. g position column number out _ char character to be written Lcd needs to be initialized for SP communication see SPI_Lcd8_Config routine Write character i at row 2 column 3 SPI LEJE Chr 2 3 SPI_Lod8_Chr_Cp delist Ls procedure SPI Lcd8 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_Lcd8_Config routine Print e at current cursor position WA Write character e at current cursor position SPY Leds Chr Cpe MikroElektronika 541 mikroPascal PRO for dsPICSO 33 and PIC24 SPI_Lcd8 Cmd Prototype procedure SPI Lcd8 Cmd out_char byte Sends command to Lcd out_ char command to be sent Lcd needs to be initialized for SPI communication see SPI_Lcd8_Config routine Clear Lcd display SPI Lcd8 Cmd LCD CLEAR Notes Predefined constants can be passed to the routine see Available SPI Lcd8 Commands Available SPI Lcd8 Commands Move cursor to the 3rd row Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected Shift display left without changing display data RAM _LCD_SHIFT_RIGHT Shift display right without changing display data RAM 042 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24
423. g signal The function configures Receiver pin After that the function performs synchronization procedure in Parameters None 0 if initialization and synchronization were successful 1 upon unsuccessful synchronization 255 upon user abort Requires Global variables MANRXPIN Receive line MANRXPIN Direction Direction of the receive pin must be defined before using this function Initialize Receiver var MANRXPIN sbit at RFO bit var MANRXPIN Direction sbit at TRISFO bit Man Receive Init In case of multiple persistent errors on reception the user should call this routine once again or Man_Synchro routine to enable synchronization MikroElektronika mikroPascal PRO for dsPICSO 33 and PIC24 Man_Receive Prototype function Man Receive var error word byte The function extracts one byte from incoming signal Parameters error error flag If signal format does not match the expected the error flag will be set to non zero Returns A byte read from the incoming signal To use this function the user must prepare the MCU for receiving See Man_Receive_lnit routines var data_ error word error 0 data 0 data_ Man Receive error if error lt gt 0 then begin error handling Man_Send_Init PRetums Nothing OSS Requires Global variables MANTXPIN Transmit line MANTXPIN Direction Direction of the transmit pin mus
424. gateway IP address DNS IP address when DHCP is not used Parameters ipMask IP subnet mask gwl pAddr gateway IP address dnsI pAddr DNS IP address Ethernet module has to be initialized See SPI_Ethernet_Init var ipMask array 4 of byte network mask for example 255 2592550 gwI p Addr array 4 of byte gateway router IP address dnsIpAddr array 4 of byte DNS server IP address gwIpAddr gwIpAddr gwiIpAddr gwIpAddr E 168 20 6 0 1 2 3 dnsIpAddr 0 dnsIpAddr 1 dnsIpAddr 2 dnsIpAddr 3 ipMas ipMas ipMas ipMas 0 SPI 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 487 mikroPascal PRO for dsPICSO 33 and PIC24 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 mbas file in the compiler s Uses folder Parameters ip IP address to be resolved tmax
425. ge string 761 lt meta http equiv refresh content 3 url http 192 168 20 60 gt 4 lt HTML gt lt HEAD gt lt HEAD gt lt BODY gt lt hl gt dsPIC ENC28J60 Mini Web Server lt hl1 gt lt a href gt Reload lt a gt lt script srce s gt lt script gt t lt table gt lt tr gt lt td valign top gt lt table border 1 style font size 20px font family terminal gt lt tr gt lt th colspan 2 gt ADC lt th gt lt tr gt lt tr gt lt td gt AN0 lt td gt lt td gt lt script gt document write ANO lt script gt lt td gt lt Eno lt tr gt lt td gt AN1 lt td gt lt td gt lt script gt document write AN1 lt script gt lt td gt lt tro lt table gt lt td gt lt td gt lt table border 1 style font size 20px font family terminal 7 S lt tr gt lt th colspan 2 gt PORTB lt th gt lt tr gt script gt War strjit stra 5 FOP LE2F2 lt 108 Itt 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 lt td bgcolor cccccc gt OFF strt lt td gt lt trs yE document write str lt Seripe gt const indexPage2 string 466 lt table gt lt td gt lt td gt lt table border 1 style font size 20px font family terminal gt lt tr gt lt th colspan 3 gt PORTD lt th gt
426. gin Spi Lced8 Cmd LCD SHIFT RIGHT Move _Delay end MikroElektronika 5A3 mikroPascal PRO for dsPIC30 33 and PIC24 while TRUE do begin for counter 0 to 6 do begin Spi Led8 Cmd LCD SHIFT LEFT Move_Delay end for counter 0 to 6 do begin Spi Led8 Cmd LCD SHIFT RIGHT Move _Delay end end end Endless loop Move text to the left 7 times Move text to the right 7 times oo 8 b 28 ELOVIIdSP SPI Lcd8 HW connection 044 mikoPascal PRO for dsPIC30 33 and PIC24 SPI T6963C Graphic Lcd Library The mikroPascal PRO for dsPIC30 33 and PIC24 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 suitable 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 dsPIC33 and PIC24 family MCUs be aware of their voltage incompatibility with certain number of T69
427. gister 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 MikroElektronika 139 mikroPascal PRO for dsPIC30 33 and PIC24 sbit type The mikroPascal PRO for dsP IC30 33 and PIC24 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 example 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 0 Please note that we used the keyword s r for declaration of Abit because we are pointing it to PORTB which is defined as a s fr 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 example 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 140 Mikr
428. gram FLASH memory including those that are not mapped to address space every 3rd byte Parameters address starting address of the FLASH memory block data_ data to be written Requires The block to be written to must be erased first either from the user code FLASH_Erase or during the programming of MCU Please note that block size that is to be erased is different from the one that can be written with this function var data_ string 192 data_ supercalifragillisticexpialidotiousABCDEFGHIJKLMNOPRSTUVWXY2Z1234 FLASH Write Compact 0x006400 data_ eer The user should take care of the address alignment see the explanation at the beginning of this page MikroElektronika 344 mikroPascal PRO for dsPICSO 33 and PIC24 FLASH_Read Prototype procedure FLASH eee longint var write to array 100 of word NoWords word Reads required number of words from the flash memory in the regular mode Parameters address starting address of the FLASH memory block to be read write to starting address of RAM buffer for storing read data NoWords number of words to be read Returns Address of RAM buffer for storing read data Rewires OOOO S var Buffer array 10 of word start address longint FLASH Write 0x006500 data start_address 0x6500 FLASH Read start_address Buffer The user should take care of the address alignment see the explanation at the beginning of
429. h address i The user should take care about the address alignment see the explanation at the beginning of this page 343 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 FLASH_Write Prototype procedure FLASH Write address longint var data_ array 64 of word Description Fills one writeable block of Flash memory 64 instructions 128 addresses 192 bytes in the regular mode Addresses and data are being mapped 1 on 1 This also means that 3rd byte of each program location remains unused Parameters address starting address of the FLASH memory block data _ data to be written Requires The block to be written to must be erased first either from the user code through the RTSP or during the programming of MCU Please note that block size that is to be erased is different from the one that can be written with this function var data array 64 of word Yk tr b Voi wa wt la r rd f FLASH Write 0x006500 data_ ae The user should take care about the address alignment see the explanation at the beginning of this page FLASH_Write_Compact Prototype procedure FLASH Write Compact address longint var data_ array 192 of byte Description Fills a portion of Flash memory 64 instructions 128 addresses 192 bytes using the dsPIC33 and PIC24s RTSP Run Time Self Programming module in the compact manner This method uses all available bytes of the pro
430. 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 gt 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 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 ade button 123 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 9 Remove button or press the Delete key It is possible to remove all variables from the Watch Values Window by clicking amp Removeall button You can also
431. he 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 mcl and mpas files in order specified by the search paths lf both mpas and mc1 files are found the compiler will check their dates and include the newer one in the project If the mpas file is newer than mc1 a new library will be written over the old one If only mpas file is found the compiler will create the mc1 file and include it in the project If only mc1 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 dsPIC30 33 and PIC24 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 MikroElektronika 194 mikro
432. hould be configured as input See Expander_Set_DirectionPortB and Expander_Set_DirectionPortAB routines Read a byt var read data Expander Set_ read_data Expander_Read_PortAB Prototype Prototype function Expa e from Port Expander s PORTB byte DirectionPortB 0 FF set expander s portb to be input Expander Read PortB 0 nder 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 fRetuns woma Cd Requires Port Expander must be initialized See Expander_lInit Port Expander s PortA and PortB should be configured as inputs See Expander_Set_DirectionPortA Expander_Set_Di Read a byt var read data Expander Set_ to be input rectionPortB and Expander_Set_DirectionPortAB routines e from Port Expander s PORTA and PORTB word DirectionPortaAB 0 FFFF set expander s porta and portb Expander Read PortAB 0 420 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Expander_Write_PortA Prototype procedure Expander Write PortA ModuleAddress Data byte The function writes byte to Port Expander s PortA Parameters ModulecAddress Port Expander hardware address see sch
433. hr memcmp memcpy memmove memset strcat strcat2 strchr strcmp strcpy strlen strncat strncpy strspn strncmp strstr strespn strpbrk strrchr Itrim rtrim strappendpre strappendsuf length memchr Prototype function memchr p byte ch byte n word word Description The function locates the first occurrence of the byte ch in the initial n words of memory area starting at the address p The function returns the offset of this occurrence 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 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 mikroPascal PRO for dsPICSO 33 and PIC24 memcmp Prototype function memcmp p1 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 Meaning pl less than p2 pl equal to p2 pl greater th
434. ht 10px cursor Shape block 1D13700 Set _Cursor 5 10 S1D13700 CURSOR_BLOCK 321 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 1D13700_Display_Cursor Prototype procedure S 1D13700 Display Cursor mode byte Description Displays cursor Parameters mode mode parameter Valid values Gled module needs to be initialized See the S1D13700_Init routine set cursor on 1D13700 Display Cursor 1D13700 CURSOR ON S1D13700_Write_Char Prototype procedure S1D13700 Write Char c char x word y word mode byte Nothing 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 1p13700 OVERLAY XOR In this mode the text and graphics data are combined via the logical exclusive OR S11 3900 OVERLAY AND The text and graphic data shown on display are combined via the logical AND function 1D13700 OVERLAY_OR Glcd module needs to be initialized See the S1D13700_Init routine ae 1D13700 Write Char A 22 23 1D13700 OVERLAY OR MikroElektronika 328 mikroPascal PRO for dsPICSO 33 and PIC2
435. ia SPI Send Low Byte temp valueDAC Store valueDAC 7 0 to temp 7 0 SPI1 Write temp Send low byte via SPI Chip Select 1 Deselect DAC chip end begin ADPCFG OxFFFF Configure AN pins as digital InitMain Perform main initialization value 2048 When program starts DAC gives yt the output in the mid range InitMain Perform main initialization value 2048 When program starts DAC gives the output in the mid range while TRUE do Endless loop begin if RBO bit and value lt 4095 then If RAO button is pressed Inc value Ei increment value else begin if RB1 bit and value gt 0 then If RAl button is pressed Dec value ff decrement value end DAC Output value Send value to DAC chip Delay_ms 1 Slow down key repeat pace end end HW Connection OSCLLATOR DAC CONNECTOR HE ELOvVOIdSP SPI HW connection MikroElektronika 473 mikroPascal PRO for dsPIC30 33 and PIC24 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 ENC28J60 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 as
436. iate hardware SPI module must be previously initialized 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 mc Fat QuickFormat mikroE 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 IDLE 393 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Mmc_Fat_Assign Prototype function Mme 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
437. ication 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 requested 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
438. ice 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 the compiler not to automatically perform context switching 156 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 SetFunCCall called _func Routines specified in the SetFunCCall argument list will be linked if the routine containing SetFunCCal1 directive is called in the code no matter whether any of them was explicitly called or not Thus placing Set FuncCal1 directive in main will make compiler link specified routines always procedure first p q byte begin SetFuncCall second let linker know that we will call the routine second end ee The Set FuncCal1 directive can help the linker to optimize function frame allocation in the compiled stack SetOrg Prototype procedure SetOrg RoutineName string address long
439. ience 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 MikroElektronika 153 mikroPascal PRO for dsPICSO 33 and PIC24 Delay_Cyc Prototype procedure Delay Cyc x word y word Creates a delay based on MCU clock Delay 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 Delay_Cyc_Long procedure Delay Cyc Long CycNo word poms Wong Example Delay Cyc Long 16384 16384 cycles pause Delay Cyc Long isa ee 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 Parameters None Returns Device clock in kHz rounded to the nearest integer GLE Clock_kHz 154 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Clock _MHz Prototype function Clock MHz word D
440. igher 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 0x32 var x word absolute 0x32 Variable y will occupy 2 words at addresses 0x34 and 0x36 var y longint absolute 0x34 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 0x42 var i word absolute 0x42 Variable will occupy 2 words at 0x40 and 0x42 thus changing i changes jj at the same time and vice versa var jj longint absolute 0x40 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 0x800 eonst MONTHS lt array 1 12 of Byte 31 28 31 30 31 30 31 31 30 31 30 31 7 org 0x800 If you want to place simple type constant into Flash memory instead of following declaration const SimpleConstant byte OxAA org 0x2000 use an array consisting of single element const SimpleConstant array 1 of byte 0xAA org 0x800 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
441. ile creation and attributes flags Each bit corresponds to the appropriate file attribute COC d Po oor o eao o Le f oao Device riemal use ony nover raon aeo 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 MMC SD card and MMC library must be initialized for file operations See Mmc_Fat_Init MikroElektronika 400 mikroPascal PRO for dsPICSO 33 and PIC24 Try to create a swap file with archive atribute whose size will be at least 1000 sectors ZZ 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 UART1 Write UART1 Write Lo e siselig UART1 Write Hi size UART1 Write Higher size OxAA UART1 Write High aia ye OxAA UART1 Write 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 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
442. ile 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 Next gt Cancel Step Five Select inital Library Manager state New Project Wizard Select initial Library Manager state Include Libraries Include all Default 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 Next gt mikoPascal PRO for dsPIC30 33 and PIC24 Step Six Click Finish button to create your New Project New Project Wizard You have successfully created a new project Click Finish to save the changes and to close the wizard Open Edit Project window to set Configuration bits Finish Cancel Related topics Project Manager Project Settings MikroElektronika 695 mikroPascal PRO for dsPICSO 33 and PIC24 Customizing Projects You can change basic project settings in the Project Settings window like chip and oscillator frequency Any change in the Project Setting Window affects currently active project only so
443. iling 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 dimensional array of size 5x10 Avariable 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 m 4 9 The first element of the 4th row would be m 3 0 204 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 nu11 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 nu11 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
444. in ptr a 0 ptr is pointer to byte pointing to a 0 ptr 2 ptr 3 ptrt3 is a pointer pointing to a 3 pir 2 G a 3 now equals 6 THE pPEX 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 j 5 assign value 10 to variable j is at the address 0x003A ptrl i ptr1 is pointer to byte pointing to i p r2 s U ptr2 is a pointer pointing to j x 2 ptrl 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 210 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 For example var a array 10 of byte array a containing 10 elements of type byte ptr byte pointer to byte begin ptr a 6 ptr is pointer to byte pointing to a 6 ptr ptr 3 ptr 3 i
445. 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 dsPIC30 33 and PIC24 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 i from the Project Manager window The project group may be reopened by clicking the Open Project Group Icon 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 mcl binary files pld project level defines files image files ihex EEPROM files hex asm and lst files see output files These files can not be added or removed from project other files Project Manager 1 1 ia PS ES S ems EY t Bm a B Sources B 16963C_240x128 mpas einstein_bmp mpas B mikroe_bmp mpas B Binaries T6963C_240x128 mel E Project level defines B E Image Files mikroE_240x128 bmp S EEPROM Files T6963C_240x128 ihex Active Comments Files 4 Output Files 76963C_240x128 hex 76963C_240x128 asm einstein_bmp asm mikroe_bmp asm
446. in the CANSPI module is set to Disable CAN capture Continue CAN operation in Idle mode Do not abort pending transmissions Fcean 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 value 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 263 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 p
447. ing functions regular and compact Using the regular set the user can write one byte of data to a single address which means that each byte of written data has its own address but on every 2 written bytes one byte of Flash memory remains empty Using the compact set every byte of Flash memory including those non addressable is filled with data this method can only be used for data organized in bytes The compact functions have Compact as name suffix For run time FLASH read write the dsPIC30 s RTSP module is being used It organizes data into rows and panels Each row contains write latches that can hold 4 instructions 12 bytes The number of panels varies from one dsPIC30 MCU model to another Because of that the flash write sequence has been split into several operations Write Init Write LoadLatch4 Write DoWrite in order to be usable on all dsPICs PIC24 and dsPIC33 Erasing can be done only in 512 instructions 1024 addresses 1536 bytes memory blocks which means that the block start address should be a multiply of 1024 i e have 10 lower bits set to zero Data is read and written in 64 instructions 128 addresses 192 bytes blocks This means that the block start address should be a multiply of 128 i e have 7 lower bits set to zero On the dsPIC33 and PIC24s 2 address locations are assigned on every 3 bytes of flash program memory Due to this specific and non one to one
448. int Use the SetOrg routine to specify the starting address of a routine in ROM Parameters RoutineName routine name address starting address Returns Noting OOOO Example SetOrg UART1 Write 0x1234 notes None MikroElektronika 157 mikroPascal PRO for dsPIC30 33 and PIC24 GetDateTime Use the GetDateTime to get date and time of compilation as string in your code PRetumns Sting with date and tne when tis routine Beompled SSCS example ecr Getbatetine OOOO Moes oe SSCS DoGetVersion FRetums Sring wih curent compter verson lt E le GetVersion for example str will take the value of Be2s 1 067 158 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 are 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 numb
449. int 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 routine 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 MikroElektronika 14 mikroPascal PRO for dsPICSO 33 and PIC24 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 value 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 generat
450. 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 set jmp function Invocation of longjmp must occur before return from the function in which set jmp was called encounters var buf array 4 of word Longjmp buf 2 MikroElektronika 671 mikroPascal PRO for dsPIC30 33 and PIC24 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 var buf array 4 of word procedure func33 begin Delay ms 1000 nop longjmp buf 2 nop end procedure func begin PORTB 3 if setjmp buf 2 then PORTB 1 else fune 33 7 end begin ADPCFG OxFFFF PORTB 0 TRISB 0 nop Eune nop Delay ms 1000 PORTB OXFFFF end 672 Note to th Program flow diagrams are indexed according xecution sequence of MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 String Library mikroPascal PRO for dsPIC30 33 and PIC24 includes a library which automatizes string related tasks Library Functions memc
451. inverts each dot Glcd needs to be initialized see Glcd_Init routine Draw a vertical line between dots 10 5 and 10 25 Glicd V Tine 5 25 10 1 7 Notes None SSCS Glcd_H_Line Prototype procedure Gled 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 see Glcd_Init routine Draw a horizontal line between dots 10 20 and 50 20 Gled H Line 10 50 20 1 Notes None oO MikroElektronika 354 mikroPascal PRO for dsPIC30 33 and PIC24 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 determines
452. ion 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 ane 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 P returns 0 toupper Prototype function toupper character byte 4 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 If the character is an uppercase letter A Z function returns a lowercase letter Otherwise function returns an unchanged input parameter res tolower A 4 returns a res tolower b returns b 658 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Conversions Library mikroPascal PRO for dsPIC30 33 and PIC24 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
453. ior 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 which 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
454. ir addresses in the ascending order Function Tree Displays Function Tree with the relevant data for each function D Statistics a Project Name C Extra Boards SPI Ethernet EthV2 DemolEth 2_Demo mbpds Time 12 9 2009 11 45 51 AM em mibros com mikoPascal PRO for dsPIC30 33 and PIC24 Memory Summary Displays summary of RAM and ROM memory in a pie like form H statistics TA E Static used 711 bytes E Dvn Available 1337 bytes Project Name C Extra Boards SPI Ethernet Ethv2 DemolEth 2_Demo mbpds Time 12 3 2009 11 45 51 AM seem mm broe com MikroElektronika 72 mikroPascal PRO for dsPIC30 33 and PIC24 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 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 3 Errors Warnings Hints Line Message No Message Text Uni
455. irection 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 D5 sbit at LATB1 bit var D6 sbit at LATB2 bit var I D7 sbit at LATB3 bit var RS Direction sbit at TRISDO bit var EN Direction sbit at TRISD1 bit var I D4 Direction sbit at TRISBO bit var D5 Direction sbit at TRISB1 bit var I D6 Direction sbit at TRISB2 bit var D7 Direction sbit at TRISB3 bit End LCD module connections ied Init MikroElektronika 314 mikroPascal PRO for dsPIC30 33 and PIC24 Led Out didi 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 Write text Hello on Lcd starting from row 1 column 3 Led Out l 3 Hello Lcd _Out_Cp 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 Led module needs to be initialized See
456. ired 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 SP 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 gt Port Expander SPI Led H 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_Lced_Chr SPI_Lcd_Chr_Cp SPI_Lcd_Cmd MikroElektronika 533 mikroPascal PRO for dsPICSO 33 and PIC24 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 before
457. ister 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 Bl B15 or0 1 15 with 15 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 i 1 expression as bit designator Set bit 6 in STATUS register i 5 SR it l 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 dsPIC30 33 and PIC24 and can be used anywhere in the code Identifiers 30 815 are not case sensitive and have a specific namespace You may override them with your own members B0 B15 within any given structure Also you can access the desired bit by using its alias name in this case Z bit Set Zero Bit 2 bit i 1 In this way if the Zero bit changes its re
458. it var TFT CS sbit at LATC3 bit var TFT RS sbit at LATBIS 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 TRISCI1 bit End of TFT display connections Initialize 240x320 TFT display TET Inidt 240 320 590 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 TFT_Set_Index Prototype procedure TFT Set_Index 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 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 591 mikroPascal
459. it 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 Library Example HW Connection OneWire Library Library Routines Ow_Reset Ow_Read Ow_Write Library Example HW Connection Peripheral Pin Select Library Library Routines Unlock_IOLOCK Lock_IOLOCK PPS_ Mapping Direction Parameters Input Functions Output Functions Port Expander Library Library Dependency Tree External dependencies of Port Expander Library Library Routines 389 389 389 390 390 390 391 392 392 393 393 394 395 396 397 397 398 398 398 399 399 400 401 401 402 403 408 409 409 409 410 410 411 413 414 414 414 414 415 415 415 416 418 418 418 418 MikroElektronika 16 mikroPascal PRO for dsPIC30 33 and PIC24 Expander_Init 419 Expander_Init_Advanced 420 Expander _Read_ Byte 420 Expander _Write_Byte 421 Expander_Read_PortA 421 Expander_Read_PortB 422 Expander_Read_PortAB 422 Expander_Write_PortA 423 Expander_Write_PortB 423 Expander_Write_PortAB 424 Expander_Set_DirectionPortA 424 Expander_Set_DirectionPortB 425 Expander_Set_DirectionPortAB 425 Expander_Set_PullUpsPortA 425 Expander_Set_PullUpsPortB 426 Expander_Set_PullUpsPortAB 426 HW Connection 428 PS 2 Library 429 External dependencies of PS 2 Library
460. it sfr Direction of the var SoftSpi_SDO Direction external Data Out pin TRISF3_ bit var SoftSpi_CLK Direction sbit sfr Direction of the var SoftSpi_CLK_ Direction sbit at external Clock pin TRISF6 bit Library Routines Soft_SPI_Init Soft_SPl_Read Soft_SPI_Write MikroElektronika 455 mikroPascal PRO for dsPICSO 33 and PIC24 Soft_SPI_ Init Requires Global variables SoftSpi_ SDT Data in line SoftSpi_ spo 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 connections var SoftSpi SDI sbit at RF2 bit var SoftSpi SDO sbit at LATF3 bit var SoftSpi CLK sbit at LATF6 bit var SoftSpi_ SDI Direction Sbit at TRISF2 bit var SoftSpi_ SDO Direction sbit at TRISF3 bit var SoftSpi_ CLK Direction sbit at TRISF6 bit End Software SPI module connections Soft_SPI_Init Init Soft_SPI Soft_SPl_ 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 Parameters sdata data to be sent Byte received via the SPI bus Requires Soft SPI must be initialized before using this function See Soft_S
461. itialized See the T6963C_init routine clear current panel T6963C_panelFill 0 580 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 T6963C_gfFill Rems nom OOOO S Toshiba Gled module needs to be initialized See the T6963C_init routine clear current graphic panel T6963C_grFill 0 moes None OoOo T6963C_txtFill Rems nonn OOOO SSS clear current text panel T6963C txtFILL1I 0 7 T6963C_cursor_height Prototype procedure T6963C cursor height n word n cursor height Valid values 0 7 Rems nom OOOO Example T6063 cursor neien OO OOOO moes fno oo MikroElektronika 581 mikroPascal PRO for dsPICSO 33 and PIC24 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 Gled module needs to be initialized See the T6963C_init routine enable graphic displaying T6963C_graphics 1 T6963C_text Prototype procedure T6963C_text n word Enable disable text displaying Parameters n on off parameter Valid values 0 disable text displaying and 1 enable text displaying Toshiba Gicd module needs to be initialized See the T6963C_init routine enable text displaying T6963C_text 1 T6963C_cursor Prototype procedure T6963C cursor n word Set cur
462. ive 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 h a 5 i Description in all projects using TFT library TET D E o I ee eden cd ical TFT Data Port var TFT DataPort byte at LATE var TFT DataPort Direction 4 var TFT DataPort Direction Dyte gxtesacic sir Direction of the TFT Data Port byte at TRISE TFT WR var TFT WR sbit sfr external Write signal at LATD13 bit var TFT CS sbit sfr external Chip Select signal F at LATC3 bit var TFT RS sbit sfr external raced cle F at LATB15 bi var TET RST z sbit sfr Reset signal FT RST sbit at LATC1 bi external a var TFT WR Direction sbit 3 A FT WR Direc Direction of the Write pin se bad external bit TFT RD Direction A FT RD Direc Direction of the Read pin eee external 4 _bit var TFT RD sbit sfr external Read signal PT RD 3 at LATD12_bi TFT_CS Direction Direction of the Chip Select FT CS Direc external pin 4 ipit TFT _ RS Direction sbit Direction of the Register Select FT RS Direc external pin SB13 bit TET RST Direction i Direction of the Reset pin var TFT_RST_ Direction sfr external ig pins TRISCI bit 588 Mik
463. ive atribute whose size will be at least 1000 sectors If it succeeds it sends the No of start sector over UART var size dword Cf Fat Get Swap File 1000 mikroE txt 0x20 size lt gt 0 then UART1 Write 0xAA UART1 Write Lo size UART1 Write Hi size UART1 Write Higher size VARTI Write Highest size UART1 Write 0xAA Long File Names LFN are not supported 291 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 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 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 var set compact flash pinout CE Data Port byte at PORTD CF RDY sbit at RB7 bit CF WE sbit at LATB6 bit CEF OE sbit at LATB5 bit CE Cpr sbit at RB4 bit CF CEL sbit at LATB3 bit CF_A2 sbit at LATB2 bit CF_Al sbit at LATB1 bit CF_AO sbit at LATBO bit CF RDY direction sbit CF WE direction sbit CF OF direction sbit CF CDi dire
464. ject Add File To Project MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 Attributes Url www mikroe com Image Easy_GSM_GPRS jpg File None Events OnLeftClick Alt OpenUrl OnRightClick None OnDbIClick None OnMouseOver 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 it is active comment V acractiveComment 30 Now let s try it If you LeftClick Alt on it URL in default Web browser will be opened If you hover the mouse over it you will see an Image preview Vs ac activeConment MikroElektronika 102 mikroPascal PRO for dsPIC30 33 and PIC24 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 activeCommentq 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 comme
465. ject level defines Related topics Project Manager Project Settings Edit Project MikroElektronika 697 mikroPascal PRO for dsPIC30 33 and PIC24 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 gt New Unit from the drop down menu or press Ctrl N or click the New File Icon li from the File Toolbar 2 Anew tab will be opened This is a new source file Select File Save from the drop down menu or press Ctrl S or click the Save File Icon A 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 dsPIC30 33 and PIC24 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 z 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
466. l 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 Pet mas Description i ofon reo e o40 Device intemal use oniy never foundon asy File creation flag If the file does not exist and this flag is 7 0x80 set a new file with specified name will be created 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 attribut if it does not already exist Cf Fat _Assign MIKROO07 TXT 0xA0 Notes Long File Names LFN are not supported 285 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Cf_Fat_Reset Prototype 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
467. lash operation FLASH_ Write_DoWrite This depends on the organization of the RTSP module for the certain dsPIC30 Please consult the Datasheet for particular dsPIC30 on this subject const iArr array 12 of word wie iy MEY ty vpr wor ya var ptr_data word ptr data lt iArr LASH Write Init 0x006100 ptr data LASH Write Loadlatch4 Compact LASH Write Loadlatch4 Compact LASH Write DoWrite 341 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 FLASH_Write_DoWrite FRetwns Nothing SSC Requires The block to be written to must be erased first either from the user code FLASH_Erase32 or during the programming of MCU Please note that block size that is to be erased is different from the one that can be written with this function This function is used as a part of the Flash write sequence therefore FLASH_Write_Init and certain number of FLASH_Write_Loadlatch4 or FLASH_Write_Loadlatch4_Compact function calls must be made before this one This function is to be called once at the and of the FLASH write sequence const iArr array 8 of word m var ptr_data word ptr data iArr FLASH Write Init 0x006100 ptr data FLASH Write Loadlatch4 FLASH Write Loadlatch4 FLASH Write DoWrite FLASH Read4 diel ias procedure FLASH Read4 flash address longint write _to word Reads one latch row 4 instructions 8 addresses in the regular mode
468. last change Redo last change Cut selected text to clipboard Copy selected text to clipboard Paste text from clipboard MikroElektronika 18 mikroPascal PRO for dsPICSO 33 and PIC24 Advanced Edit Toolbar Advanced Edit Toolbar comes with the following options ee oo oo oo O apee O apeme O a erer aenar Find Replace Toolbar PLRPALD Find Replace Toolbar is a standard toolbar with the following options C epson SSCS rJ Find text in current editor afp Replace text E E Find text in files 19 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Project Toolbar A Project Toolbar comes with the following options a New project iB Open Project E Save Project Edit project settings Close current project E Clean project folder macs G3 Add File To Project ct Remove File From Project fe Build Toolbar Hih a Build Toolbar comes with the following options o ooo o S E Build current project Build all opened projects Build and program active project Start programmer and load current HEX file MikroElektronika 80 mikroPascal PRO for dsPICSO 33 and PIC24 Debug Toolbar Debug Toolbar comes with the following options leon S o wpe o S wp ooo S afpera oo S mpre o S Styles Toolbar Styles toolbar allows you to easily change colors of your workspace Office 2003 Blue a Office 2003 Blue 81 MikroE
469. le Menu Options 43 Edit 44 Edit Menu Options 44 Find Text 45 Replace Text 45 Find In Files 46 Go To Line 46 Regular expressions option 46 View 47 View Menu Options 47 Project 49 Project Menu Options 49 Build 50 Build Menu Options 50 Run 51 Run Menu Options 51 Tools 52 Tools Menu Options 52 MikroElektronika mikroPascal PRO for dsPICSO 33 and PIC24 Help 53 Help Menu Options 53 mikroPascal PRO for dsPIC30 33 and PIC24 IDE 54 IDE Overview 54 Code Editor 55 Editor Settings 55 Auto Save 56 Highlighter 56 Spelling 56 Comment Style 56 Code Folding 56 Code Assistant 57 Parameter Assistant 57 Bookmarks 57 Go to Line 57 Column Select Mode 58 Editor Colors 58 Auto Correct 59 Auto Complete Code Templates 60 Code Explorer 62 Routine List 63 Project Manager 63 Project Settings 65 Library Manager 66 Managing libraries using Package Manager 67 Routine List 68 Statistics 68 Memory Usage Windows 68 RAM Memory Usage 69 Used RAM Locations 69 SFR Locations 70 ROM Memory Usage 70 ROM Memory Constants 71 Functions 71 Functions Sorted By Name Chart 72 Functions Sorted By Size Chart 72 Functions Sorted By Addresses 73 Function Tree 73 Memory Summary 74 Messages Window 75 Quick Converter 76 Macro Editor 76 Image Preview TT Toolbars 79 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 File Toolbar Edit Toolbar Advanced Edit Toolbar Find Replace Toolbar Project Toolbar Build Toolbar Debug Toolb
470. le contents 27 Write data to assigned file end jf Pee o2 sess S555 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 Mme Fat Read character UART1 Write character Write data to UART Dec size end end Deletes a file If file doesn t exist it will first be created EA and then deleted procedure M Delete File begin filename 7 F Mmc_ Fat Assign filename 0 Mme Fat Delete end A a Tests whether file exists and if so sends its creation date At 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 month outstr UART1 Write Text outstr WordToStr day outstr 403 MikroElektronika r mikoPascal PRO for dsPIC30 33 and PIC24 UART1 Write Text outstr WordToStr hour outstr UART1 Write Text outstr WordToStr minute outstr UART1 Write Text outstr file has
471. le of one type to a variable of another type is typecasting mikroPascal PRO for dsPIC30 33 and PIC24 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 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 gt longint integer gt longint integer gt 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 SFF b a a is promoted to word b becomes SOOFF 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 destin
472. le 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 Glced Adapter Board pinout see schematic at the bottom of this page for details Library Dependency Tree Port Expander SPI Graphic Lcd f _ Glcd 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 518 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_Glcd_Rectangle SPI_Glcd_Rectangle_Round_Edges SPI_Glcd_Rectangle_Round_Edges_ Fill SPI_Glcd_Box SPI_Glcd_Circle SPI_Glcd_Circle_Fill SPI_Glcd_Set_Font SPI_Glcd_Write_Char SPI_Glcd_Write_Text SPI_Glcd_Image SPI_Glcd_Partiallmage SPI_Glcd_Init Prototype procedure SPI Gled Init DeviceAddress byte Initializes the Glcd module via SPI interface DeviceAddress SPI expander hardware address see schematic at the bottom of this page Requires Global variables SPExpanderCs Chip Sel
473. lektronika mikoPascal PRO for dsPIC30 33 and PIC24 Statements Introduction to Statements Assignment 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 Compler Directives Linker Directives Lexical Elements Overview The following topics provide a formal definition of the mikroPascal PRO for dsPIC30 33 and PIC 24 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 dsPIC30 33 and PIC24 are derived from a series of operations performed on your programs by the compiler MikroElektronika 119 mikroPascal PRO for dsPIC30 33 and PIC24 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 i char j lt word and var as ehar J 2 word are lexically equivalent and parse identically var i char word Newlin
474. lektronika mikoPascal PRO for dsPIC30 33 and PIC24 Tools Toolbar Tools Toolbar comes with the following default options Icon i afm Open Active Comment editor aem o Tip The Tools toolbar can easily be customized by adding new tools in Options menu window View Toolbar aj L m View Toolbar provides access to assembly code listing file and statistics windows leon SSCS eion SOS Open assembly code in editor ry Open listing file in editor View statistics for current project MikroElektronika 82 mikroPascal PRO for dsPIC30 33 and PIC24 Layout Toolbar Styles toolbar allows you to easily customize workspace through a number of different IDE layouts Delete the selected layout Save the current layout Set the selected layout Help Toolbar p Help Toolbar provides access to information on using and registering compilers 2 How To Register Related topics Keyboard shortcuts Integrated Tools Debug Windows 83 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 a 4 Sources 3 Lcd mpas Binaries Project level defines Image Files EEPROM Files Active Comments Files Output Files 25 Led hex 23
475. les ADC module and reads the specified analog channel input Requires The MCU with built in ADC module ADC library routines require you to specify the module you want to use To select the desired ADC module simply change the letter x in the routine prototype for a number from 1 to 2 Number of ADC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 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 ADC1 module channel 10 This is a standalone routine so there is no need for a previous initialization of ADC module 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 243 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 ADC_Set_Active Prototype procedure ADC Set _Active adc_gs TADC_Get_Sample Description Sets active ADC module Parameters Parameters adc_gs ADCx_Get_Sample handler Requires Routine is available only for MCUs with multiple ADC modules Used ADC module must be initialized before using this routine See ADCx_Init and ADCx_Init_ Advanced routines Activate ADC2 module ADC Set Active ADC2 Get Sample Notes None SOS Library Example This code snippet
476. library i E a a i a i E a E SPI_T6963C Config 240 128 8 0 2 1 0 4 Delay ms 1000 Enable both graphics and text display at the same time J SPE T6963C graphics 1 SPI_T6963C_text 1 panel 0 Text messages a SPI T6963C write text txt 0 0 SPI T6963C ROM MODE XOR SPI T6963C write text txtl 0 15 SPI _T6963C_ROM MODE XOR 562 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Cursor ae SPI T6963C cursor height 8 8 pixel height SPI_T6963C_set_cursor 0 0 Move cursor to top left SPI_T6963C_cursor 0 i Cursor Off Draw rectangles oi SPI _T6963C_rectangle 0 0 239 127 SPI_T6963C WHITE SPI T6963C_rectangle 20 20 219 107 SPI T6963C WHITE SPI T6963C_rectangle 40 40 199 87 SPI_T6963C_WHITE SPI_T6963C_ rectangle 60 60 179 67 SPI _T69635C WHITE fe Draw a Cross SPI T6963C tine 0 Oy 239 127 SPL T69636 WHITE SPI T6963C line 0 127 239 0 SPI_T6963C_ WHITE gt Draw solid boxes SPI_T6963C_box 0 0 239 8 SPI_T6963C_WHITE SPI_T6963C_box 0 119 239 127 SPI_T6963C_WHITE i Draw circles es SIFDEF COMPLETE EXAMPLE SPI_1T6963C_circle 120 64 10 SPI T6963C WHITE SPI_T6963C_circle 120 64 30 SPI _T6963C_ WHITE SPI_1T6963C_circle 120 64 50 SPI T6963C WHITE SPI_1T6963C_circle 120 64 70 SPI_T6963C_WHITE SPI _T6963C_circle 120 64 90 SPI _T6963C_ WH
477. 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 Toshiba Glcd module needs to be initialized See SP _T6963C sa routine SPI T6963C Line 0 0 239 127 SPI T6963C WHITE MikroElektronika 951 mikroPascal PRO for dsPICSO 33 and PIC24 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 yl 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 T6963C rectangle 20 20 219 107 SPI T6963C WHITE SPI_T6963C_rectangle_round_edges Prototype age a _T6963C_ rectangle round_edges x0 pea yO integer xl integer integer radius integer pcolor byte Draws a AT 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 yl y coordinate of the lower right rectangle corner round radius radius of the rounded edge
478. llatorFail 0x0008 AddressError Ox0004 StackError Ox000C MathError OxO00E ReservedTrapS 0x0010 ReservedTrap6 0x0012 ReservedTrap7 0x0014 INTOInterrupt 0x0016 IC1Interrupt 0x0018 OC1Interrupt 0x0014 TiInterrupt OxO001C IC2Interrupt 0x001E OC2Interrupt 0x0020 T2Interrupt 0x0022 T3Interrupt 0x0026 U1RXInterrupt 0x0028 U1TXInterrupt 0x0024 ADCInterrupt Ox002C N MInterrupt OxO002E SI2CInterrupt 0x0030 MIZCInterrupt 0x0032 CNInterrupt 0x0034 INT1Interrupt 0x0036 IC7Interrupt 0x0038 IC8Interrupt Ox0034 OC3Interrupt Ox003C OC4Interrupt Ox003E T4Interrupt Conly used Cancel By checking the Only Used box you can display only the used interrupts 107 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 esca
479. low interrupt flag end begin if Man Receive Init begin end try Man Receive with blocking prevention mechanism TECO IPCO or 0x1000 Interrupt priority level 1 TIIE big s dy Enable Timerl interrupts TICON 0x8030 Timerl ON internal clock FCY prescaler 1 256 datal Man Receive error TITE bLL 07 Disable Timerl interrupts end Interrupts should be disabled before using Manchester routines again see note at the top of this page 383 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Library Example The following code is code for the Manchester receiver it shows how to use the Manchester Library for receiving data Copy Code To Clipboard program Manchester Receiver ZZ BCD moure connections var LCD_RS sbit at LATDO bit LCD_EN sbit at LATD1 bit LCD D4 sbit at LATBO bit LCD D5 sbit at LATB1 bit LCD DG sbit at LATB2 bit LCD D7 sbit at LATB3 bit var LCD RS Direction sbit at TRISDO bit CD EN Direction sbit at TRISD1 bit LCD _ D4 Direction sbit at TRISBO bit LCD _D5 Direction sbit at TRISB1 bit LCD D6 Direction sbit at TRISB2 bit LCD D7 Direction sbit at TRISB3 bit End LCD module connections Manchester module connections var MANRXPIN sbit at RFO bit MANRXPIN Direction MANTXPIN sbit at LATF1 Biti MANTXPIN Direction End Manchester module connections sbit at TRISFO bit
480. lso 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 request 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 ha
481. lt gt 0 then Cf Fat Get File Date year month day hour minute UART1 Write Text created WordToStr year outstr UART1 Write Text outstr ByteToStr month outstr UART1 Write Text outstr WordToStr day outstr UART1 Write Text outstr WordToStr heur outstr 7 UART1 Write Text outstr WordToStr minute outstr UART1 Write Text outstr r r file has been found get its modified date Cf Fat Get File Date Modified year 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 VARTI Write Text outstr get file size fsize Cf Fat Get File Size LongIntToStr fsize outstr UART1 Write Line outstr end else begin file was not found signal it UART1 Write 0x55 Delay ms 1000 UART1 Write 0x55 end end Tries to create a swap file Ea 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 mikroE txt for details month day LA 0x20 hour uncomment this line to search for file that DOES NOT exist minute whose size will be a
482. lter is to be disabled Requires The ECAN routines are supported only by MCUs with the ECAN module Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus The ECAN module must be initialized See the ECANxInitialize routine Filters 0 4 8 12 are to be disabled ECAN1FilterDisable 0x1111 wa ECAN library routine require you to specify the module you want to use To select the desired ECAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of ECAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 302 mikroPascal PRO for dsPIC30 33 and PIC24 ECANxFilterEnable Prototype procedure ECANxFilterEnable flten word Description The function enables receive filters Parameters flten filter enable selection parameter Each bit corresponds to appropriate filter By setting bit the corresponding filter will be enabled Requires The ECAN routines are supported only by MCUs with the ECAN module Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus The ECAN module must be initialized See the ECANxInitialize routine Filters 0 4 8 12 are to be enabled ECAN1FilterEnable 0x1111 P ECAN library routine require you to specify the module you want to use To select the desired ECAN module
483. lue This value is bit adjusted to appropriate buffer mask registers CAN CONFIG FLAGS selects type of message to filter Valid values CAN CONFIG ALL VALID MSG CAN CONFIG MATCH MSG TYPE CAN CONFIG MATCH MSG TYPE See CAN_CONFIG FLAGS constants amp CAN CONFIG STD MSG amp CAN CONFIG XTD MSG Nothing CAN must be in Config mode otherwise the function will be ignored See CANxSetOperationMode Requires MCU with the CAN module MCU must be connected to the CAN transceiver MCP2551 or similar which is connected to the CAN bus set appropriate filter mask and message type value CAN1SetOperationMode _CAN MODE CONFIG OxFF set CONFIGURATION mode CAN1 module must be in Set all BI mask bits to 1 config mode for mask settings 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 CAN CONFIG MATCH MSG TYPE amp CAN CONFIG XTD CAN library routine require you to specify the module you want to use To use the desired CAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of CAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 250 mikroPascal PRO for dsPIC30 33 and PIC24 CANxSetFilter Prototype procedure CANxSetFilter CAN
484. lues 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 notation 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 11 decimal literal SII hex literal equals decimal 17 oxi 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 dsPIC30 33 and PIC24 longint Compiler will report an error if the literal exceeds 2147483647 S7FFFFFFF MikroElektronika 182 mikroPascal PRO for dsPIC30 33 and PIC24 Floating Point Literals A floating point value consists of Decimal integer Decimal point Decimal fraction e or E anda signed integer exponent optional You can omit either 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 dsPIC30 33 and PIC24 limits floating point constants to the range of 1 17549435082 10 8 6
485. mikroPascal PRO for dsPIC30 33 and PIC24 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 lt source file name gt lt variable name gt 2 If declared in the interface section visible throughout the whole project lt variable name gt 3 If accessing registers declared through register rx or sfr specifiers visible throughout the whole project lt variable name gt Accessing local variable lt routine name gt lt variable name gt Accessing routine parameter FARG lt routine name gt lt variable name gt Here is an example of using asm instructions program 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 MikroElektronika 231 mikroPascal PRO for dsPIC30 33 and PIC24 asm OV _myvar w0 nop OV 6 WO OV WO _myvar OV lo_addr _myvar wl Ox2678 gt W1 0x0000 gt W1 OV lo addr _ proc WO WO 0x0001 gt W1 WO 0x3652 gt W1 gt W1 end end Asm code and SSA optimization OV hi_addr _myvar W1 r move myvar to W0 move literal 6 to WO move contents of WO to myvar
486. 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 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 year word month day hours mins byte Mmc Fat Get File Date year month day hours mins MikroElektronika 398 mikroPascal PRO for dsPICSO 33 and PIC24 Mmc_Fat_Get_File_Date_Modified Prototype procedure Mmc Fat Get File Date Modified vwar 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 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
487. 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 eonst MONTHS array 1 12 of byte 31 28 31 30 31 30 31 31 30 31 30 31 7 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 189 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Colon Colon is used in declarations to separate identifier list from type identifier For example var i J byte k word In the program use the colon to indicate a labeled statement Start nop got
488. mp2write shr RES SHIFT Convert temp whole to characters if temp whole div 100 then text 0 temp whole div 100 48 MikroElektronika 409 mikroPascal PRO for dsPIC30 33 and PIC24 else text 0 10737 text 1 temp_whole div 10 mod 10 48 Extract tens digit text 2 temp whole mod 10 48 Extract ones digit Extract temp fraction and convert it to unsigned int temp fraction word temp2write shl 4 RES SHIFT temp fraction temp fraction and 0x000F temp fraction temp fraction 625 Convert temp fraction to characters text 4 word temp fraction div 1000 48 Extract thousands digit text 5 word temp fraction div 100 mod 10 48 Extract hundreds digit text 6 word temp fraction div 10 mod 10 48 Extract tens digit text 7 word temp fraction mod 10 48 Extract ones digit Print temperature on LCD Ged Out 2 5 text end begin ADPCFG 0 Configure AN pins as digital I O text 000 0000 Led InI Initialize LCD Led_Cmd LCD CLEAR Clear LCD Led Cmd LCD CURSOR OFF Turn cursor off Led Out 1 1 Y Temperature Fa Led Chr 2 13 078 4 Print degree character C for Centigrades Different LCD displays have different char code for degree hed Chr 2 14 C jz If you see greek alpha letter try typing 178 instead of 223 Main loop while TRUE do begin Perform temperature rea
489. mple SPI T6963C inagetnyimse Sd Image dimension must match the display dimension Use the integrated Glcd Bitmap Editor menu option Tools gt Gled Bitmap Editor to convert image to a constant array suitable for displaying on Glcd J4 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_T6963C_Partiallmage Prototype procedure SPI T6963C PartialImage 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 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 Toshiba Glcd module needs to be initialized See SP _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 Partialimage l10 127 10 is 16 32 amage Use the integrated Glcd Bitmap Editor menu option Tools gt Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd SPI_T6963C_ sprite Pro
490. n begin ADPCFG OxFFFF yy 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 16 initial value for current duty current_dutyl 16 initial value for current _dutyl MikroElektronika 433 mikroPascal PRO for dsPIC30 33 and PIC24 PWM Start 1 PWM Start 2 PWM Set Duty current duty 1 Set current duty for PWM1 PWM Set Duty current dutyl 2 Set current duty for PWM2 while TRUE do endless loop begin if RBO bit 1 then button on RBO pressed begin Delay ms 20 Inc current duty increment current duty if current duty gt pwm_periodl then if we increase current duty greater then possible pwm periodi value current duty z 0 veset current duty value to zero PWM Set Duty current duty 1 set newly acquired duty ratio end if RBl bit 1 then button on RB1 pressed begin Delay ms 20 Dec current duty decrement current duty if current duty gt 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 PWM Set Duty current duty 1 set newly acquired duty ratio end if RB2 bit 1 then button on RB2 pressed begin Delay ms 20 Inc current_dutyl increment current_dutyl if current _dutyl gt pwm period2 then if w
491. n 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 lt gt 0 then begin end 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 x_coord y coord 0 then begin end 608 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 TP_Calibrate_Bottom_Left Prototype procedure TP Calibrate Bottom Left Calibrate bottom left corner of the touch Panel Rems Nothing OOOO Example 1 calibrate Botton teft0 Calibration of portom left corner Noes noe SSCS TP_Calibrate_Upper_Right Rems Nothing OOO Example Te calibrate Upper Right Calibration of upper right corner Moes Noe SSCS TP_Get_Calibration_Consts Prototype procedure TP Get _Calibration_Consts x_min word x max word y min word y max word
492. n The output string is right justified and remaining positions on the left if any are filled with zeros Parameters input word to be converted output destination string var t word txt array 4 of char t 11117 WordToHex t txt txt is 0457 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 integer number to be converted output destination string Nothing var input integer Ext 2 string 4 ifs input 32768 IntToHex input txt txt is 8000 MikroElektronika 667 mikroPascal PRO for dsPICSO 33 and PIC24 LongWordToHex Prototype 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 double word number to be converted lt a destination string var input dword txt array 8 of char IEE input 65535 LongWordToHex input txt txt is OOOOFFFF LongIntToHex Prototype procedure LongIntToHex input longint var output array 8 of char
493. n CANxRead var id longint var data array 1 of byte dataLen CAN RX MSG FLAGS word word 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 pointed by id pointer Message data is retrieved and stored to array pointed by data pointer Message length is retrieved and stored to location pointed by dat aLen pointer Message flags are retrieved and stored to location pointed by CAN RX MSG FLAGS pointer Parameters id message identifier address data an array of bytes up to 8 bytes in length dataLen data length address CAN RX MSG FLAGS message flags address For message receive flags format refer to CAN RX _ MSG FLAGS constants See CAN_RX_MSG_FLAGS constants 0 if nothing is received OxFFFF if one of the Receive Buffers is full message received Requires MCU with the CAN module MCU must be connected to the CAN transceiver MCP2551 or similar which is connected to the CAN bus CAN must be in Config mode otherwise the function will be ignored See CANxSetOperationMode check the CAN1 module for received messages If any was received do something var msg rcvd rx flags data_len word data array 8 of byte msg id longint CAN1SetOperationMode _CAN MODE NORMAL OxFF set NORMAL mode CAN1 module must be in mode in which receive is possible rx flags 0 clear message flags if msg rcvd CAN1Rea
494. n 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 ptr 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 ptri pointer in data space pointing to a byte in code space const ptr2 byte ptr2 pointer in 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 dsPIC30 33 and PIC24 The example shows how to define and use a function pointer MikroElektronika 207 mikroPascal PRO for dsPICSO 33 and PIC24 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 program Example type TMyFunctionType function paraml
495. n 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 Dy Notes For x axis and page layout explanation see schematic at the bottom of this page SPI_Glcd_Write_ Text Prototype procedure SPI Gled 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_lInit routine Use the SPI_Glcd_Set_Font to specify the font for display if no font is specified then the default Font Gled System5x7 font supplied with the library will be used Write text H
496. n the left if any are filled with zeros Parameters input word to be converted e destination string var t word txt array 5 of char Pitas t 437 WordToStrWithZeros t txt txt is 00437 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 word to be converted output destination a Returns Nothing s var t integer txt array 6 of char PE E t 3276 IntToStrWithZeros t txt txt is 03276 mikoPascal PRO for dsPIC30 33 and PIC24 LongWordToStrWithZeros Prototype procedure LongWordToStrWithZeros input dword var output array 10 of gchar Description Converts 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 word to be converted output destination string var t dword txt array 10 of char faves t 12345678 LongWordToStrWithZeros t txt ext is 0012345678 LongIntToStrWithZeros Prototype procedure LongIntToStrWithZeros input longint var output array 11 of char Description Converts input longint to a string The output string is right justified and the remaining positions on the left if any
497. n user friendly visual interface for setting the filter parameters Filter designer output is the mikroPascal PRO for dsPIC30 33 and PIC24 compatible code You can launch it from the drop down menu Tools gt Filter Designer 91 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Mikrotiektronika Filter Design Tool 5 PIR FIR Parameters FIR Window FIR Frequency S mR DR Parameters IIR Prototype OR Frequency 5 Source Code BHC PRO mhroPasca PRO mbreBasc PRO 5 Schematics POFEOL4 PROFAOLS Device Setup Device PSOF 013 Clocks 1000 000000 FIR filters are characterized by a linear phase and by a constant group delay The bad side is a high order of the filter which means higher complexity Instead IIR filters have much lower order with almost the same effects However IIR filters have a very non linear phase characteristic Graphic Lcd Bitmap Editor The mikroPascal PRO for dsPIC30 33 and PIC24 includes the Graphic Lcd Bitmap Editor Output is the mikroPascal PRO for dsPIC30 33 and PIC24 compatible code You can launch it from the drop down menu Tools gt Gied Bitmap Editor Mikroflektronika GLCD Bitmap Editor GLCD Sze controler 240x128 76963C 240x64 T6963C D 128x128 T6963C 2 notim GLCD Picture name banner bmp 1 7 GLCD Model Toshiba T6963C 240x128 unsigned char const banner _bup 3840 258 255 255 255 255 255 258 255 255 255 255 258 255 258 255 25S 255 255 255 2
498. nced UARTx_Data_Ready UARTx_Tx_Idle UARTx_Read UARTx_Read_Text UARTx_Write UARTx_Write_Text UART_Set_Active 620 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 UARTx_Init Prototype procedure UARTx Init baud_rate longint 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 Routine requires the UART module Initialize hardware UART1 module and establish communication at 2400 bps UART1 Init 2400 Refer to the device data sheet for baud rates allowed for specific Fosc For the dsPIC33 and PIC24 MCUs 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 4 Switching between the UART modules in the UART library is done by the UART_Set_Active f
499. nction 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 myst ring or PORTB mikroElektronika txt sub mikr memmove txt 7 txt_sub 4 string txt will be populated with first 4 characters of the txt 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 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 mikroElektronika memset txt a 2 routine will copy the character a into each of the first n characters of the string txt strcat Prototype procedure strcat var sl s2 string Description The function appends the value of string s2 to string s1 and terminates s1 with a null character h txt mikroElektronika txt sub lt mikr txt 3 0 strcat txt test
500. nd PIC24 Library Routines 243 ADCx_Init 243 ADCx_Init_Advanced 244 ADCx_Get_Sample 245 ADCx_Read 245 ADC_Set_Active 246 Library Example 246 HW Connection 247 CAN Library 248 Library Routines 248 CANxSetOperationMode 249 CANxGetOperationMode 249 CANxtInitialize 250 CANxSetBaudRate 251 CANxSetMask 252 CANxSetFilter 253 CANxRead 254 CANxWrite 255 CAN Constants 256 CAN_OP_MODE Constants 256 CAN_CONFIG_FLAGS Constants 256 CAN_TX_MSG_FLAGS Constants 257 CAN_RX_MSG_FLAGS Constants 258 CAN_MASK Constants 258 CAN_FILTER Constants 259 Library Example 259 HW Connection 262 CANSPI Library 263 Library Dependency Tree 263 External dependencies of CANSPI Library 264 Library Routines 264 CANSP SetOperationMode 264 CANSP GetOperationMode 265 CANSPIInit 265 CANSPISetBaudRate 267 CANSPISetMask 268 CANSPISetFilter 269 CANSPIRead 270 CANSPIWrite 271 CANSPI Constants 271 CANSPI_OP_MODE Constants 271 CANSPI_TX_MSG_FLAGS Constants 273 CANSPI_RX_MSG_FLAGS Constants 273 CANSPI_MASK Constants 274 CANSPI_FILTER Constants 274 Library Example 275 HW Connection 278 MikroElektronika 11 mikoPascal PRO for dsPIC30 33 and PIC24 Compact Flash Library 279 Library Dependency Tree 279 External dependencies of Compact Flash Library 280 Library Routines 281 Cf_Init 282 Cf_Detect 283 Cf_Enable 283 Cf_Disable 283 Cf_Read_Init 284 Cf_Read_Byte 284 Cf_Write_Init 284 Cf_Write_Byte 285 Cf_Read_ Sector 285 Cf_Write_Sector 285 Cf_Fat_Ini
501. ne multiplied by 1000 and rounded to the nearest integer result round sin angle deg 1000 Parameters angle deg input angle in degrees The function returns the sine of input parameter multiplied by 1000 Requires Nothing var res integer sinE3 45 result is 707 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 Parameters angle deg input angle in degrees The function returns the sine of input parameter multiplied by 1000 Requires Nothing var res integer res cosE3 196 result is 193 Return value range 1000 1000 690 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 CHAPTER 10 Tutorials Managing Project Projects The mikroPascal PRO for dsPIC30 33 and PIC24 organizes applications into projects consisting of a single project file extension mppds and one or more source files extension mpas mikroPascal PRO for dsPIC30 33 and PIC24 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 and optional description target device device flags config word device clock list of the project sourc
502. nel Glcd module needs to be initialized See the 1D13700_Init routine clear current text panel 1D13700 TxtFill 0 1D13700_Display_GrLayer Prototype lt procedure S1D13700 Display GrLayer mode byte Description Display selected graphic layer Parameters mode graphic layer mode Valid values Glcd module needs to be initialized See the 1D13700_Init routine Turn on graphic layer 1D13700 Display GrLayer S1D13700 LAY MikroElektronika 326 mikroPascal PRO for dsPICSO 33 and PIC24 1D13700_Display_TxtLayer 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 1D13700_Init routine Display on text layer 1D13700 Display TxtLayer S1D13700 LAYER ON 1D13700 Set_Cursor Prototype procedure S1D13700 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 1D13700_CURSOR_UNDERSCORE Set cursor shape underscore 1D13700_CURSOR_BLOCK Set cursor shape block Gled module needs to be initialized See the S1D13700_Init routine set cursor with the following properties width 5px heig
503. nfig routine Write text Here at current cursor position SPI Led Out CP Here SPI_Lcd_Chr Eromes 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 SP communication see SPI_Lcd_Config routine Write character i at row 2 column 3 SPE Led Chr 2 3 ap SPI_Lcd_Chr_Cp Prototype procedure SPI Lcd Chr CP Out Char byte Description 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 Led Chr Cp e 7 MikroElektronika 535 mikroPascal PRO for dsPICSO 33 and PIC24 SPI_Lcd_Cmd Requires Lcd needs to be initialized for SPI communication see SP _Lcd_Config routine Clear Lcd display SPI Lcd Cmd LCD CLEAR Notes Predefined constants can be passed to the routine see Available SPI Lcd Commands Available SPI Lcd Commands _LCD_RETURN_HOME Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected
504. ng is out of display dimension range if TE TFT Get Coordinates Gz coord Oy coord 0 then begin end TP_TFT_Calibrate_Min Prototype procedure TP TFT Calibrate Min Rems Noting OOOO Example re rer calibrate MnO _ Calibration of botton left comer Notes Nome o TP_TFT_Calibrate_Max Rems Nothing OOOO Example TP_TFT Calibrate Max Calibration of upper right corner E a MikroElektronika 617 mikroPascal PRO for dsPICSO 33 and PIC24 TP_TFT_Get_Calibration_Consts a procedure TP TFT Get Calibration Consts x min word x max word y min word y max word idl Gets calibration constants after calibration is done and stores themin x min x max y min and y_max parameters 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 y coordinate of the upper right corner of the working area TP TFT Get Calibration Consts x_ min y min x 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 _ 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 w
505. nika mikoPascal PRO for dsPIC30 33 and PIC24 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 dsPIC30 33 and PIC24 program on a host dsPIC30 33 or PIC24 microcontroller and view variable values Special Function Registers SFR RAM CODE and EEPROM memory along with the mikrolCD code execution on hardware MikroElektronika 116 mikroPascal PRO for dsPIC30 33 and PIC24 S EP as If you have 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 Build Type O Release ICD Debug Debugger O Software mikroIcd is l Now compile the project by pressing Ctrl F9 or by pressing Build Icon on Build Toolbar L S EP NO 2 Run the mikrolCD by selecting Run gt Start Debugger from the drop down menu or by clicking the Start Debugger Icon ES 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 Wa
506. nika mikoPascal PRO for dsPIC30 33 and PIC24 Glcd_Set_Font Prototype procedure Glcd Set Port const activeFont byte aFontWidth aFontHeight byte aFontOffs byte Sets font that will be used with Glcd_Write_Char and Glcd_Write_Text routines Parameters act iveFont 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 dsPIC30 33 and PIC24 character set and regular ASCII set eg if A is 65 in ASCII character and A is 45 in the mikroPascal PRO for dsPIC30 33 and PIC24 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 _Glcd_ System3x5 FontSystem5x7_v2 equivalent to Font _Glcd_ System5x7 font5x7 equivalent to Font _Glcd_5x7 Character8x7 equivalent to Font Glcd_Character8x7 Glcd needs to be initialized see Glcd_Init routine Use the custom 5x7 font myfont which starts with
507. nit Led Cmd _LCD_CLEAR Led_Cmd _LCD_CURSOR_OFF E ss for i 1 to 17 do begin G s7 Led _Chr i i text i 1 Ld end e end Watch Values Bi Bi Eh 90 op OT E fu a Add Remove Properties k AddAll Remove all Select variable from list text v Search for variable by assembly name _text Ci V Peripherals Freeze Name Value ch PORTB Oxon cme ADG OXF FF 0x028 de PC 0x0002E2 text 71 06 ms 121 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 4 for PIC24 and dsPIC33 family for dsPIC30 family this number depends on the MCU used If all hardware brekpoints are used then the next breakpoint will be software breakpoint These breakpoints are placed inside the mikrolCD and simulate hardware breakpoints Software breakpoints are much slower than hardware breakpoints These differences between hardware and software breakpoints are not visible in the mikrolCD 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 i
508. nk 1 gt end 2 begin non blinking cursor SPE T6963C cursor 1 7 SPI T6963C cursor blink 0 end end Delay ms 300 end j 064 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Move cursor even if not visible Inc cposx gt if cposx SPI_T6963C_txtCols then begin cposx 0 ine eposy 7 if cposy SPI_T6963C_grHeight div SPI_T6963C_CHARACTER HEIGHT then cposy 0 end SPI T6963C set_cursor cposx eposy Delay _ms 100 end end HW Connection vec Jano josc 2 a v fe NS S A wo Toshiba T6963C Graphic LCD 240x128 Contrast Adjustment SPI T6963C Gicd HW connection mikroPascal PRO for dsPICSO 33 and PIC24 T6963C Graphic Lcd Library The mikroPascal PRO for dsPIC30 33 and PIC24 provides a library for working with Glcds 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 F
509. nly 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 dsPIC30 33 and PIC24 then you should consider the possibility of purchasing the license key Who Gets the License Key Buyers of the mikroPascal PRO for dsPIC30 33 and PIC24 are entitled to the license key After you have completed the payment procedure you have an option of registering your mikroPascal PRO for dsPIC30 33 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 I work offline based on your current internet connection and click Request license key now button 35 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 How to register Choose registration method Twork online Choose this option if you are connected to nternet You will be directed to a web page which will help you o send the license key request This is the Fastest way of i taining the license key it takes minutes to get it in your mailbox Recommended j I work offlin
510. node ID CANSPISetOperationMode _CANSPI_ MODE NORMAL OxFF set NORMAL mode while TRUE do endless loop begin Msg Revd CANSPIRead Rx ID RxTx Data Rx Data_Len Can Rev Flags receive message if Rx_ID ID 1st and Msg Revd 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 215 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 HW Connection Shielded twisted pair j Example of interfacing CAN transceiver MCP2510 with MCU via SPI interface MikroElektronika 216 mikroPascal PRO for dsPICSO 33 and PIC24 Compact Flash Library The Compact Flash Library provides routines for accessing data on Compact Flash 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 C 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
511. 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 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 should be properly cofigured by the means of SPI_Ethernet_Init routine 0x02 MAC Multicast traffic receive filter flag When set MAC Spr Ethernet MUITICAST multicast traffic will be enabled e it 5 0x20 CRC check flag When set packets with invalid CRC field SPT Ethernet Ene will be discarded rt e o 7 0x80 MAC Unicast traffic receive filter flag When set MAC Serer hernet UNICAS unicast traffic will be enabled 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 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 ane Pekernet BROADCAST broadcast traffic will be enabled S 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 enable
512. not conflicting with another peripheral When a pin selectable peripheral is active on a given I O pin it takes priority over all other digital I O and digital communication peripherals associated with the pin Important Before using any of the digital peripherals or its library routines user must set the desired pins as input output and assign the desired peripheral to these pins Library Routines Unlock_IOLOCK Lock_IOLOCK PPS_Mapping Unlock_IOLOCK Prototype Unlocks I O pins for Peripheral Pin Mapping PRetums Nothing SSCS example Usiock Tomek SSCS Moes noe OoOO Lock_IOLOCK Prototype Locks I O pins for Peripheral Pin Mapping fexample rock 10meR 412 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 PPS Mapping Prototype function PPS Mapping rp num input output funct_name byte word Sets desired internal MCU module to be mapped on the requested pins Parameters rp num Remappable pin number Consult the appropriate datasheet for adequate values direction Sets requested pin to be used as an input or output See Direction Parameters for adequate values funct name Selects internal MCU module function for usage See Input Functions or Output Functions for adequate values 0 if non existing peripheral pin is selected 1 if desired function is not implemented for the chosen MCU 2 if any of the other RPOUT registers is configured to output the SCK1O
513. nstants depends on the oscillator frequency Rems Noting OOS Example Delay_us 10 Ten microseconds pause Maes Non 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 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 CA E Example Delay_ms 1000 One second pause notes For generating dlayo wih varabe as O O 152 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 VDelay_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 conven
514. nt 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 y 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 Show more info Click on Yes button you ll prompted for an active comment file 103 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Look in Easy_GSM_GPRS activeComment 2 activeComment2 My Recent Documents File name Files of type Active Link Files xml Cancel 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 b
515. nts in vector s Dot product value nurmelerns 1 7 X srcV1 n srcV2 n n 0 var vecl array 3 of word rslt Vector Dot veci vecli 3 W0 W2 used not restored W4 W5 used not restored AccuA used not restored CORCON saved used restored mikroPascal PRO for dsPIC30 33 and PIC24 Vector_Correlate numElemsV2 word Description Function calculates Vector correlation using convolution N L rinj gt x kl y k n k 0 where x n defined for n e 0 N y n defined for n e 0 M M lt N r n defined for n e 0 N M 1 Prototype procedure Vector Correlate var vl v2 dest array 1024 of word numElemsV1 Parameters vi first vector v2 second vector numElemsV1 number of the first vector elements numElemsV2 number of the second vector elements dest result vector var vecl array 3 of word vConDest array 10 of word Vector Correlate vecl vecl vConDest 3 3 7 Notes W0 W7 used not restored 648 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Vector_Convolve Prototype procedure Vector Convolve var vl v2 dest array 1024 of word numElemsV1 numElemsV2 word Description Function calculates Vector using convolution y nj gt x k h n k nelo My k 0 yin xik h n k M N k n M 1 aat ne N N M 1 y nj x k h n k k n M 1 Parameters vi first vector v2 second vector numElemsV
516. o Assignment Statements Compound Statements Blocks Conditional Statements Iteration Statements Loops Jump Statements asm Statement 223 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 Statements 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 lt n do begin temp a i alil a b i temp t s 2 LT 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 MikroElektronika 2
517. o 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 Program Organization mikroPascal PRO for dsPIC30 33 and PIC24 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 Module 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 Otherwise 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 J BK RK RR RRR AK E A A Ok k k k Declarations globals J BR RK RK KAR AK AR A A AA A k A aE A a A aE A k k ak k k k E A k k k constants declarations CORSE soi MikroElektronika 190 mikroPascal PRO for dsPIC30 33 and PIC24 types declarations type variables declarations var Name Name2 type absolute 0x123 external volatile register sfr labels declarations label procedur
518. o 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 MikroElektronika 52 mikroPascal PRO for dsPIC30 33 and PIC24 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 Rralect Fes ay Y Restore Last Opened Project Restore All Opened Files h w Editor Colors e 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 Timeout Interval Auta Complete Enable Auto Save GE Eohi o Highlighter Style Y Highlight brackets Highlight begin end pairs Spelling Y Check Spelling Comment st
519. oElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 implementation end program MyProgram var 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 dsPIC30 33 and PIC24 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 yar rto eit tnvaisd Note Bit variables can not be initialized Bit variables can not be members of structures and unions 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 MikroElektronika 141 mikroPascal PRO for dsPIC30 33 and PIC24 Interrupts The dsPIC30 33 and PIC24 interrupt controller mod
520. oPascal PRO for dsPIC30 33 and PIC24 8 Put the J11 and J10 Jumpers in the correct position as showed in the picture below PGC RF3 RB7 RB4 RF8 9 Next open MPLAB and select the appropriate device by choosing Configure Select Device a MPLAB IDE v8 36 Output File Edit View Project Debugger Programmer Tools Easit Window Help lect Device Dg Ba S th oe es ki a e an Configuration Bits Build Version Control Find in Files External Me ID Memory Settings 10 After device selection click on the File gt Import Open file dialog box should appear Then go to the project folder and open the generated HEX file UART hex Note This is very important because hex file contains configuration bit settings which are essential for the proper functioning of the user code mikoPascal PRO for dsPIC30 33 and PIC24 11 Next click the File Import Open file dialog box should appear Then go to the project folder and open the generated COFF file UART cof a MPLAB IDE v8 36 Output REY Edit view Project Debugger Programmer Tools Configure Window Help Ctri N Ctrl 0 Ctrl E Open Workspace Save Workspace Save Workspace As ose Workspace Export Print Recent Files Recent Workspaces Exit dsPIC30F4013 oab sab IPO denovzc or mikroPascal PRO for dsPICSO 33 and PIC24
521. of the font width they will be scaled to the nearest lower number that is a multiple of the font width 518 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 T6963C_set_cursor Prototype procedure T6963C_set_cursor x y byte Sets cursor to row x and column y Parameters x cursor position row number y cursor position column number FRetums Noting SSS Example T6963C_ set _cursor cposx cposy Notes ne OOO T6963C_displayGrPanel Rems Nothing OOOO display graphic panel 1 T6963C_displayGrPanel 1 None T6963C_displayTxtPanel Rems Nothing OSC Toshiba Glcd module needs to be initialized See the T6963C_init routine display text panel 1 T6963C_displayTxtPanel 1 Notes Nowe OSS MikroElektronika 979 mikroPascal PRO for dsPICSO 33 and PIC24 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 Gled module needs to be initialized See the T6963C_init routine set graphic panel 1 as current graphic panel T6963C_setGrPanel 1 T6963C_setTxtPanel text D will be peee at this text panel Rems nom OOOO set text panel 1 as current text panel T6963C_setTxtPanel 1 T6963C_panel Fill Rems Nothing OSC Toshiba Gled module needs to be in
522. oller must be connected to ECAN transceiver which is connected to the ECAN bus The ECAN module must be in a mode in which transmission is possible See ECANxSetOperationMode send messag xtended ECAN message with appropriate ID and data var tx flags word data array 8 of byte msg id longint ECAN1SetOperationMode _ECAN MODE NORMAL OxFF set NORMAL mode ECANI1 must be in a mode in which transmission is possible tx flags ECAN TX PRIORITY 0 and _ECAN TX _XTD_ FRAME and ECAN TX NO RTR FRAME set message flags ECAN1Write msg id data 1 tx flags ECAN library routine require you to specify the module you want to use To select the desired ECAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of ECAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 308 mikroPascal PRO for dsPICSO 33 and PIC24 ECAN Constants There is a number of constants predefined in the ECAN 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 ECAN_OP_MODE Constants The ECAN OP MODE constants define ECAN operation mode The routine ECANxSetOperationMode expect one of these as their argument Copy Code To Clipboard const _ECAN MODE BITS word 0x00E0 Use this
523. olor parameter Valid values 1D13700_BLACK Black color S1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700_Init routine oa 1D13700 Line 0 239 127 S1D13700 WHITE 1D13700 Rectangle Prototype procedure S 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 yl y coordinate of the lower right rectangle corner pcolor color parameter Valid values 1D13700_ BLACK Black color 1D13700_ WHITE White color Glcd module needs to be initialized See the S1D13700_Init routine 1D13700 rectangle 20 20 219 107 S1D13700 WHITE 331l MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 1D13700_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 yl y coordinate of the lower right rectangle corner pcolor color parameter Valid values 1D13700_BLACK Black color 1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700_Init routine 1D13700 Box 0 119 239 127
524. ompile 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 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 mi
525. on 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 ENC247600 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 SP _Ethernet_24j600_Init while true do _Ethernet_ 243600 doPacket process received packets ENC24J600 write EWRPT Nothing Ethernet module has to be initialized See SP _Ethernet_24j600_Init byte Ethernet 243600 putByte data put an byte into ENC24J600 buffer 506 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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_24j600_Ini
526. on 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 0 Port needs to be initialized for working with the Keypad library see Keypad_Init Example kp Keypad Key Click Notes None OSS MikroElektronika 310 mikroPascal PRO for dsPIC30 33 and PIC24 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 Keypad module connections var keypadPort word at PORTB var keypadPort Direction word at TRISB End Keypad module connections begin ADPCFG OXFFFF oldstate 0 UART1_ Init 9600 Delay ms 100 Keypad Init Initialize Keypad UART1 Write Text Press any key on your kaypad 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 Prepare value for output transform key to it s ASCII val
527. onstant array which contains complex twiddle factors The array is expected to be in program memory See Twiddle Factors for adequate array values Samples array of input samples Upon completion complex array of FFT samples is placed in the Samples parameter var InputSamples array 512 of word ydata Perform FFT DFT 7 stages 128 samples of complex pairs FFT 8 TwiddleCoeff 256 InputSamples Complex array of FFT samples is placed in Samples parameter Input Samples are arranged in manner Re Im Re Im where Im is always zero Output samples are arranged in the same manner but Im parts are different from zero Output samples are symmetrical First half of output samples index from 0 to N 2 is identical as second half of output samples index from N 2 to N Input data is a complex vector such that the magnitude of the real and imaginary parts of each of its elements is less than 0 5 If greater or equal to this value the results could produce saturation Note that the output values are scaled by a factor of 1 N with N the length of the FFT input is expected in natural ordering while output is produced in bit reverse ordering 638 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Twiddle Factors TwiddleCoeff_64 const TwiddleCoeff 64 array 64 of word Ox7FFF O0x0000 Ox7F62 OxF374 Ox7D8A OxE707 Ox7A7D OxDAD8 0x7642 OxCF04 O0x70E3 OxC3A9 Ox6A6E OxB8E3 Ox62F2 OxAECC Ox5A82 OxAST7E
528. or creating a custom set of Glcd images use Glcd Bitmap Editor Tool Important When using this library with dsPIC33 and PIC24 family 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_Init 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 Library Dependency Tree T6963C Trigonometry 566 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 External dependencies of T6963C Graphic Lcd Library The following variables must be defined in all projects using T6963C Graphic Lcd library Description word T6963C Data Port fr LE SPS Write signal Reet SER Read signal 3 spiti Sfr ca fer SE Command Data signal var T6963C ctrlrst sbit sfr Reset signal external var T6963C ctrlwr Direction
529. or dsPIC30 33 and PIC24 I2Cx_Is_Idle Waits for the I C bus to become free This is a blocking function 0 if I C bus is free 1 if IPC bus is not free Requires MCU with at least one C module Used I C module must be initialized before using this function See I2Cx_Init routine var data i byte if I T2E1 Ts rale 2Cl Write data I I 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 3 Number of C modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library I2Cx_Read Reads a byte from the I C 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 Returns Received data Requires MCU with at least one 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 12Cx_Start var take byte Read data and send the not_acknowledge signal take IZC1 Read 1 IC 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 C modules per MCU differs from chip to chip
530. orking area y coordinate of the upper right corner of the working area TP TET Set Calibration Consts 173 776 7S 760 Set calibration constants 618 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 HW Connection dsPIC33FJ128GP710 TFT 320x240 display QO UUURUPULUBU ONY U MI02830T2 Touch Panel TFT HW connection MikroElektronika 619 mikroPascal PRO for dsPICSO 33 and PIC24 UART Library The UART hardware module is available with a number of dsPIC30 33 and PIC24 MCUs The mikroPascal PRO for dsPIC30 33 and PIC24 UART Library provides comfortable work with the Asynchronous full duplex mode You can easily communicate with other devices via RS 232 protocol for example with PC see the figure at the end of the topic RS 232 HW connection You will need a MCU with hardware integrated UART for example ATmega16 Then simply use the functions listed below 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 4 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 Library Routines UARTx_Init UARTx_Init_Adva
531. ortant PWM module uses either Timer2 or Timer3 module Library Routines PWM_Init PWM_Set_Duty PWM_Start PWM_Stop MikroElektronika 431 mikroPascal PRO for dsPICSO 33 and PIC24 PWM_Init Prototype function PWM Init freq hz longint enable channel x timer prescale use_ timer x word word 30F1010 and dsPIC33FJ06GS101 102 202 prototype function PWM Init freq hz longint enable channel x timer prescale word Initializes the PWM module with duty ratio 0 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 timer to be used with the PWM module Valid values 2 Timer2 and 3 Timer3 OxFFFE 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 periodi word pwm_period1l PWM_Init 5000 1 0 2 Notes Number of available PWM channels depends on MCU Refer to MCU datasheet for details 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_
532. otePort localPort reqLength word var flags TEthPktFlags word var i word my reply length bitMask byte 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 MikroElektronika 493 mikroPascal PRO for dsPIC30 33 and PIC24 get 10 first bytes only of the request the rest does not matter here for i j 0 to 9 do getRequest i SPI Ethernet _getByte getRequest 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 don 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 result SPI Ethernet _putConstString httpHeader 7 7 HTTP header result result SPI Ethernet putConstString httpMimeTypeScript with text MIME type add AN2 value to reply Wor
533. otype function TP TFT Press Detect 2 byte Detects if the touch panel has been pressed 1 if touch panel is pressed 0 otherwise Requires lobal 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 DriveY_Up pin DriveY Down Direction Direction of DriveY_Down pin must be defined before using this function Touch Panel module connections DriveX Left sbit at LATB13 bit Drivex Right sbit at LATBII bit DriveY Up gt sbit at LATB12 bit DriveY Down sbit at LATB10 bit Drivex Left Direction sbit at TRISB13 bit Drivex Right Direction sbit at TRISB11 bit DriveY Up Direction 7 sbit at TRISB12 bit DriveY Down Direction sbit at TRISB10 bit End Touch Panel module connections if TP TFT Press Detect lt gt 0 then 616 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 if reading is within display dimension range 0 if readi
534. our device you can save bit configuration as a scheme using svescheme button In case you need this scheme in another project you can load it using eadstheme button There is also a pefaut button which lets you select default configuration bit settings for the selected device Edit Project Oscillator XT wiPLL 8x MCU and Oscillator Clock Switching and Monitor MCU Name p30r4013 E v 5w Disabled Mon Disabled WDT Prescaler BO g j Oscillator Frequency MHz 80 000000 1 16 WDT Prescaler A 1 512 Build Type Release ICD Debug Watchdog Timer Disabled POR Timer alue aoe ae l dms rosc F80000 0x8706 FUDT F80002 0x003F Brown Out oltage FBORPOR F80004 Ox87B3 FGS F8000A 0x0007 IcD F8000C 0xC003 Save Scheme Configuration Registers Load Scheme Reserved PBOR Enable Enabled Master Clear Enable Default Enabled General Code Segment Write Protect Disabled General Segment Code Protection Disabled General Output Settings Related topics Project Settings Customizing Projects 700 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 great care beca
535. output due to its silicon bug in SPI hardware If you try lower dsPIC30 33 and PIC24 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 24j600 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 thereis EthEnc24j600Private 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 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 m spi SPI Ethernet j String MikroElektronika 499 mikroPascal PRO for dsPIC30 33 and PIC24 External dependencies of SPI Ethernet ENC24J600 Library The following variables must be defined
536. 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 dsPIC30 33 and PIC24 specifics Build all files as library enables user to use compiled library mc1 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 87 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Options Output Settings Output Settings Y Generate ASM file V Include HEX opcodes Include ROM constants Y Include ROM Addresses Y Generate list file Include debug info Y Include source lines in output files Y Generate COFF file V Long HEX Format Optimization level Four V Enable 554 optimization Compiler F Case sensitive F Dynamic link for string literals Build all files as library mikroPascal PRO for dsPICSO 33 and PIC24 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 gt Active Comments Editor or by clicking the Active Comment Editor Icon A from Tools toolbar Active Comments Editor Enter comment name activeComment
537. owever 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 mikroPascal PRO for dsPICSO 33 and PIC24 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 help 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
538. pe sequences to be interpreted by preceding them with a backslash For instance metacharacter matches beginning of string but matches character and matches WA etc Examples unsigned matches string unsigned unsigned matches string unsigned Escape sequences Characters may be specified using a escape sequences n matches a newline t a tab etc More generally xnn where nn is a string of hexadecimal 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 x 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 r car return CR same as x0d form feed FF same as x0c a alarm bell BEL same as x07 e 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 MikroElektronika 108 mikroPascal PRO for dsPIC30 33 and PIC24 Examples count
539. peg 150 193 65 TFT_Color16bitloRGB Prototype procedure TFT Colorl6bitToRGB color word rgb red rgb green rgb blue bpyte 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 Example TFT_Color1 6bitToRGB start_color red_ start green_ start blue_ start 604 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 HW Connection 99 e i TERN dsPIC33FJ128GP710 TFT 320x240 display MI0283072 TFT HW connection MikroElektronika 605 mikroPascal PRO for dsPICSO 33 and PIC24 Touch Panel Library The mikroPascal PRO for dsPIC30 33 and PIC24 provides a library for working with Touch Panel Library Dependency Tree Touch Panel apc External dependencies 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 TRISC13 bit var DriveB Direction sbit siz Direction of the DriveB pin var
540. ple Here is a step by step mikrolCD Debugger Example Se First you have to write a program We will show how the mikrolCD works using this example program Lcd Test LCD module connections var var var var var var var var var var var var LC LC LC EC LC LC LC iC RS sbit at EN sbit at D4 sbit at DS Spit at D6 sbit at D7 Sbit at RS Direction LC LC LC LC PN RS NES N EN Direction D4 Direction DS Direction D6 Direction D7 Direction sbit sbit sbit sbit sbit sbit LATDO bit LATD1 bit LATBO bit LATB1_ bit LATB2 bit LATB3 bit at at at at at at End LCD module connections var text i begin ADPC text Led_ Led _ Led array 16 byte FG OxFFFF mikroElektronika Tare 4 Cmd _LCD_CLEAR Cmd _ LCD _CURSOR_OFF for end i 1 to 17 do text i 1 Led Che i i of char TRISDO bit TRISD1 bit TRISBO bit TRISB1 bit TRISB2 bit TRISB3 bit 119 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 ES EP NO 2 After successful compilation and MCU programming press F9 to start the mikrolCD After the mikrolCD initialization a blue active line should appear o a H begin Watch Values Liros ne perre Saas B Be E R e text s mikroElektronika gt E Gh G Bee gt o E A 50 ab Add Remove
541. portant 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 Examples int 8 10 matches strings which contain 8 9 or 10 instances of the int routi 0 9 at e matches routi0e routile routine routinne routinnne etc Metacharacters Backreferences Metacharacters 1 through 9 are interpreted as backreferences matches previously matched subexpression Examples 1 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 Ti MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Keyboard Shortcuts Below is a complete list of keyboard shortcuts available in mikroPascal PRO for dsPIC30 33 and PIC24 IDE Fi C Alt X Close mikroPascal PRO for dsPIC30 33 and PIC24 Ctrl N Ctrl O Ctrl Shift O Ctrl Shift N Ctrl K Ctrl F4 Ctrl Shift E Ctrl F9 Shift F9 Ctrl
542. prescaler pri_prescaler slave select data_ sample clock idle and determine the working mode for SPI The master mode parameter determines the working mode for SPI module The parameter mode16 determines the data length mode which can be 8 bits per transmitions cycle or 16 bits The parameter sec _prescaler determines the value of the secondary SPI clock prescaler Used only in the Master Mode Secondary SPI Clock Prescaler Value Description Predefined library const Secondary Prescaler 1 _PRESCALE SEC 1 Secondary Prescaler 1 _PRESCALE SEC 2 Secondary Prescal _PRESCALE_SEC_3 secondary Prescaler 1 PI PRESCALE SEC 4 Secondary Prescaler 1 PI PRESCALE SEC 5 Secondary Prescal 6 PI PRESCALE SEC _6 ry er dt _SPI_ Secondary Prescaler 1 8 _SPI_PRESCALE_SEC_8 The parameter pri prescaler determines the value of the primary SPI clock prescaler Used only in the Master Mode MikroElektronika 469 mikroPascal PRO for dsPICSO 33 and PIC24 Parameters The parameter slave select determines whether the Slave Select SS pin is used in communication Valid 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 The parameter data sample determines the sample moment phase of input data The parameter clock idle determines the behaviour of the SPI clock CLK line in IDLE phase The parameter edge
543. quals 369 ptr TBytePtr arr ptr byte Qarr end 214 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Typedef Specifier The specifier t ype 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 lt type_ definition gt The type keyword assigns synonym to lt type definition gt The synonym needs to be a valid identifier A declaration starting with the t ype specifier does not introduce an object or a 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 dsPIC30 33 and PIC24 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 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 cons
544. r dsPICSO 33 and PIC24 1D13700_Init Prototype procedure 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 D13700 Data Port Data Bus Port D13700 WR Write signal pin D13700 RD Read signal pin D13700 A0 Command Data signal pin D13700 R ES Reset signal pin D13700 _ CS Chip Select signal pin D13700 Data Port Direction Data Bus Port Direction D13700 WR Direction Direction of Write signal pin D13700_R D Direction Direction of Read signal pin D13700 A0 Direction Direction of Command Data signal pin D13700 R ES Direction Direction of Reset signal pin D13700 CS Direction Direction of Chip Select signal pin 1 1 1 1 1 1 S1 S1 51 1 1 1 Requires Global variables SL SL S1 51 Su ADL S1 lt 51 SL are ll Sl SL must be defined before using this function 3700 Data Port b 3700 WR sbit at 3700 R D sbit at 3700 AO sbit at 3700 R ES sbit at 3700 CS sbit at yte at PORTD LATC2 bit LATE bit LATCO bit LATC3 bat LATC4 bit 3700 Data Port Direction byte at PORTD 3700 W 3700 R R Direction D Direction 3700 AO Direction 3700 R ES Direction 3700 CS Direction S1D13700 module connections var I var a var L A var L 3 var 1 var L I v
545. r example UART library for 30F4013 is different from UART library for 30F6014 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 m1 xk 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 mikroPascal PRO for dsPIC30 33 and PIC24 Using Microchip MPLAB IDE with mikroElektronika compilers This new feature will boost your productivity by enabling you to import your code in a non mikroElektronika enironment Microchip s MPLAB With the introduction of COFF File in mikroElektronika compiler it is possible to debug and analyze your code through a software or hardware simulator Debugging Your Code If your program has been built correctly the compiler should generate a hex file anda cof file The cof file contains all the information necessary for high level debugging in MPLAB and it should be loaded by selecting the File gt Import menu in the MPLAB Once you have done this you have two choices either to use MPLAB ICD 2 Debugger if you have the appropriate hardware or MPLAB Simulator Trademarks The Microchip name and logo the Microchip logo Accuron dsPIC KEELOQ KEELOQ logo microlID MPLAB PIC PlCmicro PICSTART PRO MATE rfPIC and SmartShunt are registe
546. r 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 expression 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 si zeof 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
547. r relevant when using LATx for output MODIFY Data 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 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 116 MikroElektronika CHAPTERS mikroPascal PRO for dsPIC30 33 and PIC24 Language Reference mikroPascal PRO for dsPICSO 33 and PIC24 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 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 118 MikroE
548. racter by default is only guaranteed to match beginning of the input string text and the s metacharacter only at the end Embedded line separators will not be matched by or 7 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 Awww unicode org unicode reports tr18 109 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Metacharacters Predefined classes w an alphanumeric character including _ W a nonalphanumeric character d a numeric character D anon numeric character s 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 soon but not routine routime and so on Metacharacters Word boundaries A word boundary b is a spot between two characters that has an alphanumeric character w on one side and a nonalphanumeric character w on the other side in either order counting the imaginary characters off the beginning and end of the string as matching a w b match a word boundary B match a non word boundary Metacharacters Iterators Any item of a regular expression may be followed by another type of metacharacters iter
549. raffic receive filter flag When set MAC _SPI_Ethernet_2435600_ broadcast traffic will be disabled BROADCAST 0x02 MAC Multicast traffic receive filter flag When set MAC _SPI_ Ethernet _243600_ multicast traffic will be disabled MULTICAST ive fi i _SPI_Ethernet_24j600_ UNICAST Nothing Ethernet module has to be initialized See SPI_Ethernet_24j600_Init SPI Ethernet 247600 Disable SPI Ethernet 24j600 CRC Or SPI Ethernet 24j600_ UNICAST disable CRC checking and Unicast traffic This routine will change receive filter configuration on the fly It will not in any way mess with enabling ENC24J600 module The should be properly cofigured by the means of SPI_Ethernet_24j600_Init routine routine Advanced filtering available in the ENC243600 module such as Pattern Match Magic Packet and Hash Table cannot be disabled by this routine disabling receive transmit logic or any other part of the The ENC243600 module should be properly cofigured by the means of SPI_Ethernet_24j600_Init ENC2 43600 module MikroElektronika mikroPascal PRO for dsPIC30 33 and PIC24 SPI_Ethernet_24j600_doPacket Prototype function SPI Ethernet _ 243600 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 functi
550. rameter color determines the line color O white 1 black and 2 inverts each dot Glcd needs to be initialized for SP communication see SPI_Glcd_lInit routine Draw a horizontal line between dots 10 20 and 50 20 SPI Glcd H Line 10 50 20 1 moes Noe SSS MikroElektronika 523 mikroPascal PRO for dsPICSO 33 and PIC24 SPI_Glcd_Rectangle Prototype procedure SPI Glcd Rectangl 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 determines the color of the rectangle border O white 1 black and 2 inverts each dot Glcd needs to be initialized for SP communication see SPI_Glcd_lInit routine Draw a rectangle between dots 5 5 and 40 40 SPI Gled Rectangle 5 5 40 40 1 7 SPI_Glcd_Rectangle_Round_Edges Prototype procedure SPI Glcd Rectangle Round Edges x upper left byte y upper left PIUSE x bottom right gt byte y bottom right byte radius byte color byte Draws a rounded edge rectangle on Glcd Parameters
551. rary routines require you to specify the module you want to use To select the desired ADC module simply change the letter x in the routine prototype for a number from 1 to 2 Example _ ADC1 Init Initialize ADC1 module with default settings Number of ADC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 241 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 ADCx_Init_Advanced Prototype dsPIC30F and PIC24FJ prototype procedure ADC1 Init Advanced Reference word AsSPIC33FJ and PIC24HJ prototype procedure ADCx Init Advanced ADCMode word Reference word Description This routine configures the internal ADC module to work with user defined settings Parameters ADCMode resolution of the ADC module Reference voltage reference used in ADC process Voltage reference Internal voltage reference _ADC_INTERNAL REF External voltage reference _ADC_EXTERNAL REF Requires MCU with built in ADC module ADC library routines require you to specify the module you want to use To select the desired ADC module simply change the letter x in the routine prototype for a number from 1 to 2 ADC1 Init Advanced _ ADC 10bit _ADC_ INTERNAL REF sets ADC module in 12 bit resolution mode with internal reference used al Number of ADC modules per MCU differs from chip to chip Please read the appropriate datasheet
552. rd gt 0 and x coord lt 127 and y_ coord lt 63 then Glcd_Dot x_coord y coord write erase 2 if x coord gt 0 and y coord gt 0 and x coord lt 127 1 and y_coord lt 63 1 then Gled Box x coord y coord x coord 1 y coord 1 write erase 3 if x coord gt 1 and y coord gt 1 and x coord lt 127 2 and y_coord lt 63 2 then Gled Box x coord 1 y coord 1 x coord 2 y coord 2y write erase end end end end end MikroElektronika 613 mikroPascal PRO for dsPICSO 33 and PIC24 Touch Panel TFT Library The mikroPascal PRO for dsPIC30 33 and PIC24 provides a library for working with Touch Panel for TFT Library Dependency Tree Touch Panel apc 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 DriveX Left So piti var DriveX Right sbit sfr external DriveX_Right line DriveX Right sbit at T Diti var DriveY Up sbit sfr external DriveY_Up line DriveY Up i a TB bits var DriveY Down sbit sfr external DriveY_Down line DriveY Down TB10 bit var DriveX_ Left Direction sbit sfr Direction of the DriveX_Left pin var DriveX_Left Direction external sbit at TRISB13 bit var DriveX Right Direction sbit sfr Direction of the DriveX_Right var DriveX
553. reads analog value from the channel 1 and sends readings as a text over UART1 Copy Code To Clipboard program ADC on LEDs var ADCresult word txt array 6 of char begin PORTB 0x0000 clear PORTB TRISB OxFFFF PORTB is input ADC1 Init Enable ADC module UART1_ Init 9600 Initialize UART communication while TRUE do begin ADCresult ADC1 Get _Sample 1 Acquire ADC sample WordToStr ADCresult txt convert its value to string UART1 Write Text txt and send it to UART terminal Delay _ms 50 end end MikroElektronika 244 mikroPascal PRO for dsPIC30 33 and PIC24 HW Connection SUB D 9p i CONNECT Receive to MCU TO PC data Rx a CABLE ae ic 3 CONNECT i i Send PC TO MCU i Data Tx SUB D 9p ADC HW connection 245 mikoPascal PRO for dsPIC30 33 and PIC24 CAN Library mikroPascal PRO for dsPIC30 33 and PIC24 provides a library driver for working with the dsPIC30F CAN module 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
554. red CORCON saved used restored Vector_Min Prototype function Vector Min var Vector array 1024 of word word var MinIndex word word Description This function finds minimal value in vector minVal min srcV n n e 0 numElems 1 If srcV i srcV j minVal and i lt j thenMinIndex j Parameters Vector original vector numElems number of elements in vector MinIndex index of minimum value Minimum value minVa1 Requires Nothing var vecl array 3 of word index rslt z word rslt Vector Min veel 3 index WO W5 used not restored mikoPascal PRO for dsPIC30 33 and PIC24 Vector_Max Prototype function Vector Max var Vector array 1024 of word numElems word var MaxIndex word word Description This function find maximal value in vector maxVal max srcV n n e 0 numElems 1 If srcV i srcV j maxVal andi lt j thenmaxIndex j Parameters Vector original vector numElems number of elements in vector s MaxIndex index of maximum value Returns Minimum value maxVa1 var vecl array 3 of word index rslt i word rslt Vector Max vecl 3 index Notes W0 W5 used not restored Vector _Dot Prototype function Vector _ Dot var vl v2 array 1024 of word numElems word word Function calculates vector dot product Parameters v1 first vector v2 second vector Elems number of eleme
555. red trademarks of Microchip Technology Incorporated in the U S A and other countries Related topics COFF File Using MPLAB ICD 2 Debugger Using MPLAB Simulator Using MPLAB ICD 2 Debugger Important It is assumed that MPLAB and USB drivers for MPLAB ICD 2 Debugger are previously installed Procedure described below is also relevant for MPLAB ICD 3 Debugger Be sure to import compiled hex file prior to importing cof file because it contains configuration bit settings which are essential for the proper functioning of the user code To successfully use MPLAB ICD 2 Debugger with generated cof file follow the steps below 1 First of all start mikroPascal PRO for dsPIC30 33 and PIC24 and open the desired project In this example UART project for EasydsPIC4A board and dsPIC30F4013 will be opened 2 Open Tools gt Options gt Output settings and check the Generate COFF file option and click the OK button 3 After that compile the project by pressing Ctrl F9 4 Connect USB cable and turn on power supply on EasydsPIC4A 5 Program the MCU by pressing F11 6 Connect external power supply USB cable from PC and modular interface cable to the MPLAB ICD 2 Debugger s appropiate sockets like on the picture below 704 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 7 Connect second end of the modular interface cable to the ICD RJ12 socket of EasydsPIC4A 105 mikr
556. res t stremp txt txt_sub compares strings txt and txt sub and returns returns a difference between the first differing characters in this case 69 mikoPascal PRO for dsPIC30 33 and PIC24 strcpy ie procedure strcpy var sl s2 string The function copies the value of the string s2 to the string s1 and appends a null character to the end of s1 mikroElektronika an mikr strcpy txt txt sub Gopies string Ext s b to txt strlen i aa function strlen var s string word The function returns the length in words of the string s The length does not include the null terminating character mikroElektronika res strlen txt calculates the length of the txt string result 16 strncat Prototype procedure strncat var sl s2 string size word Description The function appends at most size characters from the string s2 to the string s1 and terminates s1 with a null character If s2 is shorter than the size characters s2 is copied up to and including the null terminating character mikroElektronika txt sub mikr Ext 5S 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 strncpy Prototype procedure strncpy var sl s2 string size word Description The function copies at most size characters from
557. resent on the network to fetch assigned DNS IP address Returns Pointer to the global variable holding DNS IP address Ethernet module has to be initialized See SPI_Ethernet_Init vV dnsIpAddr array 4 of byte user DNS IP address buffer memcpy dnsIpAddr SPI Ethernet 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 SPI_Ethernet_getlpMask peratia Prototype function SPI Ethernet getIpMask This routine should be used when DHCP server is present on the network to fetch assigned IP subnet mask Returns Pointer to the global variable holding IP subnet mask Requires Ethernet module has to be initialized See SPI_Ethernet_Init Available for PIC18 family MCUs only var 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 location returned by this routine into its own IP subnet mask buffer These locations should not be altered by the user in any case 486 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_Ethernet_confNetwork Prototype procedure SPI Ethernet _confNetwork var ipMask gwIpAddr dnsIpAddr array 4 of byte Configures network ener IP subnet mask
558. returns zero iscntrl r returns OxFF iscntrl o returns 0 656 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 isdigit erates function isdigit character byte word Function returns OxFF if the character is a digit 0 9 otherwise returns zero isdigit o returns OxFF isdigit i jg returns 0 isgraph Prototype function isgraph character byte word Description Function returns OxFF if the character is a printable excluding the space decimal 32 otherwise returns zero isgraph o returns OxFF 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 islower 0 returns OxFF res islower A returns 0 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 ispunct returns OxFF ispunct 1 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 isspace l returns 0 mikroPascal PRO for dsPIC30 33 and PIC24 isupper Prototype funct
559. ring strappendsuf Prototype procedure strappendsuf var sl string letter char The procedure appends character at the end of the string txt z mikro strappendsuf E txt adds letter E at the end of the txt string Prototype The function returns length of passed string mikrol res length txt calculates and returns the length of the txt string 680 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 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 FRetums Number of seconds since January 1 1970 0h0Omnd0s var tsl TimeStruct Epoch longint what is the epoch of the date ints poch Time dateToEpoch tsl mikroPascal PRO
560. roElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 589 mikroPascal PRO for dsPIC30 33 and PIC24 TFT_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 FT DataPort Data Port FT WR Write signal pin RD Read signal pin r CS Chip Select signal pin l RS Register Select signal pin FT RST Reset signal pin DataPort Direction Direction of Data Port l WR Direction Direction of Write signal pin l RD Direction Direction of Read signal pin FT CS Direction Direction of Chip Select signal pin RS Direction Direction of Register Select signal pin l 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 LATDI12 b
561. rocedure SPI Glcd Set Page page byte Retums 23 page number Valdvalues 7 SSCS Example ser orca see ase OOOO Notes For side x axis and page layout explanation see schematic atthe bottom ofthis pags 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 x_pos position on x axis Valid values 0 63 Rems Nong OOOO fexample ser era seee O O OOOO Notes For side x axis and page layout explanation see schematic atthe botom ofthis pags 520 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_Glcd_Read_Data Reads data from the current location of GIcd memory and moves to the next location Returns One byte from Glcd memory Requires Glcd needs to be initialized for SP 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 var Peeks byte SPI_Glcd_Write_Data rs procedure SPI Glcd Write Data data_ byte Writes one byte to the current location in Glcd memory and moves to the next location data_ data to be written Requires Glcd needs to be initialized for SP 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_S
562. roject level defines Image Files EEPROM Files Active Comments Files Output Files Led hex Led asm Other Files m nnsansansnasani baskan SC Souri B aa eue w palosd ii dabeue y palo Prete tt tt 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 dsPIC30 33 and PIC 24 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 MikroElektronika 86 mikroPascal PRO for dsPIC30 33 and PIC24 Options Tools Tool Name Notepad File Name C WINDOWS NOTEPAD EXE ar E Parameters Macro HEX_FILE_NAME Full path and name of the out V Insert Shortcut F11 v E Clear all fields C Close when finished OK Apply Cancel Output settings By modifying Output Settings user can configure the content of the
563. rom Project menu select Export Project or hit Ctrl Alt E Following window will appear Export Project Select project to export C Program Files MikroelektronikalmikroPascal PRO For dsPIC Examples Other Time Time_Demo m Select destination folder D Project Gl 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 6 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 i 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 MikroElektronika 106 mikroPascal PRO for dsPICSO 33 and PIC24 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 fu from the Watch Values Window Available Interrupts Ox0004 ReservedTrapO 0x0006 Osci
564. rom the Debugger Toolbar 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 dsPIC device behavior i e it doesn t update timers interrupt flags etc Related topics Software Simulator Debug Windows Software Simulator Debugger Options 129 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Software Simulator Debug Windows Debug Windows This section provides an overview of available Debug Windows in mikroPascal PRO for dsPIC30 33 and PIC24 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 sho
565. ronika mikoPascal PRO for dsPIC30 33 and PIC24 TES63C cursor blink 1 end 2 begin non blinking cursor T6963C cursor 1 T6963C cursor blink 0 end end Delay ms 300 end i Move cursor even if not visible a Inc cposx if cposx begin cposx 0 Inc cposy if cpos T6963C_grHeight div T6963C_ CHARACTER HEIGHT then cposy 0 end T6963C set cursor cposx eposy T6963C_txtCols then r y y Delay ms 100 end end HW Connection Toshiba T6963C Graphic LCD 240x128 a a av Q S oe w Contrast Adjustment T6963C Glcd HW connection MikroElektronika 587 mikroPascal PRO for dsPICSO 33 and PIC24 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 dsPIC30 33 and PIC24 provides a library for working with HX8347 D 320x240 TFT Led 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 dr
566. ry Led Library Manchester Code Library Multi Media Card Library OneWire Library Peripheral Pin Select Library Port Expander Library PS 2 Library PWM Library PWM Motor Library RS 485 Library Software I 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 Digital Signal Processing Libraries FIR Filter Library IIR Filter Library FFT Library Bit Reverse Complex Library Vectors Library Matrices Library MikroElektronika 238 mikroPascal PRO for dsPIC30 33 and PIC24 Miscellaneous Libraries Button Library C Type Library Conversions Library Setjmp Library String Library Time Library Trigon Library Trigonometry Library See also Built in Routines 239 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Hardware Libraries ADC Library CAN Library CANSPI Library Compact Flash Library Enhanced CAN Library EEPROM Library Epson S 1D13700 Graphic Led Library Flash Memory Library Graphic Lcd Library IC Library Keypad Library Led Library Manchester Code Library Multi
567. s 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_24j600_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 adju by the user to achieve desired reply sted MikroElektronika 509 mikroPascal PRO for dsPIC30 33 and PIC24 SPI_Ethernet_24j600_UserUDP Prototype B Parameters function SPI Ethernet 24j600_ UserUDP var remoteHost array 4 of byte remotePort destPort reqLength word var flags TEthj600PktFlags word 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_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 remoteHost Client s
568. s a pointer pointing to a 3 pEr r 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 pire byte begin i 10 assign value 10 to variable i is at the address 0x0039 J Se assign value 5 to variable j is at the address 0x003A ptrl i ptri is a pointer to byte pointing to i ptr2 Qj ptr2 is a pointer pointing to j x g pErZ peri result is equal to the distance between the two pointed addresses x 1 1 byte x i ptr pira result is equal to the difference of the values pointed to x 5 end Records Arecord 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
569. s 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 mikrolCD while Power Up Timer is enabled Trying to Step Into F7 the mikroPascal PRO for dsPIC30 33 and PIC24 Library routines Use Step Over F8 command for these routines It is not possible to force Code Protect while trying to debug MCU with mikrolCD Trying to debug MCU with mikrolCD with pull up resistors set to ON on RB6 and RB7 Related topics mikrolCD Debugger Debug Windows Debugger Options MikroElektronika 122 mikroPascal PRO for dsPICSO 33 and PIC24 mikrolCD Debugger Windows Debug Windows This section provides an overview of available Debug Windows in mikroPascal PRO for dsPIC30 33 and PIC24 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
570. s messages from Slaves Messages are multi byte so this routine must be called for each byte received Parameters data buffer 7 byte buffer for storing received data Data will be stored in the following manner data_buffer 2 message content data_buffer number of message bytes received 1 3 data_buffer is set to 255 when message is received data buffer is set to 255 if error has occurred data_buffer 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 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 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 Parameters data_buffer data to be sent datalen number of bytes for transmition Valid values 0 3 slave address Slave s address Requires 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 441 mikro
571. sapplication 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 33 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 LIMITED 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 GOVERN
572. selected file is already open its current Editor tab will become active Printing an open file 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 Save from the drop down menu or press Ctrl S or click the Save File Icon A from the File Toolbar 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 698 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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
573. sheet for operation mode codes Returns Current operation mode m The ECAN routines are supported only by MCUs with the ECAN module Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus check whether the ECAN1 module is in Normal mode and if it is do something if ECAN1GetOperationMode _ECAN MODE NORMAL then begin end ECAN library routine require you to specify the module you want to use To select the desired ECAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of ECAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 300 mikroPascal PRO for dsPIC30 33 and PIC24 ECANxInitialize Prototype Description Parameters procedure ECANxInitialize SJW BRP PHSE EG2 PROPSE ECAN CONFIG _ FLAGS word Initializes the ECAN module The internal ECAN module is set to Disable ECAN capture Continue ECAN operation in Idle mode Abort all pending transmissions Clear all transmit control registers Fean clock Fcy Fosc 2 Baud rate is set according to given parameters ECAN mode is set to Normal Filter and mask registers remain unchanged SAM SEG2PHTS WAKFIL and DBEN bits are set according to the ECAN CONFIG FLAGS value SJW as defined in MCU s datasheet ECAN Module BRP as defined in M
574. sisted 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 activity indication This library is designed to simplify handling of the underlying hardware ENC28J60 It works with any dsPIC30 33 and PIC24 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 dsPIC30 33 and PIC24 should be clocked by ENC28J60 clock output due to its silicon bug in SPI hardware If you try lower dsPIC30 33 and PIC24 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 mbas 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 hardwar
575. sor on off n on off parameter Valid values 0 set cursor off and 1 set cursor on Toshiba Glcd module needs to be initialized See the T6963C_init routine set cursor on T6963C cursor 1 None 982 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 eine Toshiba Glcd module needs to be initialized See the T6963C_init routine enable cursor blinking T6963C cursor biink 1 Notes None oO Library Example The following drawing demo tests advanced routines of the T6963C Glcd library Hardware configurations in this example are made for the EasydsPIC4A board and dsPIC30F4013 Copy Code To Clipboard program T6963C 240x128 uses Lib T6963C Consts T6963C module connections var T6963C dataPort byte at PORTB DATA port var T6963C_ctrlwr sbit at LATF2 bit WR write signal var T6963C_ctrlird sbit at LATF1 bit RD read signal var T6963C_ctrlcd sbit at LATFO bit CD command data signal var T6963C_ctrirst sbit at LATF4 bit RST reset signal var T6963C_ctrlwr Direction sbit at TRISF2 bit WR write signal direction var T6963C_ctrird Direction sbit at TRISF1 bit RD read signal direction var T6963C_ctrlcd Direction s
576. space 32 Gled Set Font myfont 5 7 32 Notes None SOS MikroElektronika 398 mikroPascal PRO for dsPICSO 33 and PIC24 Glcd_Write_Char Prototype 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_Font to specify the font for display if no font is specified then default Font Glcd System5x7 font supplied with the library will be used Write character C on the position 10 inside the page 2 Gled Write Char C 10 2 1 7 For x axis and page layout explanation see schematic at the bottom of this page Glcd_Write_ Text Prototype procedure Glcd 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
577. ss of EEPROM eeData 0 Data to be written while eeData lt Ox00FF do begin Eeprom Write eeAddr eeData Write data into EEPROM Inc eeData while WR bit do Wait for write to finish LATB Eeprom Read eeAddr then read the just written data eeAddr eeAddr 2 Next address of EEPROM memory location Delay ms 100 end Delay ms 1000 Wait 1 second eeData OxAAAA for i 0 to 15 do Initializing array of 16 integers with data begin dArr i eeData eeData not eeData end Eeprom Write Block Ox7FFC20 dArr Write entire row of EEPROM data while WR bit do Wait for write to finish eeAddr Ox7FFC20 Address of EEPROM where reading should start for i 0 to 15 do Read the data back begin LATB Eeprom Read eeAddr and show it on PORTB eeAddr eeAddr 2 Next address of EEPROM memory location Delay ms 500 end end MikroElektronika 320 mikroPascal PRO for dsPICSO 33 and PIC24 Epson 1D13700 Graphic Lcd Library The mikroPascal PRO for dsPIC30 33 and PIC24 provides a library for working with Glcds based on Epson 1D13700 controller The S1D13700 Glicd 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 tex
578. symbols and appear automatically Use the folding symbols to hide unhide the code subsections pesmi 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 begin EJ MikroElektronika 54 mikroPascal PRO for dsPICSO 33 and PIC24 Another way of folding unfolding code subsections is by using Alt lt and Alt If you place a mouse cursor over the tooltip box the collapsed text will be shown in a tooltip style box begin N2 begin i PORTA 0 PORTB 0 Led_Init LCD_Out 1 1 txt 0 LCD_Out 2 1 txt 1 delay_ms 1000 Led_Cmad 1 LCD_Out 1 1 txt 1 LCD_Out 2 4 txt 2 delay_ms S00 end 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 BR 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 floating panel
579. t WR write signal direction var T6963C_ctrlrd Direction z Sbit at TRISFI1 bit RD read signal direction var T6963C_ctrlcd Direction sbit at TRISFO bit CD command data signal direction var T6963C_ctrlirst 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 ctrifs shit at LATF6 bit ES signal var T6963C_ctrlmd sbit at LATF5 bit MD signal var T6963C_ctrlce Direction sbit at TRISF3 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 inte 240 128 8 T6963C_writeData Prototype procedure 7T6963C_writeData mydata byte Writes data to T6963C controller mydata data to be written Rems Nothing Example T6963c weitepatanaarty Notes None 910 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 T6963C_writeCommand Prototype procedure T6963C_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 T6963C_ writeCommand T6963C CURSOR POINTE T6963C_setPtr neues proced
580. t 1 mPDsPic exe DBG pP30F4013 MSF GC Y 132 Compilation Started c Program Files Mikroelektronika mikroPascal PRO For dsPIC 1015 Hint Compiling unit c Program Files Mikroele UART mpas 1010 Hint Unit U amp RT mpas has been recompiled UART mpas 133 Compiled Successfully c Program Files MikroelektronikamikroPascal PRO For dsPIC All Files Compiled in 31 ms Used RX bytes 32 100 Free RX bytes Used RX bytes 32 100 Free RX bytes 0 0 Static RAM bytes 41 Dynamic RAM bytes Static RAM bytes 41 Dynamic RAM bytes 2038 Used ROM bytes 820 3 Free ROM byt Used ROM bytes 820 3 Free ROM bytes 31948 97 Project Linked Successfully UART mppds COFF File successfully generated COFF File successfully generated Linked in 609 ms Project U4RT mppds completed 1062 ms Finished successfully 04 Dec 2009 09 37 35 UART mppds 5 0 0 1 5 o o oO 0 0 0 o 0 o oO Double click the message line in the Message Window to highlight the line where the error was encountered 13 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Quick Converter Quick Converter enables the user to easily transform numbers from one base to another Quick Converter Size Sign DECIMAL HEXADECIMAL BINARY CHARACTER Se nsigned 77 00000040 00000000 oooo0000 ooooooo0 01001101 its 22bits O Signed FLOAT DECIMAL 136 89 F t Opn FLOAT 32bit EEE FLOAT 32 bit
581. t Prototype Otis 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 Toshiba Glcd module needs to be initialized See SPI_T6963C SEN routine SPI_T6963C_write text GLCD LIBRARY DE 0 0 SPI_T6963C_ROM_ MODE_XOR 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
582. t array 9 of word Matrix Scale 0x4000 mxl mxDest 2 3 WO W5 used not restored AccuA used not restored CORCON saved used restored numRows numCols lt 214 mikroPascal PRO for dsPICSO 33 and PIC24 Matrix_Multiply Prototype procedure Matrix Multiply var srcl src2 dest array 256 of word numRows1 numCols2 numColslRows2 word Description Function does matrix multiplication dstM i jJ gt gt srcM1 i k srcM2 k j bjk with i e 0 numRows1 1 j e 0 numCols2 1 k e 0 numCols1Rows2 1 Parameters srcl first matrix src2 second matrix dest result matrix numRows1 number of rows in the first matrix numCols2 number of columns in the second matrix numColsilRows2 number of columns in the first matrix and rows in the second matrix var mxl array 6 of word mx2 array 6 of word mxDest array 9 of word Matrix Multiply mxl1 mx2 mxDest 2 2 3 WO W7 used not restored W8 W13 used and restored AccuA used not restored CORCON saved used restored mikoPascal PRO for dsPIC30 33 and PIC24 Matrix_Add Prototype procedure Matrix Add var srcl src2 dest array 1024 of word numRows numCols word Description Function does matrix addition dstM i j srcM4 i j srcM2 i j Parameters srcl first matrix src2 second matrix dest result matrix numRows1 number of rows in the first matrix numCols2 number of columns in the se
583. t var buffer array 17 of byte buffer mikroElektronika SPI Ethernet 243600 putBytes buffer 16 put an RAM array into ENC24J600 buffer SPI_Ethernet_24j600_putConstBytes Prototype procedure SPI Ethernet 243600 putConstBytes const ptr byte n word Description This is MAC module routine It stores requested number of const bytes into ENC247600 RAM starting from current ENC247600 write pointer EWRPT location Parameters ptr const buffer containing bytes to be written into ENC247600 RAM ni 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 _24j600 putConstBytes buffer 16 put a const array into ENC24J600 buffer MikroElektronika 507 mikroPascal PRO for dsPICSO 33 and PIC24 SPI_Ethernet_24j600_putString Prototype function SPI Ethernet 243600 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
584. t 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 1D13700 Graphic Lcd Library The following variables must be defined in all projects using Description 1D13700 Graphic Lcd library 1D13700 DATA van a byte System data bus var S1D13700_DATA at PORTD sfr external SLOT By WR sbit Er n 5 he ne See Write signal var S1D13700 WR sbit at LATC2 bit external i SID1I3700 RD 4 sbity Sfr i s var E sbi sfr Read signal var S 3700 RD sbit at LATC1 bit external ses Ls 1013700 AO sorte sfr A A y ARS aCe System Address pin var S1D13700 AO sbit at LATCO bit external T S1D13700 RES sbit fr gt A ver sbit SEE Reset signal var 1D13700 RES sbit at LATC3 bit external var S1D13700 CS sbit siz 7 Chip select var S1D external var 1D13700 DATA Direction Direction of the system data bus var S1D1
585. t 286 Cf_Fat_QuickFormat 286 Cf_Fat_Assign 287 Cf_Fat_Reset 288 Cf_Fat_Read 288 Cf_Fat_Rewrite 289 Cf_Fat_Append 289 Cf_Fat_Delete 289 Cf_Fat_Write 290 Cf_Fat_Set_File Date 290 Cf_Fat_Get_File_Date 291 Cf_Fat_Get_File_Date_Modified 291 Cf_Fat_Get_File_Size 292 Cf_Fat_Get_Swap_File 292 Library Example 294 HW Connection 299 ECAN Library 300 Library Routines 300 ECANxDmaChannellnit 301 ECANxSetOperationMode 301 ECANxGetOperationMode 302 ECANxInitialize 303 ECANxSelectTxBuffers 304 ECANxFilterDisable 304 ECANxFilterEnable 305 ECANxSetBufferSize 305 ECANxSetBaudRate 306 ECANxSetMask 307 ECANxSetFilter 308 ECANxRead 309 ECANxWrite 310 ECAN Constants 311 MikroElektronika 12 mikroPascal PRO for dsPICSO 33 and PIC24 ECAN_OP_MODE Constants 311 ECAN_CONFIG_FLAGS Constants 311 ECAN_TX_MSG_FLAGS Constants 312 ECAN_RX_MSG_FLAGS Constants 312 ECAN_MASK Constants 313 ECAN_FILTER Constants 313 ECAN_RX_BUFFER Constants 314 Library Example 315 HW Connection 319 EEPROM Library 319 Library Routines 319 EEPROM _Erase 320 EEPROM _Erase_Block 320 EEPROM_Read 320 EEPROM_Write 321 EEPROM_Write_Block 321 Library Example 321 Epson 1D13700 Graphic Lcd Library 323 External dependencies of the Epson S1D13700 Graphic Lcd Library 323 Library Routines 324 1D13700_Init 325 1D13700_Write_Command 326 1D13700 Write _Parameter 327 1D13700 Read_Parameter 327 1D13700_ Fill 327 1D13700_GrFill 328 1D13700_TxtFill 328 1D13700_Display_
586. t 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 CANSP SetOperationMode 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 the appropriate filter mask and message type value CANSPISetOperationMode _CANSPI MODE CONFIG 0xFF 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 L CANSPI CONFIG MATCH MSG TYPI CANSPI_CONFIG XTD MSG MikroElektronika 266 mikroPascal PRO for dsPIC30 33 and PIC24 CANSPISetFilter Prototype procedure CANSPISetFilter CAN FILTE as byte val longint CANSPI_ CONFIG FLAGS as byte Description Configures message filter The parameter value is bit adjusted to the appropriate filter registers
587. t and x is permitted to be zero The return value is in radians between M and M inclusive atan2 2 1 res 4 636475e 1 ceil oe function ceil real real Function returns value of a x rounded up to the next whole number Example res ceil 0 5 res 1 000000 COS Prototype function cos arg real real Function returns the cosine of in radians The return value is from 1 to 1 Example res cos PI 3 res 0 500008 cosh Prototype function cosh x real real Description Function returns the hyperbolic cosine of x defined mathematically as e e 2 If the value of x is too large if overflow occurs the function fails Example res cosh PI 3 res 1 600286 eval_ poly Prototype Prototype function eval poly x real var d array 10 of real m byte real Description Function Calculates polynom for number x with coefficients stored in d for degree n 686 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 exp Prototype function exp x real real Function returns the value of e the base of natural logarithms raised to the power x i e e Example res exp 0 5 ves t 1 648721 Prototype funetion fabs d real real Function returns the absolute i e a value of d Example res fabs 1 3 if ses Ke aeiia aa function floor real real Function returns the value of parameter x
588. t at RB1 bit external E PS2_D pi i it i PS2_D Di i i var _Data_Direction sbit Direction of the PS 2 Data pin var _Data_Direction sbit at sfr external recon ofthe PSI2 Data pin TRISBO bit var PS2 Clock Direction sbit var PS2_Clock_Direction sbit at sfr external Direction of the PS 2 Clock pin TRISB1 bit Library Routines Ps2_Config Ps2_Key_Read MikroElektronika 427 mikroPascal PRO for dsPIC30 33 and PIC24 Ps2_ Config Reus Nothing OOOO 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 spe
589. t at TRISB3 bit GLCD D2 Direction sbit at TRISB2 bit GLOD DI Direction sbit at TRISB1 bit GLCD DO Direction sbit at TRISBO bit var GLCD CS1 sbit at LATB4 bit GLCD_CS2 sbit at LATB5 bit GLCD_RS sbit at LATFO bit GLCD_RW sbit at LATF1 bit GLCD_EN sbit at LATF4 bit GLCD_RST sbit at LATF5 bit var GLCD CS1 Direction sbit at TRISB4 bit GLCD CS2 Direction sbit at TRISB5_bit GLED RS Direction sbit at TRISFO bit GLCD RW Direction sbit at TRISF1 bit GLCD_EN Direction sbit at TRISF4 bit GLCD RST Direction Sbit at TRISFS bit End Glcd module connections byte array 18 var counter someText of char procedure Delay2S begin Delay ms 2000 end begin DEFINE COMPLETE EXAMPLE comment 2 seconds delay function this line to make simpler smaller example 361 mikoPascal PRO for dsPIC30 33 and PIC24 ADPCFG OxFFFF Gica Imit Gled Fi1L 0x00 while TRUE do begin SIFDEF COMPLETE EXAMPLE Glcd_Image truck_ bmp Delay2S delay2S SENDIF Gled_Fill 0x00 Gled Box 62 40 124 63 1 Gled Rectangle 5 5 84 35 1 7 Gled_Line 0 0 127 63 1 Delay2S counter 5 while counter lt 59 do begin Delay ms 250 Gled V Line 2 54 counter 1 Gica H Lane 2 120 counter 1 Counter counter 5 end Delay2S Gled Fill 0x00 Clear GLCD SIFDEF COMPLETE EXAMPLE a7 fe
590. t be defined before using this function Initialize Transmitter var MANTXPIN sbit at LATF1 bit var MANTXPIN Direction sbit at TRISTI bit Man Send Init 381 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Man_Send Prototype procedure Man Send tr_ data byte Sends one byte tr data data to be sent To use this function the user must prepare the MCU for sending See Man_Send_Init routine var msg byte Man_Send msg Notes Baud rate used is 500 bps Man_Synchro Prototype Measures half of the manchester bit length with 10us resolution 0 if synchronization was not successful Half of the manchester bit length given in multiples of 10us upon successful synchronization To use this function you must first prepare the MCU for receiving See Man_Receive_lnit var man_ half bit_len word MikroElektronika 382 mikroPascal PRO for dsPIC30 33 and PIC24 Man_Break Prototype procedure Man Break Description Man_Receive is blocking routine and it can block the program flow Call this routine from interrupt to unblock the program execution This mechanism is similar to WDT var datal error counter byte procedure TimerliInt org IVT_ADDR_TIINTERRUPT begin counter 0 if counter gt 20 then begin Man _ Break counter 0 reset counter end else Inc counter increment counter TIIF bit 0 Clear Timerl overf
591. t buffer start address 0x1 9AE transmit buffer end address 0x1 FFF 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 00012 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 Parameters mac RAM buffer containing valid MAC address ip RAM buffer containing valid IP address fullDuplex ethernet duplex mode switch Valid values 0 half duplex mode and 1 full duplex mode Nothing Requires Global variables SPI_ Ethernet CS Chip Select line SPI Ethernet CS Direction Direction of the Chip Select pin SPI_Ethernet_RST Reset line 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 416 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 S
592. t 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 ENC24J600 RAM start address Valid values 0 8192 ni 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 243600 getBytes buffer 0x100 16 read 16 bytes starting from address 0x100 SPI_Ethernet_24jJ600_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 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 reqLength TCP request data field length flag
593. t least 100 see help on this function 295 mikoPascal PRO for dsPIC30 33 and PIC24 if size lt gt 0 then begin LOongIntTostr size err Cxt 7 UART1 Write Line err txt for i 0 to 4999 do begin Cf Write Sector size Buffer Inc size VARTI Weite 3 end end end a Main Uncomment the function s to test the desired operation s begin err txt t FATIG not found file contents XX CF FAT16 library by Anton Rieckert filename MIKROOOxTXT define COMPLETE EXAMPLE comment this line to make simpler smaller example ADPCFG OxFFFF disable A D inputs Initialize UART1 module UART1 Init 19200 Delay ms 10 UART1 Write Line dsPIC Started asPIC present report Init the FAT library use Cf Fat QuickFormat instead of init routine if a format is needed 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 UART1 Write Line Test Start Create New File SIFDEF COMPLETE EXAMPLE Create Multiple Files M Open File Rewrite Open File Append Open File Read Delete File 7 Test File Bxist M Create Swap File SENDIF UART1 Write Line Test End end else begin UART1 Write Line err txt Note Cf Fat Init tries to initialize a card more than once
594. t 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 E 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 4 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library UARTx_Read Prototype The function receives a byte 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 var receive word read data if ready if UART1 Data _Ready 1 then receive UARTI1 Read module simply change the letter x in the routine prototype for a number from 1 to 4 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library UART library routines require you to specify the module you want to use To select the desired UART mikoPascal PRO for dsPIC30 33 and PIC24 UARTx_Read_Text Prototype procedure UARTx Read Text var output delimiter string Attempts
595. t 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 IPv4 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 I 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 Ethernet module has to be initialized See SP _Ethernet_Init var data byte SPI _Ethernet_putByte data put an byte into ENC28J60 buffer 480 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_Ethernet_putBytes Prototype procedure SPI Ethernet putBytes ptr byte n word 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 Requires Ethernet module has to be initialized See SPI_Ethernet_Init var buffer array 17 of byte
596. t qualifier all objects need to be initialized The mikroPascal PRO for dsPIC30 33 and PIC24 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 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 MikroElektronika 215 mikroPascal PRO for dsPICSO 33 and PIC24 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 dsPIC30 33 and PIC24 Arithmetic Operators Bitwise Operators Boolean Operators Relational Operators Operators Precedence and Associativity There are 4 precedence categories in mikroPascal PRO for dsPIC30 33 and PIC24 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 a
597. t 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_lInit 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 Set_DirectionPortA 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_lInit Set Port Expander s PORTA to be output Expander Set _DirectionPortA 0 00 422 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Expander_Set_DirectionPortB Prototype procedure Expander Set DirectionPortB ModuleAddress Data byte The function sets Port Expander s PortB direction
598. ta cArr FLASH Write Compact flash_address ptr data 36 The al should take care about the address alignment see the explanation at the beginning of this FLASH_Write_Init a Tiare eee eee FLASH Write Init flash_address longint data address word Initializes RTSP for write to FLASH Initializes RTSP for write to FLASH operation 000 E Parameters flash address starting address of the FLASH memory block data_ address data to be written Requires The block to be written to must be erased first either from the user code FLASH_Erase32 or during the programming of MCU Please note that block size that is to be erased is different from the one that can be written with this function const iArr array 8 of word var ptr data word ptr data iArr LASH Write Init 0x006100 ptr data LASH Write Loadlatch4 LASH Write a ara aa FLASH Write DoWrite Z The user should take care about the address alignment see the explanation at the beginning of this page MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 FLASH_Write_Loadlatch4 Prototype procedure FLASH Write Loadlatch4 Description Loads the current RTSP write latch with data 7 instructions 8 addresses 12 bytes The data is filled in the regular mode Requires The block to be written to must be erased first either from the user code FLASH_Erase32 or during the programming of MCU Please note that block
599. tangle_Round_Edges Fill 358 Glcd_Box 358 Glcd_ Circle 359 Glcd_Circle_Fill 359 Glcd_Set_Font 360 Glcd_Write_Char 361 Glcd_Write_ Text 361 MikroElektronika 14 mikroPascal PRO for dsPIC30 33 and PIC24 Glcd_Image 362 Glcd_Partiallmage 362 Library Example 363 HW Connection 365 I C Library 366 Library Routines 366 I2Cx_Init 366 I2Cx_Start 367 I2Cx_Restart 367 I2Cx_Is_Idle 368 I2Cx_Read 368 I2Cx_Write 369 I2Cx_Stop 369 Library Example 370 HW Connection 370 Keypad Library 371 External dependencies of Keypad Library 371 Library Routines 371 Keypad_Init 371 Keypad_Key_Press 372 Keypad_Key_Click 372 Library Example 373 HW Connection 374 Led Library 375 Library Dependency Tree 375 External dependencies of Lcd Library 375 Library Routines 375 Led_Init 376 Lced_Out 377 Led _Out_Cp 377 Led_Chr 377 Led_Chr_Cp 378 Lcd_Cmd 378 Available Lcd Commands 378 Library Example 379 Manchester Code Library 381 External dependencies of Manchester Code Library 381 Library Routines 382 Man_Receive_Init 382 Man_Receive 383 Man_Send_Init 383 Man_Send 384 Man_Synchro 384 Man_Break 385 Library Example 386 Connection Example 388 15 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Multi Media Card Library Secure Digital Card Secure Digital High Capacity Card Library Dependency Tree External dependencies of MMC Library Library Routines Mmc_Init Mmc_Read_Sector Mmc_Write_ Sector Mmc_Read_Cid Mmc_Read_Csd Mmc_Fat_In
600. tch Window Status Bar 1E Bi Ex Select variable from list text Peripherals Freeze rrereeeee Value Address Related topics mikrolCD Debugger Example Debug Windows Debugger Options 117 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 mikrolCD Debugger Options Debugger Options PpP Function Toolbar Description Key Icon 7 8 Run Pause Debugger Run Pause Debugger 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 executing the first instruction within it Executes the current program line then halts If the executed pean woes 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 Executes all remaining program lines within the subroutine The Step out debugger halts immediately upon exiting the subroutine this option is provided with the PIC18 microcontroller family but not with the PIC16 family Executes the program until reaching the cursor position Ctrl F8 gt Toggle Breakpoint Toggle breakpoints option sets new breakpoints or removes those F5 already set at the current cursor position 3 Related topics Run Menu Debug Toolbar e F F6 E F F8 MikroElektronika 118 mikroPascal PRO for dsPIC30 33 and PIC24 mikrolCD Debugger Exam
601. te 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 this line can slow down the performance Set file date amp time info 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 end jf 22323335 gt S55 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 filename 7 loop2 set filename Cf Fat Set File Date 2005 6 21 10 35 0 Cf Fat Assign filename OxA0 find Cf Fat _Rewrite for loop 1 to 44 do begin file contents 0 loop div 10 48 file contents 1 loop mod 10 48 Cf Fat Write file contents LINE LEN 1 end end end ff fea sSSsSS 55555 Opens an existing file and rewrites it procedure M Open File Rewrite begin filename 7 C Cf _Fat_Assign filename Cf Fat Rewrite for loop 1 to 55 do begin 0 Set filename for single file tests 293 mikoPascal PRO for dsPIC30 33 and PIC24 file contents 0 byte loop div 10 48 file contents 1 byte loop mod 10 48 Cf Fat Write file contents LINE LEN 1 write data to the assigned file end end J f Se Fee eSeSSeeee Opens an existing file and appends data to it Ji and al
602. teByteArr 0 FLASH Write Compact 0x006000 pb 36 ee This is what FLASH Write Compact does beneath the hood FLASH Write Init 0x006000 pvl FLASH Write Loadlatch4 Compact FLASH Write Loadlatch4 Compact FLASH Write Loadlatch4 Compact FLASH Wri te DoWrite ei read compact format pb ReadByteArr FLASH Read4 Compact 0x006000 pb po i pb t 12 FLASH Read4 Compact 0x006008 pb po 2 pb 127 MikroElektronika 346 mikroPascal PRO for dsPIC30 33 and PIC24 FLASH Read4 Compact 0x006010 pb pb pb 12 pb 0 termination UART1 Init 9600 VARTI Write 10 UART1 Write 13 UART1 Write Text Start UART1 Write 10 UART1 Write 13 i 0 while ReadByteArr i do begin temp byte ReadByteArr i UART1 Write temp byte Inc i end now for some non compact flash write pw WriteWordArr erase the block first FLASH Erase32 0x006100 FLASH Write Init 0x006100 pw FLASH Write Loadlatch4 FLASH Write Loadlatch4 FLASH Write DoWrite read non compact format pw ReadWordArr 0 FLASH Read4 0x006100 pw pw pw 4 FLASH Read4 0x006108 pw pw pw 4 pw 0 termination show what has been written UART1 Write 10 UART1 Write 13 i e 0 while ReadWordArr i lt gt 0 do begin temp byte ReadWordArr i UART1 Write temp_ byte i s i aos end end Graphic L
603. ted 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 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 206 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 var ptrl const byte ptril 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 withi
604. ters the date time stamp procedure M Open File Append begin filename 7 B Cf Fat Assign filename 0 Cf Fat Set File Date 2009 1 23 17 22 0 Cf Fat Append file contents for mikroElektronika 2007 Prepare file for append file _contents 26 10 LF Cf Fat _Write file contents 27 Write data to assigned file end f Has S556 S55 2 Opens an existing file reads data from it and puts it to USART procedure M Open File Read begin filename 7 B Cf Fat_Assign filename 0 Cf_Fat_Reset size To read file procedure returns size of file while size gt 0 do begin Cf Fat _Read character UART1 Write character Write data to USART Dec size end end Deletes a file If file doesn t exist it will first be created and then deleted procedure M Delete File begin filename 7 F Cf Fat _Assign filename 0 Cf Fat _Delete end ff Hett aaeSeSes Tests whether file exists and if so sends its creation date Ir and file size via USART procedure M Test File Exist var fsize lt longinty year word month day hour minute byte outstr array 12 of char begin filename 7 B uncomment this line to search for file that DOES exists MikroElektronika 294 mikroPascal PRO for dsPIC30 33 and PIC24 filename 7 E if Cf Fat Assign filename 0 begin file has been found get its date
605. th the specified character code _ 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 Retums Returns a character associated with the spectied character coc Example c Chr 10 returns the linefeed character moes oe OO 150 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 Retums ASGI code ofthe ciasacte O OOOO Example c gt Ord A returns 65 Maes None SetBit Prototype procedure SetBit var register word rbit byte Description Function sets the bit rbit 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 register desired register rbit desired bit fetus nonno OOS Example SetBit PORTB 2 Set RB2 Notes fno SS ClearBit Prototype procedure ClearBit var register_ byte rbit byte Description Function clears the bit roit of register Parameter rbit needs to be a variable or literal with value 0 7 See Predefined glob
606. 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 E Library Manager ix Fe oc CO Sound s O spr C SPI_Ethernet C SPI_Glicd O spt_ted CO SPILede C sPr_T6963C CO Sprintf C Sprinti C Sprint E T6963C O Time C TouchPanel Trigonometry w O TWI w C UART E D 8 8 DDD Help Examples Uninstall package BinaryToGray GrayToBinary v Related topics mikroPascal PRO for PIC Libraries Creating New Library MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 E3 Sort By Name Sort By Line Line 74 Line 50 Q imove_Delay Line 54 G shift_Text_Left Line 64 GQiishift_Text_Right Statistics After successful compilation you can review statistics of your code Click the Statistics Icon ma Memory Usage Windows Provides overview of RAM and ROM usage in the various forms MikroElektronika 66 mikroPascal PRO for dsPIC30 33 and PIC24 RAM Memory Usage Displays RAM memory usage in a pie like form B Statistics Project Nam
607. the bottom of this page PullUps data for choosing pull up down resistors configuration PortA pull up down resistors configuration is passed in Pul 1Ups higher byte PortB pull up down resistors configuration is passed in PullUps 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_lInit Set Port Expander s PORTA and PORTB pull up resistors Expander Set _PullUpsPortAB 0 S FFFF 424 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 ADPCFG OXFFFF TRISB 0x00 LATB OxFF initialize AN pins as digital If Port Expander Library uses SPI1 module SPI1_Init Expander Init 0 Expander Set DirectionPortA 0 0x00 Expander Set _DirectionPortB 0 OxFF Expander Set_PullUpsPortB 0 OxFF pins while TRUE do begin
608. 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 SP communication see SPI_Glcd_Init routine ZZ Draw a circle with center in 50 50 and radius 10 SPI Gled Cirele s0 50 10 1 SPI_Glcd_Circle_FIll 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 Glcd needs to be initialized for SPI communication see SPI_Glcd_lInit routine Draw a filled circle with center in 50 50 and radius 10 SPI_Gled Circle Fil1 50 50 10 1 526 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 routines Glcd needs to be initialized for SPI communica
609. 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 Gled_Rectangle 5 5 40 40 1 Glcd_Rectangle_Round_Edges Prototype procedure 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 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 radius radius of the rounded edge 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 see Glcd_Init routine Draw a rounded edge rectangle between dots 5 5 and 40 40 with the edge radius of 12 Glcd_ Rectangle Round Edges 5 5 399 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Glcd_Rectangle_Round_Edges Fill Prototype procedure Glcd Rectangle Round Edges Fill x_upper left byte y upper left ian x bottom right byte y bottom right byte radius byte color byte
610. the user to easily manipulate current project New Project Shift Ctrl N Open Project Shift Ctrl O Open Project Group Recent Projects gt Save Project Save Project As Close Project Close Project Group Add File To Project Remove File From Project Edit Search Paths Edit Project Shift Ctrl E Clean Project Folder Import Project Ctrl I 3 Export Project Ctrl alt E e Ceseription Clean Project Folder Clean Project Folder Import projects created in previous versions of mikroPascal BS Export Project ctrl at E Export Project Related topics Keyboard shortcuts Project Toolbar Creating New Project Project Manager Project Settings 4l MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Build Build Menu Options Build Menu allows the user to easily manage building and compiling process Build Ctrl F9 Rebuild All Sources Alt F9 Build All Projects Shift F9 Stop Build All Ctrl F12 Build Program Ctrl F 11 Bud _________ amp 9_ Build active project Rebuild All Sources __At F9 Rebuild all sources in acrive project Stop building of all projects By Build Program ctHFi1 Build and program active project Related topics Keyboard shortcuts Project Toolbar Creating New Project Project Manager Project Settings MikroElektronika 48 mikroPas
611. 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 called a phi function is inserted so that these multiple definitions are merged In mikroPascal PRO for dsPIC 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 W10 W13 for dsPIC 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 box from the Output Settings Menu Lets consider a trivial case program Example procedure SSA Test y integer k integer begin if yt k then asm nop end end begin SSA Test 5 5 7 end With SSA enabled sub proc
612. thernet _ 243600 UseruUDP Since all libraries are built for SSA SSA restrictions regarding function pointers dictate that modules that use SPI_Ethernet_24j600_setUserHandlers must also be built for SSA 310 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_Ethernet_24j600_getlpAddress Pratoypa Prototype function SPI Ethernet 24j600 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_24j600_Init Vv oe array 4 of byte user IP address buffer memcpy ipAddr SPI Ethernet 243600 getIpAddress 4 fetch IP 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 SPI_Ethernet_24j600_getGwlpAddress Prototype _ Prototype function SPI Ethernet _24j600_ 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 vV gwIpAddr array 4 of byte user gateway IP address buffer memcpy gwIpAddr SPI Ethernet 243600 getGwiIpAddress 4 fetch gate
613. thernet _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 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 er returned by this routine into it s own IP address buffer These locations should not be altered by the user in any case SPI_Ethernet_getGwlpAddress Fratotype 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 DNS IP address Ethernet module has to be initialized See SPI_Ethernet_Init vV gwIpAddr 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 its own gateway IP address buffer These locations should not be altered by the user in any case MikroElektronika 485 mikroPascal PRO for dsPICSO 33 and PIC24 SPI_Ethernet_getDnslpAddress Patois Prototype function SPI_Ethernet_getDnsIpAddress This routine should be used when DHCP server is p
614. 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 SP _Ethernet_Init var The Ethernet services are not stopped while this routine waits for ARP reply The incoming packets will be processed normaly during this time IpAddr array 4 of byte IP address IpAddr 0 192 IpAddr 0 168 IpAddr 0 i IpAddr 0 1 SPI Ethernet _arpResolve IpAddr 5 get MAC address behind the above IP address wait 5 secs for the response 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 dest Port destination UDP port number pkt packet to transmit pkt Len length in bytes of packet to transmit UDP packet was sent successfully 0 otherwise Ethernet module has to be initialized See SPI_Ethernet_Init var IpAddr array 4 of byte remote IP address TpAddr 0 192 TpAddr 0 168 IpAddr 0 1 IpAddr 0 1 SPI_ Ethernet _sendUDP IpAddr 10001 10001 Hello 5 send Hello message to the above IP address from UDP port 10001 to UDP port 10001 488 MikroElektronika mikoP
615. tion see SPI_Glcd_Init routine Use the custom 5x7 font myfont which starts with space 32 7 32 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 dsPIC30 33 and PIC24 character set and regular ASCII set eg if A is 65 in ASCII character and A is 45 in the mikroPascal PRO for dsPIC30 33 and PIC 24 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 Gled 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 _Glcd_ System3x5 FontSystem5x7_ v2 equivalent to Font Glcd_ System5x7 font5x7 equivalent to Font _Glcd_5x7 Character8x7 equivalent to Font_Glcd_Character8x7 MikroElektronika 527 mikroPascal PRO for dsPICSO 33 and PIC24 SPI_Glcd_Write_Char Prototype procedure SPI Glcd Write Char chrl x pos page num color byte Prints character on Glcd Parameters chr1 character to be written x pos character starting positio
616. tion 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 var cnt char var readbuff array 64 of char var writebuff array 64 procedure USBlInterrupt begin USB_Interrupt_Proc end begin ADIPCFGL OxFFFF of char iv IVT_ADDR_USB1INTERRUPT HID Enable readbuff writebuff while TRUE do begin while HID Read 0 for cnt 0 to 63 do writebuff cnt while HID Write wri end end HW Connection 634 do readbuff cnt tebuff 64 0 do 24FJ256GB110 USB connection scheme MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Digital Signal Processing Libraries mikroPascal PRO for dsPIC30 33 and PIC24 includes various libraries for DSP engine All DSP routines work with fractional Q15 format Digital Signal Processing Libraries FIR Filter Library IIR Filter Library FFT Library Bit Reverse Complex Library Vectors Library Matrices Library MikroElektronika 635 mikroPascal PRO for dsPICSO 33 and PIC24 FIR Filter Library mikroPascal PRO for dsPIC30 33 and PIC24 includes a library for finite impulse response FIR filter All routines work with fractional Q15 format A
617. tion of the Chip select 2 pin LCD RS Direction Direction of the Register select signal pin GLCD RW Direction Direction of the Read Write signal pin GLCD EN Direction Direction of the Enable signal pin GLCD RST Direction Direction of the Reset signal pin je I es a ae se a A E S o A E A l must be defined before using this function Glcd module connections var GLCD D7 sbit at RD3 bit LCD D6 sbit at RD2 bit LCD D5 sbit at RDI bit LCD D4 sbit at RDO bit LCD DS sbit at RBS bit LCD D2 sbit at RB2 bit LCD DL sbit at RBI bit LCD DO sbit at RBO bit LCD_D7 Direction sbit at TRISD3 bit LCD_D6 Direction sbit at TRISD2 bit LCD_D5 Direction sbit at TRISD1 bit LCD D4 Direction sbit at TRISDO bit LCD D3 Direction sbit at TRISB3 bit LCD_D2 Direction sbit at TRISB2 bit LCD DI Direction spit at TRISB1 bit LCD_DO Direction sbit at TRISBO bit D CS2 shit at LATB5 bit LCD RS sbit at LATFO bit LCD RW sbit at LATF1 bit LCD EN sbit at LATF4 bit LCD RST sbit at LATES bit Swe toe hoe hee aa GI G G G G G G G G G G G G G G GI GI G G G LCD CS1 Direction sbit at TRISB4 bit LCD CS2 Direction sbit at TRISB5 bit LCD RS Direction sbit at TRISFO bit LCD RW Direction sbit at TRISF1 bit LCD EN Direction sbit at TRISF4 bit LCD RST Direction sbit at TRISF5 bit End Gled module connections QAAARAA
618. to access opmode bits _ECAN MODE NORMAL word 0x00 _ECAN MODE DISABLE word 0x01 _ECAN MODE LOOP word 0x02 _ECAN MODE LISTEN word 0x03 _ECAN MODE CONFIG word 0x04 ECAN MODE LISTEN ALL word 0x07 ECAN_CONFIG_FLAGS Constants The ECAN CONFIG FLAGS constants define flags related to the ECAN module configuration The routines ECANxInitialize and ECANxSetBaudRate expect one of these or a bitwise combination as their argument Copy Code To Clipboard const _ECAN CONFIG DEFAULT word OxFF J ATPITIITA ECAN CONFIG PHSEG2 PRG BIT word 0x01 ECAN CONFIG PHSEG2 PRG ON word OxFF XXXXXXX1 ECAN CONFIG PHSEG2 PRG OFF word OxFE XXXXXXXO ECAN CONFIG LINE FILTER BIT word 0x02 ECAN CONFIG LINE FILTER ON word OxFF XXXXXX1X ECAN CONFIG LINE FILTER OFF word OxFD XXXXXXOX ECAN CONFIG SAMPLE BIT word 0x04 ECAN CONFIG SAMPLE ONCE word OxFF XXXXX1XX ECAN CONFIG SAMPLE THRICE word OxFB XXXXXOXX ECAN CONFIG MSG TYPE BIT word 0x08 ECAN CONFIG STD MSG word OxFF XXXX1XXX ECAN CONFIG XTD MSG word OxF7 XXXXOXXX ECAN CONFIG MATCH TYPE BIT word 0x20 ECAN CONFIG ALL VALID MSG word 0xDF XXOXXXXX ECAN CONFIG MATCH MSG TYPE word OxFF gt XX1XXXXX 309 MikroElektronika mikoP
619. to 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 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 dsPIC Specifics mikroPascal PRO for dsPIC30 33 and PIC24 specifics Memory type specifiers 162 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Common Object File Format COFF COFF File Format The Common Object File Format COFF is a specific file format suitable for code
620. 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 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 PartialiImage 10 12 10 15 16 32 Caimage Use the mikroPascal PRO for dsPIC30 33 and PIC24 integrated Glcd Bitmap Editor Tools gt Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd MikroElektronika 360 mikroPascal PRO for dsPIC30 33 and PIC24 Library Example The following drawing demo tests advanced routines of the Glcd library Copy Code To Clipboard program GLCD Test Glcd module connections var GLCD D7 sbit at RD3 bit GLCD DG sbit at RD2 bit GLCD_D5 sbit at RD1 bit GLCD D4 sbit at RDO bit GLCD_D3 sbit at RB3 bit GLCD D2 sbit at RB2 bit GLCD DI sbit at RB1 bit GLCD DO sbit at RBO bit GLCD D7 Direction 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 sbi
621. tor 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 208 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 program example var w 2 word ptr b byte ptr arr array 10 of byte arr array 10 of byte begin ptr b Qarr operator will return byte wW 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 dsPIC30 33 and PIC24 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 var ptrl byte ptr
622. tored 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 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 FLAGS constants See CANSPI_RX_MSG_FLAGS constants 0 if nothing is received OxFFFF if one of the Receive Buffers is full message received Requires The CANSPI module must be in a mode in which receiving is possible See CANSP SetOperationMode 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 rX flags i 0 clear message flags msg_revd CANSPIRead msg_id data data len rx flags then MikroElektronika 268 mikroPascal PRO for dsPICSO 33 and PIC24 CANSPIWrite Prototype function CA
623. totype Ales SPI_T6963C sprite px py byte const pic byte sx sy byte Fills TT 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 SPI_T6963C_Config routine SPI T6963C_sprite 76 4 einstein 119 draw a sprite If px 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 MikroElektronika 599 mikroPascal PRO for dsPICSO 33 and PIC24 SPI_T6963C_set_cursor Prototype procedure SPI _T6963C_set_cursor x y byte Description Sets cursor to row x and column y Parameters x cursor position row number y cursor position column number Notes None oo SPI_T6963C_clearBit Parameters b bit mask The function will clear bit x on control port if bit x in bit mask is set to 1 SPI T6963C clearBit 0x03 None 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 Toshiba Gled module needs to b
624. tput 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 double word number to be converted as destination string var input longint txt array 10 of char Plies begin input 12345678 InkToStr input ext jf tet as 22345673 662 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 f 3 real txt array 10 of char ffl 37 4 29 ff2 123 456789 ff3 0 000001234 FloatToStr tl txt jf tHE as Y 374 20001L FloatToStr fL2 txt i tz is 123 456789 FIlOatToSte ES CXE 7 7 Ext 1s 0 000000 Notes Given floating point number will be truncated to 7 most significant digits before conversion MikroElektronika mikroPascal PRO for dsPICSO 33 and PIC24 WordToStrWithZeros Prototype procedure WordToStrWithZeros 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 o
625. tr_data a The user should take care about the address alignment see the explanation at the beginning of this page MikroElektronika 338 mikroPascal PRO for dsPIC30 33 and PIC24 FLASH_Write_Compact Prototype procedure FLASH Write Compact flash address longint data_address word bytes word Description Fills a portion of Flash memory using the dsPIC30 RTSP module in the compact manner In this way several blocks of RTSP s latch can be written in one pass One latch block contains 4 instructions 8 addresses 12 bytes Up to 8 latch blocks can be written in one round resulting in a total of 812 96 bytes This method uses all available bytes of the program FLASH memory including those that are not mapped to address space every 3rd byte Parameters flash address starting address of the FLASH memory block data_ address data to be written bytes number of bytes to be written The amount of bytes to be written must be a multiply of 12 since this is the size of the RTSP s write latch es Requires The block to be written to must be erased first either from the user code FLASH_Erase32 or during the programming of MCU Please note that block size that is to be erased is different from the one that can be written with this function var flash_address longint cArr string 36 7 ptr d ta gt word flash _ address 0x006000 cArr mikroElektronikal2mikroElektronika34 ptr da
626. troller must be connected to ECAN transceiver which is connected to the ECAN bus The ECAN module must be in Config mode otherwise the function will be ignored See ECANxSetOperationMode set appropriate filter mask and message type value ECAN1SetOperationMode _ECAN MODE CONFIG OxFF set CONFIGURATION mode ECAN1 module must be in config mode for mask settings Set all mask0 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 ECAN1SetMask _ECAN MASK 0 1 ECAN CONFIG MATCH MSG TYPE _ECAN_ CONFIG _ XTD MSG ECAN library routine require you to specify the module you want to use To select the desired ECAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of ECAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 305 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 ECANxSetFilter Prototype procedure ECANxSetFilter ECAN FILTER word val longint ECAN FILTE MASK word ECAN FILTER RXBUFF word ECAN CONFIG FLAGS word The function configures and enables appropriate message filter Parameters ECAN FILTER ECAN module filter number Valid values ECAN FILTER constants See ECAN_ FILTER constants val filter register value This value is
627. tx ID 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 begin ADPCFG OxFFFF Configure AN pins as digital I O PORTB 0 clear PORTB TRISH 2 07 set PORTB as output Can_ Init Flags 0 a ll Can_ Send Flags clear flags Can Rev Flags ll Mag Ja MikroElektronika 214 mikroPascal PRO for dsPIC30 33 and PIC24 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 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 and CANSPI CONFIG LINE FILTER OFF Initialize SPI1 module SPELL Ine CANSPIInitialize 1 3 3 3 1 Can_Init_Flags initialize external CANSPI module CANSPISetOperationMode _CANSPI_ MODE CONFIG OxFF set CONFIGURATION mode CANSPISetMask CANSPI MASK Bl1 1 CANSPI CONFIG XTD MSG set all maski 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 set id of filter B2 F3 to Ist
628. type procedure SPI Ethernet 24j600 confNetwork var ipMask gwlpAddr dnsIpAddr array 4 of byte Description Configures network parameters IP subnet mask gateway IP address DNS IP address when DHCP is not used Parameters ipMask IP subnet mask gwl pAddr gateway IP address dnsIpAddr DNS IP address Nothing Requires Ethernet module has to be initialized See SPI_Ethernet_24j600_Init var ipMask array 4 of byte network mask for example 209 299 25Si0Q gwilpAddr array 4 of byte gateway router IP address dnsIpAddr array 4 of byte DNS server IP address gwIpAddr 0 192 gwipAddr 1 168 gwipAddr 2 20 gwIpAddr 3 6 dnsIpAddr 0 1927 dnsIpAddr 1 168 dnsIpAddr 2 20 dnsIpAddr 3 1007 255 255 2557 0 Ethernet_24j600_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 512 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_Ethernet_24j600_arpResolve Prototype function SPI Ethernet _ 243600 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 config
629. ue case kp of case 10 kp 42 oe Vee Uncomment this block for keypad4x3 case 11 kp 48 fe Oe case 12 kp 35 Z W default kp 48 kp 49 kpes 50 77 kp 51 kp 65 en Fe kp 537 kp 54 kp 66 kp 557 102 kp 2 56 77 Lie kp c 57 f2 Vp kos 67 A7 13s kp 2 425 14 kp 48 15 kp 357 7 16 kp s 68 ODINHDUBWNHE tal xe Oss Oo 10 06 OD oh Os Pw SO Uncomment this block for keypad4x4 311 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 vec OSCILLATOR 2 a a O B w Fi ta a st ea ALA LS cGy 4x4 Keypad connection scheme MikroElektronika 312 mikroPascal PRO for dsPIC30 33 and PIC24 Lcd Library mikroPascal PRO for dsPIC30 33 and PIC24 provides a library for communication with Leds 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 Led Lcd_Constants External dependencies of Lcd Library The following variables must be defined in 3 Description all projects using L
630. ulate 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 units 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 i E xr end begin CircleArea CircleArea routine call end MikroElektronika 196 mikroPascal PRO for dsPIC30 33 and PIC24 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 squared and pi 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
631. ule reduces numerous peripheral interrupt request signals to a single interrupt request signal to the dsPIC30 33 and PIC24 CPU and has the following features Up to 8 processor exceptions and software traps 7 user selectable priority levels Interrupt Vector Table IVT with up to 62 vectors dsPIC30 or up to 118 vectors dsPIC33 and PIC24 Aunique vector for each interrupt or exception source Fixed priority within a specified user priority level Alternate Interrupt Vector Table AIVT for debug support 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 example iv IVT ADDR T1INTERRUPT is IVT address of Timer interrupt source of the dsPIC 30F3014 MCU For more information on IVT refer to the dsPIC30 33 and PIC24 Family Reference Manual 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
632. unction 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 621 mikroPascal PRO for dsPIC30 33 and PIC24 UARTx_Init_Advanced Prototype AsPIC30 prototype procedure UARTxX Init Advanced baud rate longinet parity stop bits word AsPIC33 and PIC24 prototype Procedure UARTx Init Advanced baud rate longint parity stop bits word high low _ speed word Description Configures and initializes the UART module with user defined settings Parameters baud rate requested baud rate parity parity and data selection parameter Valid values stop bits stop bit selection parameter Valid values Description Predefined library const One stop bit _UART_ONE_STOPBIT Two stop bit _UART_TWO STOPBITS high low speed high low speed selection parameter Available only for dsPIC33 and PIC24 MCUs Valid values mikoPascal PRO for dsPIC30 33 and PIC24 Routine requires the UART module dsPIC30 family example Initialize hardware UART1 module and establish communication at 2400 bps 8 bit data even parity and 2 STOP bits UART1 Init Advanced 2400 2 1 dsPIC33 and PIC24 family example Initialize hardware UART2 module and establish communication at 2400 bps 8 bit data even parity 2 STOP bits and high speed baud rate calculations UART
633. uration ARP cash can store up to 3 entries 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_24j600_Init var IpAddr array 4 of byte IP address IpAddr IpAddr IpAddr TpAddr 0 192 0 168 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 dest 1P remote host IP address sourcePort local UDP source port number dest Port destination UDP port number pkt packet to transmit pkt Len length in bytes of packet to transmit UDP packet was sent successfully 0 otherwise Ethernet module has to be initialized See SPI_Ethernet_24j600_Init var IpAddr array 4 of byte remote IP address IpAddr 0 192 TpAddr 0 1687 IpAddr 0 is IpAddr 0 1 SPI Ethernet 243600 sendUDP IpAddr 10001 10001 Hello
634. ure T6963C_ setPtr p word byte Sets the memory pointer p for command p Parameters p address where command should be written c command 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 procedure 1T6963C_ waitReady Pools the status byte and loops until Toshiba Glcd module is ready Rems Nothing OOOO Example T063C wasereaayo O OOOO moes fn Ooo MikroElektronika 971 mikroPascal PRO for dsPIC30 33 and PIC24 T6963C_fill Prototype procedure 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 len length of the memory block in bytes T6963C_dot Prototype procedure T6963C dot x y integer 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 T6963C_BLACK and T6963C_WHITE Nothing Requires Toshiba Glcd module needs to be initialized See the T6963C_init routine T6963C_dot x0 yO pcolor None 512 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 T6963C_write_char Prototype procedure T6963C_ write char c x y mode byte
635. use 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 the Clean button M Lcd asm Led cfg Lcd cof Lcd dbg Lcd dct Lcd dlt Lcd hex Led log Led Ist Lcd mel Led mil Lcd mpas Led mpas ini Led mppds Lcd mppds_callertable txt Led user dic M M M M M Of C Program Files Mikroelektronika mikroPascal PRO for dsPIC Examples Development Sy Related topics Customizing Projects MikroElektronika 701 mikroPascal PRO for dsPICSO 33 and PIC24 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 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 from 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 dsPIC30 33 and PIC24 will generate output files Outp
636. 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 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 SPITI Init Initialize SPI module used with PortExpander SPI Led Config 0 initialize Lcd over SPI interface SPI_Lced_Out Prototype procedure SPI Lcd Out row column byte var text string Description 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 Nothing Requires Lcd needs to be initialized for SP communication see SP _Lcd_Config routine Write text Hello on Lcd starting from row 1 column 3 SPI Led Out l 37 Hello 7 None 004 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_Lcd_Out_Cp Erne 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 SP communication see SPI_Lcd_Co
637. usly assigned See Cf_Fat_Assign open file for appending Cf Fat _Append None Cf_Fat_Delete Requires CF card and CF library must be initialized for file operations See Cf_Fat_lInit File must be previously assigned See Cf_Fat_Assign delete current fil Cf Fat _Delete None 287 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Cf_Fat_Write Prototype procedure Cf Fat Write var fdata array 512 of byte data_len word Writes requested number of bytes to currently assigned file opened for writing Parameters fdata data to be written data len number of bytes to be written 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 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 day day attribute Valid values 1 31 hours hours attribute Valid
638. ut Files Upon successful compilation mikroPascal PRO for dsPIC30 33 and PIC24 will generate output files in the project folder folder which contains the project file mppds Output files are summarized in the table below Intel HEX Intel style hex records Use this file to program MCU Binary 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 the mikroPascal PRO for dsPIC30 33 and PIC24 you can click the View Assembly icon a or select View View Assembly from the drop down menu to review the generated assembly code asm file in a new tab window Assembly is human readable with symbolic names Related topics Build Menu Build Toolbar Messages Window Project Manager Project Settings mikoPascal PRO for dsPIC30 33 and PIC24 Creating New Library mikroPascal PRO for dsPIC30 33 and PIC24 allows you to create your own libraries In order to create a library in mikroPascal PRO for dsPIC30 33 and PIC24 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 dsPIC Uses 3
639. utConstBytes 509 SPI_Ethernet_24j600_putString 510 SPI_Ethernet_24j600_putConstString 510 SPI_Ethernet_24j600_getByte 510 SPI_Ethernet_24j600_getBytes 511 19 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 SPI_Ethernet_24j600_UserTCP 511 SPI_Ethernet_24j600_UserUDP 512 SPI_Ethernet_24j600_setUserHandlers 512 SPI_Ethernet_24j600_getlpAddress 513 SPI_Ethernet_24j600_getGwlpAddress 513 SPI_Ethernet_24j600_getDnslpAddress 513 SPI_Ethernet_24j600_getlpMask 514 SPI_Ethernet_24j600_confNetwork 514 SPI_Ethernet_24j600_arpResolve 515 SPI_Ethernet_24j600_sendUDP 515 SPI_Ethernet_24j600_dnsResolve 516 SPI_Ethernet_24j600_initDHCP 517 SPI_Ethernet_24j600_doDHCPLeaseTime 517 SPI_Ethernet_24j600_renewDHCP 518 Library Example 519 SPI Graphic Lcd Library 520 Library Dependency Tree 520 External dependencies of SPI Lcd Library 520 Library Routines 520 SPL_Glcd_Init 521 SPI_Glcd_Set_Side 522 SPI_Glcd_Set_Page 522 SPIL_Glcd_Set_X 522 SPI_Glcd_Read_Data 523 SPI_Glcd_Write_Data 523 SPIL_Glcd_Fill 523 SPIL_Glcd_Dot 524 SPIL_Glcd_Line 524 SPIL_Glcd_V_Line 525 SPIL_Glcd_H_Line 525 SPI_Glcd_Rectangle 526 SPI_Glcd_Rectangle_Round_Edges 526 SPI_Glcd_Rectangle_Round_Edges Fill 527 SPI_Glcd_Box 527 SPL_Glcd_ Circle 528 SPIL_Glcd_Circle_FIll 528 SPI_Glcd_Set_Font 529 SPI_Glcd_Write_Char 530 SPI_Glcd_Write_Text 530 SPI_Glcd_Image 531 SPI_Glcd_Partiallmage 531 Library Example 532 HW Connection 534 SPI Lcd Library 535 Library Dependen
640. value to be used ECAN CONFIG PHSEG2 PRG ON and with ECAN1SetBaudRate ECAN CONFIG XTD MSG and ECAN CONFIG MATCH MSG TYPE and ECAN CONFIG LINE FILTER OFF ECAN1SetBaudRate 1 3 3 3 1 ecan_config flags set ECAN1 module baud rate ECAN library routine require you to specify the module you want to use To select the desired ECAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of ECAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 304 mikroPascal PRO for dsPICSO 33 and PIC24 ECANxSetMask Prototype procedure ECANxSetMask ECAN MASK word val longint ECAN CONFIG FLAGS word Description The function configures appropriate mask for advanced message filtering Parameters CAN MASK ECAN module mask number Valid values ECAN_MASK constants See ECAN_MASK constants val mask register value This value is bit adjusted to appropriate buffer mask registers ECAN CONFIG FLAGS selects type of messages to filter Valid values ECAN CONFIG ALL VALID MSG ECAN CONFIG MATCH MSG TYPE amp ECAN CONFIG STD MSG ECAN CONFIG MATCH MSG TYPE amp ECAN CONFIG XTD MSG See ECAN_CONFIG_FLAGS constants Requires The ECAN routines are supported only by MCUs with the ECAN module Microcon
641. 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 Example Cf Fat Set File Date 2005 9 30 17 41 0 me None MikroElektronika 288 mikroPascal PRO for dsPICSO 33 and PIC24 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 Reads time date attributes of 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 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 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 da
642. ve to repeat registration procedure from the new compiler and you will get a new license mikoPascal PRO for dsPIC30 33 and PIC24 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 in 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 h
643. w 220 Logical Operations on Bit Level 220 Unsigned and Conversions 221 Signed and Conversions 221 Bitwise Shift Operators 221 Boolean Operators 222 Unary Operators 222 Unary Arithmetic Operator 222 Unary Bitwise Operator 222 Address and Indirection Operator 223 Sizeof Operator 223 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Sizeof Applied to Expression 223 Sizeof Applied to Type 223 Expressions 224 Expression Evaluation 224 Statements 225 Assignment Statements 226 Compound Statements Blocks 226 Conditional Statements 226 If Statement 227 Nested if statements 227 Case Statement 227 Nested Case Statements 228 Iteration Statements 229 For Statement 229 Endless Loop 229 While Statement 230 Repeat Statement 230 Jump Statements 231 Break and Continue Statements 231 Break Statement 231 Continue Statement 231 Exit Statement 232 Goto Statement 232 asm Statement 233 Accessing variables 233 Asm code and SSA optimization 234 With Statement 234 Directives 235 Compiler Directives 235 Directives DEFINE and UNDEFINE 235 Directives IFDEF IFNDEF ELSE and ENDIF 235 Include Directive I 236 Linker Directives 237 Directive absolute 237 Directive org 237 CHAPTER 9 239 mikroPascal PRO for dsPIC30 33 and PIC24 Libraries 239 Hardware Libraries 240 Digital Signal Processing Libraries 240 Miscellaneous Libraries 241 Hardware Libraries 242 ADC Library 242 MikroElektronika 10 mikroPascal PRO for dsPICSO 33 a
644. w the Watch Values Window select Debug Windows gt 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 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 add button MikroElektronika 130 mikroPascal PRO for dsPIC30 33 and PIC24 Also it is possible to add all variables in the Watch Values Window by clicking W Addall button To remove a variable from the Watch Values Window just select the variable that you want to remove and then click the 9 Remove button or press the Delete key It is possible to remove all variables from the Watch Values Window by clicking amp Removeall 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 alues 1E B E Select variable from list WREGL PC 0x00028E 9655 99 ms Double clicking a variable or clicking the Properties button opens the Edit
645. way 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 Protovga Prototype function SPI Ethernet _ 243600 getDnsIpAddress This routine should be used when DHCP server is present on the network to fetch assigned DNS IP address Returns Pointer to the global variable holding DNS IP address Ethernet module has to be initialized See SPI_Ethernet_24j600_Init Vv dnsIpAddr array 4 of byte user DNS IP address buffer memcpy dnsIpAddr SPI Ethernet 243600 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 511 mikroPascal PRO for dsPICSO 33 and PIC24 SPI_Ethernet_24j600_getlpMask Prototype function SPI Ethernet 243600 getIpMask word var IpMask array 4 of byte user IP subnet mask buffer memcpy IpMask SPI Ethernet 243600 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 Proto
646. wer right rectangle corner round_radius radius of the rounded edge pcolor color parameter Valid values 1D13700_ BLACK Black color 1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700_Init routine DTA 1D13700 Rectangle Round Edges Fill 20 20 219 107 12 1D13700 WHITE 1D13700_ Circle Prototype procedure S 1D13700 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 1D13700_ BLACK Black color 1D13700_ WHITE White color Glcd module needs to be initialized See the S1D13700_Init routine eee 1D13700 Circle 120 64 110 1D13700 WHITE 333 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 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 1D13700_ 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
647. 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 193 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Units In mikroPascal PRO for dsPIC30 33 and PIC24 each project consists of a single project file and one or more unit files Project file with extension mppds 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 mc1 file for each unit Uses Clause mikroPascal PRO for dsPIC30 33 and PIC24 includes units by means of the uses clause It consists of t
648. word word word word word word Oe WN Po The example demonstrates CAN protocol The 1st 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 The 1st node then does the same and sends incremented data back to the 2nd node etc Code for the first CAN node Copy Code To Clipboard program CAN 1st var Can_Init_Flags RxTx_ Data Rx_ID const ID 1st Can Send Flags array 8 of byte longint Msg Revd word longint 12111 const ID 2nd longint 3 begin ADPCFG OxFFFF PORTB 0 TRISB 0 Can_Init_Flags Can Send Flags Can Rev Flags Can _ Rev _ Flags Rx_Data_Len word node IDs Can Send Flags CAN TX PRIORITY 0 and form value to be used _CAN TX _XTD FRAME and with CANSendMessage CAN TX NO RTR_ FRAME Can_Init Flags CAN CONFIG SAMPLE THRICE and form value to be used CAN CONFIG PHSEG2 PRG ON and with CANInitialize CAN CONFIG XTD MSG and CAN CONFIG DBL BUFFER ON and CAN CONFIG MATCH MSG TYPE and _CAN CONFIG LINE FILTER OFF MikroElektronika 251 mikoPascal PRO for dsPIC30 33 and PIC24 RxTx Data 0 9 CANIInitialize 1 3 3 3 l Cam Init Flags initialize CAN CAN1SetOperationMode CAN MODE CONFIG 0xFF set CONFIGURATION mode CAN1SetMask _CAN MASK B1 l CAN CONFIG MATCH
649. y 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 SPI External dependencies of Port Expander Library The following variables must be defined in all projects using Port Expander Description Library var SPExpanderRST sbit sfr var SPExpanderRST sbit at LATFO Reset line f a external bitty var SPExpanderCS sbit sfr 3 n Chip Select line var SPExpanderCS sbit at LATF1 bit external var SPExpanderRST Direction 3 Direction of the Reset pin var SPExpanderRST Direction sbit at sbit sfr external pin TRISFO_ bit var SPExpanderCS Direction gs Sag var SPExpanderCS Direction sbit at sbit sfr external Direction of the Chip Select pin TRISFI bit Library Routines Expander_lnit Expander_Init_Advanced Expander_Read_Byte Expander_Write_Byte Expander_Read_PortA Expander_Read_PortB Expander_Read_PortAB Expander_Write_PortA Expander_Write_PortB Expander_Write_PortAB Expander_Set_DirectionPortA Expander_Set_DirectionPortB Expander_Set_DirectionPortAB Expander_Set_PullUpsPortA Expander_Set_PullUpsPortB Expander_Set_PullUpsPortAB O16 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Expander_Init Prototype proc
650. y hours mins byte CE Fat Get File Date year month day hours mins Cf_Fat_Get_File_Date_Modified Prototype sub procedure Cf Fat Get File Date Modified dim byref year as word dim byref month day hours mins as byte 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 day buffer to store day of modification attribute to Upon function execution day of modification attribute is returned through this parameter hours buffer to 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 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 289 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Cf_Fat_Get_File_Size Returns
651. y 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 Attributes www mikroe com Image l File N J Events OnLeftClick Alt OnRightClick OnDblClick OnMouseOver N 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 c Radni mikroC PRO for ds 2 eE E E P Easy_GSM_GPRS mppds i Sources Easy_GSM_GPRS mpas Header Files Binaries Project Level Defines S E Image Files Easy_GSM_GPRS jpg EEPROM Files Active Comments Files L activeComment xml Output Files Other Files 99 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 You can see the contents of the created XML file by expanding Active Comment Editor Active Comments Editor Enter comment name activeComment Active Comment Actions New Rename Properties Attributes www mikroe com Image File Events OnLeftClick Alt OnRightClick OnDb
652. y double clicking on it or pressing the Enter button Also you can sort routines by size or by address Routine List ES Sort By Name Sort By Line imove_Delay Dshift_text_Left Dshift_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 mppds c Progr R eE cS i et eS Led mppds 2 Sources 3 Lcd mpas Binaries Project level defines Image Files EEPROM Files E Active Comments Files 3 Output Files 25 Lcd hex 25 Led asm E Other Files 61 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 The following options are available in the Project Manager icon Description E fee Ss E Remove project from the project group Add file to the active project Remove selected file from the project D Build the active project Run mikroElektronika s Flash programmer For details about adding and removing files from project see Add Remove
653. yle 3 fi single line Advanced Editor Options gS Open options dialog Code Folding V Enable code folding Show Ident Guides J Tools J Output mikoPascal PRO for dsPIC30 33 and PIC24 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 a 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 tat 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 code folding
654. 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 C modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 364 mikroPascal PRO for dsPIC30 33 and PIC24 I2Cx_Start Rems Nothing SCSCSCS SCSCSCSCSCSCSCSCSSSSS Requires MCU with at least one I C module Used 1 C module must be initialized before using this function See I2Cx_Init routine Issue START signal T2C1 Start J I 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 3 Number of I C modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library I2Cx_Restart FRetuns Nothing OOOO 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 RESTART signal T2Cl1_ Restart IC 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 C modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 365 MikroElektronika mikoPascal PRO f
655. your disposal for building complex conditional expressions These operators conform to standard Boolean logic and return either TRUE all ones or FALSE zero logical exclusive OR XOR 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 2 a Unary Bitwise Operator The result of the not bitwise negation 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 220 MikroElektronika mikoPascal PRO for dsPIC30 33 and PIC24 Address and Indirection Operator In the mikroPascal PRO for dsPIC30 33 and PIC24 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 accesses a value indirectly through a pointer result is the value at the address to which operand points constructs a pointer to its operand See Pointers fo
656. ype function ECANxDmaChannelInit DmaChannel word ChannelDir DmaRamBuffAdd word word The function preforms initialization of the DMA module for ECAN Parameters DmaChanne1 DMA Channel number Valid values 0 7 ChannelDir transfer direction Valid values 1 DMA RAM to peripheral and 0 peripheral to DMA RAM DmaRamBuffAdd DMA RAM buffer address DMA RAM location is MCU dependent refer to datasheet for valid address range 0 if DMAchannel parameter is valid 0x0001 if DMA channel is already in use busy OxF FFF if DMA channel parameter is invalid Requires The ECAN routines are supported only by MCUs with the ECAN module Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus channel 0 will transfer 8 words from DMA RAM at 0x4000 to ECANI ECAN1DmaChannelInit 0 1 0x4000 a ECAN library routine require you to specify the module you want to use To select the desired ECAN module simply change the letter x in the routine prototype for a number from 1 to 2 Number of ECAN modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library ECANxSetOperationMode Prototype procedure ECANxSetOperationMode mode word WAIT word Sets the ECAN module to requested mode Parameters mode ECAN module operation mode Valid values ECAN OP MODE constants See ECAN_OP_ MODE constants WAIT ECAN mod
657. zation of Other Units Scope and Visibility Scope Visibility Name Spaces Units Uses Clause Main Unit Other Units Variables External Modifier Variables and dsPIC30 33 and PIC24 Constants Labels Functions and Procedures Functions Procedures Forward declaration Functions reentrancy Types Type Categories Simple Types Derived Types 183 184 184 184 185 185 185 187 190 190 190 190 190 191 191 191 191 192 192 192 192 193 194 194 195 195 196 196 196 197 198 198 199 200 200 201 201 202 203 204 204 204 205 205 MikroElektronika mikroPascal PRO for dsPICSO 33 and PIC24 Arrays 205 Array Declaration 205 Constant Arrays 206 Multi dimensional Arrays 206 Strings 207 String Concatenating 207 Pointers 208 Pointers and memory spaces 209 Function Pointers 209 Operator 210 Pointer Arithmetic 211 Assignment and Comparison 211 Pointer Addition 212 Pointer Subtraction 212 Records 213 Accessing Fields 214 Types Conversions 215 Implicit Conversion 215 Explicit Conversion 216 Conversions Examples 216 Typedef Specifier 217 Type Qualifiers 217 Qualifier const 217 Qualifier volatile 217 Operators 218 Operators Precedence and Associativity 218 Arithmetic Operators 218 Division by Zero 219 Unary Arithmetic Operators 219 Relational Operators 219 Relational Operators Overview 219 Relational Operators in Expressions 219 Bitwise Operators 220 Bitwise Operators Overvie
Download Pdf Manuals
Related Search
Related Contents
Samsung YP-Z3AL คู่มือการใช้งาน (I) La Cité Copyright © All rights reserved.
Failed to retrieve file