Home
Data Sheet - MikroElektronika
Contents
1. SPIL Inge initialize SPI1 module CANSPI 1 3 3 3 1 CANSPI Init Flags initialize CANSPI Notes CANSPI mode NORMAL will be set on exit MikroElektronika 246 mikroBasic PRO for PIC32 CANSPISetBaudRate Prototype sub procedure CANSPISetBaudRate dim SJW BRP PHSE EG2 PROPS CANSPI CONFIG FLAGS as byte Nothing Description Sets the CANSPI module baud rate Due to complexity of the CAN protocol you can not simply force a bps value Instead use this function when the CANSPI module is in Config mode SAM SEG2PHTS and WAKFIL bits are set according to CANSPI CONFIG FLAGS value Refer to datasheet for details Parameters SJW as defined in MCU s datasheet CAN Module BRP as defined in MCU s datasheet CAN Module PHSEG1 as defined in MCU s datasheet CAN Module PHSEG2 as defined in MCU s datasheet CAN Module PROPSEG as defined in MCU s datasheet CAN Module CANSPI CONFIG FLAGS is formed from predefined constants See CANSPI CONFIG FLAGS constants Nothing Requires The CANSPI module must be in Config mode otherwise the function will be ignored See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page set required baud rate and sampling rules dim CANSP
2. MIDDLE SPI CLK IDLE LOW SPI ACTIVE 2 IDLE Expander Init 0 Initialize Port Expander Expander Set DirectionPortA 0 0x00 Set Expander s PORTA to be output Expander Set DirectionPortB 0 0xFF Set Expander s PORTB to be input Expander Set PullUpsPortB 0 0xFF Set pull ups to all of the Expander s PORTB pins while TRUE Endless loop Expander Write PortA 0 counter Write i to expander s PORTA Inc counter PORTB Expander Read PortB 0 Read expander s PORTB and write it to LEDs Delay ms 75 wend end MikroElektronika mikroBasic PRO for PIC32 HW Connection o vcca ovcca ovcca HH Port Expander HW connection 367 MikroElektronika mikoBasic PRO for PIC32 PS 2 Library The mikroBasic PRO for PIC32 provides a library for communication with the common PS 2 keyboard Important The library does not utilize interrupts for data retrieval and requires the oscillator clock to be at least 6MHz The pins to which a PS 2 keyboard is attached should be connected to the pull up resistors Although PS 2 is a two way communication bus this library does not provide MCU to keyboard communication e g pressing the Caps Lock key will not turn on the Caps Lock LED External dependencies of PS 2 Library The following variables must be defined Description in all projects using PS 2 Library P i external ae i PS2 Clock i
3. dnsIpAddr 0 dnsIpAddr 1 dnsIpAddr 2 dnsIpAddr 3 ipMask 0 ipMask 1 ipMask 2 ipMask 3 2995 299 0 SPI Ethernet 245 600 confNetwork ipMask gwlIpAddr dnsIpAddr set network configuration parameters The above mentioned network parameters should be set by this routine only if DHCP module is used Otherwise DHCP will override these settings not MikroElektronika 452 mikroBasic PRO for PIC32 SPI Ethernet 24j600 arpResolve Prototype sub function SPI Ethernet 243600 arpResolve dim byref ip as byte 4 dim tmax as byte as word Description This is ARP module routine It sends an ARP request for given IP address and waits for ARP reply If the requested IP address was resolved an ARP cash entry is used for storing the configuration ARP cash can store up to 3 entries Parameters 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 dim IpAddr as IP address IpAddr IpAddr IpAddr 0 0 0 IpAddr 0 SPI Ethernet 243600 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 Ethern
4. Main Uncomment the function s to test the desired operation s main DEFINE COMPLETE EXAMPLE comment this line to get smaller example fat txt FAT16 not found file contents XX MMC SD FAT16 library by Anton Rieckert file contents 41 10 newline filename MIKROOOxTXT CHECON 0x32 ADIPCFG OxFFFF initialize AN pins as digital Initialize UART1 module UART1 Init 56000 300 MikroElektronika mikoBasic PRO for PIC32 Delay ms 10 UART Write Line MCU Started MCU present report set up SPI for the file read SPI2 Init Advanced SPI MASTER SPI 8 BIT 64 SPI SS DISABLE SPI DATA SAMPLI MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 IDLE Delay ms 10 Fl use fat16 quick format instead of init routine if a formatting is needed if Mmc Fat Init 0 then reinitialize spi at higher speed SPI2 Init Advanced SPI MASTER SPI 8 BIT 8 SPI SS DISABLE SPI DATA SAMPLI MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 IDLE Test start UART Write Line Test Start Test routines Uncomment them one by one to test certain features Create New File Fl IFDEF COMPLETE EXAMPLE Create New File Create Multiple Files Open File Rewrite Open File Append Open File Read Delete File Test File Exist Create Swap File ENDIF UART Write Line Test End else UART Write Line fat txt Note Mme F
5. 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 u The Ethernet services are not stopped while this routine waits for DNS reply The incoming packets will be processed normaly during this time When DHCP module is used global library variable SPI Ethernet 243600 userTimerSec is used to keep track of time It is user responsibility to increment this variable each second in it s code 455 MikroElektronika mikoBasic PRO for PIC32 SPI Ethernet 24j600 doDHCPLeaseTime Prototype sub function SPI Ethernet 245 600 doDHCPLeaseTime as byte This is DHCP module routine It takes care of IP address lease time by decrementing the global lease time library counter When this time expires it s time to contact DHCP server and renew the lease 0 lease time has not expired yet 1 lease time has expired it s time to renew it Ethernet module has to be initialized See SPI Ethernet 24j600 Init while true if SPI Ethernet 243600 doDHCPLeaseTime lt gt 0 the
6. Nothing MCU must have the SPI module Set SPI1 to the Master Mode data length is 16 bit clock Fcy no clock scaling data sampled in the middle of interval clock IDLE state high and data transmitted at low to high clock edge SPI1 Init Advanced SPI MASTER SPI 16 BIT 1 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 IDLI SPI library routines require you to specify the module you want to use To select the desired SPI module simply change the letter x in the routine prototype for a number from 1 to 3 Number of SPI modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 408 mikroBasic PRO for PIC32 SPIx Read Prototype sub function SPIx Read dim data out as word as word Description Reads one word or byte depending on mode set by init routines from the SPI bus Parameters iata out dummy data for clock generation see device Datasheet for SPI modules implementation details Received data Requires Routine requires at least one SPI module Used SPI module must be initialized before using this function See the SPIx Init and SPIx_Init_ Advanced routines read a byte from the SPI bus dim take buffer as byte take SPITI Read buffer SPI library routines require you to specify the module you want to use To select the desired SPI module simply change th
7. Bookmarks Code Explorer Library Manager Macro Editor Messages Project Manager Shift Ctrl F11 Project Settings Routine List Ctri L Quick Converter Ctri Q View Image Preview a Assembly Listing Statistics Windows MikroElektronika 42 mikroBasic PRO for PIC32 Show Hide Software Simulator mikroICD In Circuit Debugger Debug Windows The Tools toolbar can easily be customized by adding new tools in Options F12 window Related topics Keyboard shortcuts Integrated Tools Software Simulator 43 MikroElektronika mikoBasic PRO for PIC32 Project Project Menu Options Project Menu allows the user to easily manipulate current project New Project Shift Ctrl N OpenProject 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 Shift4 Ctrl E Clean Project Folder Import Project Ctrl I B Export Project Ctrl Alt E Project Desin 5 rmm cima prc rmm zc Clean Project Folder Clean Project Folder Jh Import Project ctr4r Import projects created in previous versions of mikroBasic Related topics Keyboard shortcuts Project Toolbar Creating New Project Project M
8. File Name C Projects Hello World mbas 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 C Include None Advanced Selecting all libraries is recommended For beginners Selecting libraries manually using Library Manager recommended For advanced users results in Faster compilation Libary Manager Help Next gt MikroElektronika 616 mikroBasic PRO for PIC32 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 j Cancel Related topics Project Manager Project Settings 617 MikroElektronika mikoBasic PRO for PIC32 Customizing Projects You can change basic project settings in the Project Settings window You can change chip and oscillator frequency Any change in the Project Setting Window affects currently active project only so in case more than one project is open you have to ensure that exactly the desired project is set as active one in the Project Manager Also you can change configuration bits of the selected chip in the Edit Project window Managing Project Group mikroBasic PRO for PIC32 IDE provides convenient option which enables several proje
9. I2Cx Start 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 START signal I2C1 Start PC library routines require you to specify the module you want to use To select the desired C module simply change the letter x in the routine prototype for a number from 1 to 5 Number of I C modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 311 MikroElektronika mikoBasic PRO for PIC32 I2Cx Restart ums Noting 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 I2C 1 Restart FC library routines require you to specify the module you want to use To select the desired C module simply change the letter x in the routine prototype for a number from 1 to 5 Number of IC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library I2Cx Is Idle Prototype sub function I2Cx Is Idle as word Waits for the lC bus to become free This is a blocking function 0 if IC bus is free 1 if IC bus is not free MCU with at least one IC module Used 1 C module must be initialized before using this function See I2Cx Init routine FC library routines require you to specify the module you want
10. m Port Expander SPI Graphic Lcd 1 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 45 MikroElektronika mikoBasic PRO for PIC32 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 sub procedure SPI Glcd Init 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 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
11. Draws a 10x15 part of the image starting from the upper left corner on the coordinate 10 12 Original image size is 16x32 T6963C Partiallmage l0 12 10 15 16 32 Gumage Image dimension must match the display dimension Use the integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd T6963C sprite Prototype sub procedure T6963C sprite dim px py as byte dim const pic as byte dim Sx sy as byte Fills graphic rectangle area px py to px sx py sy with custom size picture Parameters px x coordinate of the upper left picture corner Valid values multiples of the font width py y coordinate of the upper left picture corner pic picture to be displayed sx picture width Valid values multiples of the font width sy picture height Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C sprite 76 einstein 119 draw a sprite If ox and sx eee 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 020 mikroBasic PRO for PIC32 T6963C set cursor Prototype sub procedure T6963C set cursor dim x y as byte Description Sets cursor to row x and column y Parameters x cursor position row number y cursor position column number LIMIT o ooo UUU Example T6963C set cursor cposx
12. Prompt for action Reload file but do not prompt Ignore externally made changes Save Breakpoints Save Bookmarks Auto Correct Auto Save I Auto Complete s Highlighter amp Style V Highlight brackets V Highlight begin end pairs V Enable Auto Save Timeout Interval ZA minutes Spelling V Check Spelling Comment style e tc qi single line Advanced Editor Options 3 Open options dialog Code Folding V Enable code folding V Show Ident Guides Tools J Output mikroBasic PRO for PIC32 Auto Save Auto Save is a function which saves an opened project automatically helping to reduce the risk of data loss in case of a crash or freeze Autosaving is done in time intervals defined by the user Highlighter Highlighting is a convenient feature for spotting brackets which notate begin or end of a routine by making them visually distinct Spelling The Spell Checker underlines unknown objects in the code so they can be easily noticed and corrected before compiling your project Select Tools Options from the drop down menu or click the Show Options Icon B and then select the Spell Checker Tab Comment Style Code Editor has a feature to change the comment style to either single line or multi line Commenting or uncommenting the selected code is done by a simple click of a mouse using the Comment Icon i2 and Uncomment Icon u from the Advanced Edit Toolba
13. Related topics Project Level Defines 135 MikroElektronika mikoBasic PRO for PIC32 Accessing Individual Bits The mikroBasic PRO for PIC32 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 dim Z bit as sbit at SR BlI To access this bit in your code by its name you can write something like this Clear Zero Bit SR Z 0 In this way if Zero bit changes its position in the register you are sure that the appropriate bit will be affected But if Zero bit is not located in the designated register you may get errors Another way of accesing bits is by using the direct member selector with a variable followed by a primary expression Primary expression can be variable constant function call or an expression enclosed by parentheses For individual bit access there are predefined global constants BO B1 B15 or 0 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 F5 1 expression as bit designator Set bit 6 in STATUS register i 5 SR i 1 1 In this way if the target bit changes its position in the register you cannot be sure that you are invoking the appropriate bit
14. Y If RB12 is pressed change cursor else if RB12 bit 0 then Inc curs if curs select case curs case 0 dno Cursor T6963C cursor 0 case 1 blinking cursor T6963C_cursor 1 T6963C cursor blink 1 case 2 non blinking cursor T6963C cursor 1 T6963C cursor blink 0 end select Delay ms 300 end if Ve If RB13 is pressed perform the Partial image demonstration Ve IFDEF PARTIAL IMAGE DEMO if RB13 bit 1 then T6963C_setGrPanel 0 T6963C_setTxtPanel 0 T6963C txtFill 0 T6963C_setGrPanel 1 T6963C_setTxtPanel 0 T6963C_graphics 1 T6963C_text 1 929 MikroElektronika mikoBasic PRO for PIC32 T6963C displayGrPanel 1 T6963C write text txt2 5 15 T6963C ROM MODE XOR Delay 1sec T6963C grFill 0 T6963C Partiallmage 0 0 64 64 240 128 mikroE 240x128 bmp Delay ms 1500 T6963C Partiallmage 0 0 128 128 240 128 mikroE 240x128 bmp Delay ms 1500 T6963C Partiallmage 0 0 240 128 240 128 mikroE 240x128 bmp Delay ms 1500 T6963C_txtFill 0 T6963C write text txt 0 0 T6963C ROM MODE XOR T6963C write text txtl 0 15 T6963C ROM MODE XOR end if ENDIF end if end if end if end if Ve Move cursor even if not visible Ab Inc cposx if cposx T6963C txtCols then cposx 0 Inc cposy if cposy cposy 0 end if end if T6963C set cursor cposx cposy T6963C grHeight
15. ee pte as An array of type bit is not valid invalid i TOI d3 m ecr as array tS Note Bit variables can not be initialized Bit variables can not be members of structures 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 138 mikroBasic PRO for PIC32 Interrupts The PIC32MX generates interrupt requests in response to interrupt events from peripheral modules The Interrupt module exists external to the CPU logic and prioritizes the interrupt events before presenting them to the CPU The PIC32MX Interrupts module includes the following features Up to 96 interrupt sources Up to 64 interrupt vectors Single and Multi Vector mode operations Five external interrupts with edge polarity control Interrupt proximity timer Module freeze in Debug mode Seven user selectable priority levels for each vector Four user selectable subpriority levels within each priority User configurable shadow set based on priority level this feature is not available on all devices refer to the specific device data sheet for availability Software can generate any interrupt User configurable interrupt vector table location ISRs are organized in IVT ISR is defined as a standard function but with the iv directive afterwards which c
16. 425 MikroElektronika mikoBasic PRO for PIC32 SPI Ethernet confNetwork Prototype sub procedure SPI Ethernet confNetwork dim byref ipMask gwIpAddr dnsIpAddr as byte 4 Configures network parameters IP subnet mask gateway IP address DNS IP address when DHCP is not used Parameters ipMask IP subnet mask gwlpAddr gateway IP address dnsIpAddr DNS IP address Nothing Ethernet module has to be initialized See SPI Ethernet Init dim ipMask as byte 4 network mask for example 255 255 255 0 gwlIpAddr as byte 4 gateway router IP address dnsIpAddr as byte 4 DNS server IP address gwIpAddr 0 192 gwlIpAddr 1l 168 gwlIpAddr 2 20 gwlIpAddr 3 6 dnsIpAddr 0 192 dnsIpAddr 1 168 dnsIpAddr 2 20 dnsIpAddr 3 100 255 j 255 255 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 426 mikroBasic PRO for PIC32 SPI Ethernet arpResolve Prototype sub function SPI Ethernet arpResolve dim byref ip as byte 4 dim tmax as byte as 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
17. Library Dependency Tree 1 Port Expander SPI T6963C Gicd Trigonometry External dependencies of SPI T6963C Graphic Lcd Library The implementation of SPI T6963C Graphic Lcd Library routines is based on Port Expander Library routines External dependencies are the same as Port Expander Library external dependencies 485 MikroElektronika mikoBasic PRO for PIC32 Library Routines SPI T6963C config SPI T6963C writeData SPI T6963C writeCommand SPI T6963C setPtr SPI T6963C waitReady SPI T6963C fill SPI T6963C dot SPI T6963C write char SPI T6963C write text SPI T6963C line SPI T6963C rectangle SPI T6963C rectangle round edges SPI T6963C rectangle round edges fill SPI T6963C box SPI T6963C circle SPI T6963C circle fill SPI T6963C image SPI T6963C Partiallmage SPI T6963C sprite SPI T6963C set cursor SPI T6963C clearBit SPI T6963C setBit SPI T6963C negBit SPI T6963C displayGrPanel SPI T6963C displayTxtPanel SPI T6963C setGrPanel SPI T6963C setTxtPanel SPI T6963C panelFill SPI T6963C grFill SPI T6963C txtFill SPI T6963C cursor height SPI T6963C graphics SPI T6963C text SPI T6963C cursor SPI T6963C cursor blink MikroElektronika 486 mikroBasic PRO for PIC32 SPI T6963C config Prototype sub procedure SPI T6963C config dim width height fntW as word dim DeviceAddress as by
18. SPI Glcd Rectangle Prototype sub procedure SPI Glcd Rectangle dim x upper left y upper left x bottom right y bottom right color as 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 SPI communication see SPI Glcd Init routine Draw a rectangle between dots 5 5 and 40 40 SPI Gled Rectangle 5 5 40 40 1 463 MikroElektronika mikoBasic PRO for PIC32 SPI Glcd Rectangle Round Edges Prototype sub procedure Glcd Rectangle Round Edges dim x upper left as byte dim y upper left as byte dim x bottom right as byte dim y bottom right as byte dim radius as byte dim color as 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
19. m F E E E S E E E F T IL T a Related topics Keyboard shortcuts Toolbars 3 MikroElektronika mikoBasic PRO for PIC32 File File Menu Options The File menu is the main entry point for manipulation with the source files L New Unit Ctr N Open Ctri o Recent Files gt Save Ctr S Save As Close Ctri F4 Close All Shift Ctrl F4 Print Preview S25 Print Ctrl P Exit AIL X File Z4 Description O Related topics Keyboard shortcuts File Toolbar Managing Source Files MikroElektronika 38 mikroBasic PRO for PIC32 Edit Edit Menu Options The Edit Menu contains commands for editing the contents of the current document Undo Ctr z Redo Shift Ctrl z My Cut Ctrlex Copy Ctrl C Paste Ctrl V Delete Select All Ctrl Find Ctrl F Find Next F3 Find Previous Shift F3 Replace Ctrl R Find In Files Alt F3 Goto Line Ctri G Advanced Edt Bescipin O 39 MikroElektronika mikoBasic PRO for PIC32 Advanced Description Comment selected code or put single line comment if there is no selection Uncomment selected code or remove single line comment if there is no selection Indent shift ctr I Indent selected code Outdent shift ctr U f Outdent selected code
20. DLE DLE O DI ABOZCA 2088CO A60010 A802D6 A70010 A902D6 O7FF7C 2088CO lt STX gt SPC D A60010 370002 07FF64 370001 o7FF86 FAS000 060000 FAO002 DLE STX 7d j 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 Gi DC3 7 G CR 97B84E E10061 32FFEE 97B84E 10062 32FFEE 97B84E E10063 N a ij2N b 32FFEE 97B84E E10064 32FFEE 37FFFO 97B83E 5000E1 570068 iy2N d aiy2ay7 gt 408010 9FBF40 781F80 O7FFOB B1002F 2088C0 A10010 EF2000 DLE G GO j US 980700 97B8AE 470060 408010 EO0410 32000C 97B8AE 470060 BELL 9 G E 408010 784010 FB8000 781F80 07FF32 BI1002F 200011 470060 DLE O DLE Ox 408810 37FFEF 2088CO AD0010 Fasooo 060000 FAOD02 EF2000 DLE Qij7 SPC 984700 90400E E10468 310009 2001C0 781F80 07FF78 B1002F G lt 50 gt 0 h lt EOT O7FF31 B3CO11 470060 40C810 37FFF4 FASO00 060000 FAO002 19 lt BELL gt DCI EF2000 984700 90400E E10468 310009 200180 781F80 07FF67 SPC i G 50 GU B1002F 07FF20 B3COl1 470060 40C810 37FFF4 FAS000 060000 SPC j BELL lt C 2088EF 20FFFO B7A020 200000 B7A034 200040 B72044 FAO000 i SPC lt SPC gt SF
21. Description Writes requested number of bytes to currently assigned file opened for writing Parameters fdata data to be written data len number of MCCC NR to be written Retums Nothing eee 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 dim file contents as array 42 Cf Fat Write file contents 42 write data to the assigned file Cf Fat Set File Date Prototype sub procedure Cf Fat Set File Date dim year as word dim month as byte dim day as byte dim hours as byte dim mins as byte dim seconds as byte Description Sets the date time stamp Any subsequent file writing operation will write this stamp to currently assigned file s time date attributes Parameters year year attribute Valid values 1980 2107 month month attribute Valid values 1 12 da y day attribute Valid values 1 31 hours hours attribute Valid values 0 23 mins minutes attribute Valid values 0 59 seconds seconds attribute Valid values 0 59 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 oes pe O y y y O MikroEle
22. End of S1D13700 module connections init display for 320 pixel width 240 pixel height S1D13700 Init 320 240 281 MikroElektronika mikoBasic PRO for PIC32 S1D13700 Write Command Prototype sub procedure S1D13700 Write Command dim command as byte Description Writes a command to S1D13700 controller Parameters command command to be issued a1pDiis d cs RIGHT Cursor moves right after write to display memory SPDTSTOQ DECUS Cursor moves left after write to display memory Bipi3990 CS Ue Cursor moves up after write to display E memory 83513200 658 DOWN Cursor moves down after write to display e memory Selects the gray ioa in bits per pixel S1D13700 MEMWRITE Write to display memory S1D13700 MEMREAD Read from display memory Glcd module needs to be initialized See the S1D13700 Init routine Turn the display on S1D13700 Write Command S1D13700 DISP ON MikroElektronika 282 mikroBasic PRO for PIC32 S1D13700 Write Parameter Prototype sub procedure S1D13700 Write Parameter dim parameter as byte Description Writes a parameter to S1D13700 controller Parameters parameter parameter to be written Requires Glcd module needs to be initialized See the S1D13700 Init routine Previously a command must be sent through S1D13700 Write Command routine S1D13700 Write Command S1D13700 CSRW set cursor address 1D13700 Write Parameter Lo start send lower byte of curso
23. begin bat case Gdecl class code compact COnst constructor contains data default deprecated destructor gispid dispinterface div dma d downto dynamic end 6xcepe export exports external far file final finalization finally for MikroElektronika 183 mikroBasic PRO for PIC32 forward goto helper idata if ilevel implementation implements in index inherited initialization inline interface io is qu label library message mod name near nil nodefault not object of on operator or org out overload override package packed pascal pdata platform private procedure program property protected public published raise read readonly record register 184 MikroElektronika mikroBasic PRO for PIC32 Also mikroBasic PRO for PIC32 includes a number of predefined identifiers used in libraries You can replace them by your own definitions if you plan to develop your own libraries For more information see mikroBasic PRO for PIC32 Libraries reintroduce repeat requires rx safecall sbit sealed set sfr shl shr small stdcall stored string threadvar to try type unit until uses var virtual volatile while with write writeonly xdata xor ydata Identifiers Identifiers are arbitrary names of any length given to functions variables symbolic constants us
24. file was not found signal it UART1 Write 0x55 MikroElektronika 216 mikroBasic PRO for PIC32 Delay ms 1000 UART1 Write 0x55 end if end sub a Tries to create a swap file whose size will be at least 100 sectors see Help for details sub procedure M Create Swap File dim i as word for i 0 to 511 Buffer i i next i size Cf Fat Get Swap File 5000 mikroE txt 0x20 see help on this function for details if size 0 then LongIntToStr size err txt UART1 Write Line err txt for i 0 to 4999 Cf Write Sector size Buffer Inc size UART1 Write next i end if end sub Y Main Uncomment the function s to test the desired operation s main err txt FAT16 not found file contents XX CF FAT16 library by Anton Rieckert file contents LINE LEN 2 13 file contents LINE LEN 1 10 file contents LINE LEN 0 filename MIKROOOxTXT define COMPLETE EXAMPLE comment this line to make simpler smaller example CHECON 0x32 ADIPCFG OxFFFF disable A D inputs Initialize UART1 module UART1 Init 56000 Delay ms 10 UART1 Write Line MCU Started MCU present report Init the FAT library use Cf Fat QuickFormat instead of init routine if a format is needed if Cf Fat Init 0 then Delay ms 2000 wait for a while until the card is stabilized period depends on used C
25. next i Name Value Address end PORB tC text 2 0x0800 PC 0x0002E2 71 06 ms MikroElektronika 118 mikroBasic PRO for PIC32 Breakpoints are divided into two groups hardware and software breakpoints The hardware breakpoints are placed in the MCU and provide fastest debugging Number of hardware breakpoints is limited to 8 6 instruction 2 data If all hardware brekpoints are used then the next breakpoint will be software breakpoint These breakpoints are placed inside the mikrolCD and simulate hardware breakpoints Software breakpoints are much slower than hardware breakpoints These differences between hardware and software breakpoints are not visible in the mikroICD software but their different timings are quite notable That s why it is important to know that there are two types of breakpoints The picture below demonstrates step by step execution of the code used in above mentioned examples Common Errors Trying to program the MCU while the mikrolCD is active Trying to debug Release build version of the program with the mikrolCD debugger Trying to debug program code which has been changed but has not been compiled and programmed into the MCU Trying to select line that is empty for Run to cursor F4 and Toggle Breakpoints F5 functions Trying to debug MCU with mikrolCD while Watch Dog Timer is enabled Trying to debug MCU with mikroICD while Power Up Timer is enabled Trying to Step Into F7 the
26. te 13 te 10 uart rd UART1 Read UART1 Write uart_rd end if wend Configure AN pins as digital I O Initialize UART module at 9600 bps Wait for UART module to stabilize Endless loop If data is received read the received data and send data via UART MikroElektronika mikoBasic PRO for PIC32 HW Connection SUB D 9p Receive data Rx CONNECT MCU TO PC p Send CONNECT Data Tx PC TO MCU vec3 suBDop F OSCKLATOR o VCC3 GNO vec UDDUUUUBUUUUTUHUUUUUUUUUU RS232 HW connection MikroElektronika 910 mikroBasic PRO for PIC32 USB Library Universal Serial Bus USB provides a serial bus standard for connecting a wide variety of devices including computers cell phones game consoles PDAs etc USB Library contains HID routines that support 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 steer
27. 408810 37FFEF 2088CO0 AD0010 FASO00 060000 FAO002 EF2000 DLE G i97 A SPC 984700 90400E E10468 310009 2001CO0 781F80 07FF78 B1002F G SO Dh EOT 07FF31 B3C011 470060 40C810 37FFF4 Fasooo 060000 FAO002 1j BELL lt DC1 gt A EF2000 984700 90400E E10468 310009 200180 781F80 07FF67 SPC i G SO C B1002F 07FF20 B3C011 470060 40C810 37FFF4 FA8000 060000 SPC j BELL lt C 2088EF 20FFFO B7A020 200000 B7A034 200040 B72044 FA0000 i SPC 8y SPC SF 0203D8 000000 ZFFFF B7A2A8 O7FF1D 2000C0 781F80 O7FF4F lt ETX gt lt STX gt 8 y B1002F 208610 781F80 200060 781F80 200010 781F80 07FF87 DLE f SPC lt B1006F 208690 781F80 200060 781F80 200020 781F80 O7FF7F ot 0O f SPC US B1006F 200CC8 273987 ED200E 3AFFFE ED2010 3AFFFC 200010 o amp FF SPCo 9 781F80 07FF35 B1002F 208700 781F80 200010 781F80 200010 lt US gt x 5 y BELL 781F80 O7FF D BIOD F 208810 781F80 200050 781F80 200020 US xmj BELL o gt STATUS Idle E MikroElektronika 124 mikroBasic PRO for PIC32 CHAPTER o Software Simulator Overview 125 MikroElektronika mikoBasic PRO for PIC32 Software Simulator The Source level Software Simulator is an integral component of the mikroBasic PRO for PIC32 environment It is designed to s
28. Draws a rounded edge rectangle on Glcd Parameters x upper left x coordinate of the upper left rectangle corner Valid values 0 127 y upper left y coordinate of the upper left rectangle corner Valid values 0 63 x bottom right x coordinate of the lower right rectangle corner Valid values 0 127 y bottom right y coordinate of the lower right rectangle corner Valid values 0 63 round radius radius of the rounded edge color color parameter Valid values 0 2 The parameter color determines the color of the rectangle border 0 white 1 black and 2 inverts each dot Glcd needs to be initialized see Glcd Init routine Draw a rounded edge rectangle between dots 5 5 and 40 40 with the radius of 12 Gled Rectangle Round Edges 5 MikroElektronika 304 mikroBasic PRO for PIC32 Glcd Rectangle Round Edges Fill Prototype sub procedure Glcd Rectangle Round Edges Fill dim x upper left as byte dim y upper left as byte dim x bottom right as byte dim y bottom right as byte dim radius as byte dim color as 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
29. S cos PI 3 res 0 500008 MikroElektronika 608 mikroBasic PRO for PIC32 cosh Prototype sub function cosh dim x as float as float Description Function returns the hyperbolic cosine of x defined mathematically as eX e 2 If the value of x is too large if overflow occurs the function fails Example res cosh PI 3 res 1 600296 eval_poly Prototype sub function eval poly dim x as float dim byref d as array 10 of float dim n as integer as float Function Calculates polynom for number x with coefficients stored in d for degree n exp Prototype sub function exp dim x as float as float Function returns the value of e the base of natural logarithms raised to the power x i e ex Example res exp 0 5 res 1 648721 fabs Prototype sub function fabs dim d as float as float Function returns the absolute i e positive value of a res fabs 1 3 y res 1 3 floor Prototype sub function floor dim x as float as float Function returns the value of parameter x rounded down to the nearest integer Example res floor 15 258 res 15 000000 frexp Prototype sub function frexp dim value as float dim byref eptr as integer as float 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 obje
30. SPI Lcd8 Config SPI Lcd8 Out SPI Lcd8 Out Cp SPI Lcd8 Chr SPI Lcd8 Chr Cp SPI Lcd8 Cmd 479 MikroElektronika mikoBasic PRO for PIC32 SPI Lcd8 Config Rems NM OOOO T 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 dim SPExpanderRST as sbit at LATFO bit SPExpanderCS as sbit at LATF1 bit SPExpanderRST Direction as sbit at TRISFO bit SPExpanderCS Direction as sbit at TRISF1 bit End Port Expander module connections SPII Init Initialize SPI interface SPI Lcd8 Config 0 Intialize Lcd in 8bit mode via spi SPI Lcd8 Out Prototype sub procedure SPI Lcd8 Out dim row column as byte dim byref text as string Prints text on Lcd starting from specified position Both string variables and literals can be passed as a text Parameters row starting position row number column starting position column number text text to be written Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routine Write text Hello on Lcd starting from row 1 column 3 SPI Led Out 1 3 Hellol MikroElektronika 480 mikroBasic PRO f
31. TFT Set Active Prototype sub procedure TFT Set Active dim Set Index Ptr as TTFT Set Index Ptr dim Write Command Ptr as TIFT Write Command Ptr dim Write Data Ptr as TTFT Write Data Ptr Description This function sets appropriate pointers to a user defined basic routines in order to enable multiple working modes Parameters Set Index Ptr Set Index handler Write Command Ptr Write Command handler Write Data Ptr Write Data handler Example of establishing 16 bit communication between TFT display and PORTD PORTE of MCU sub procedure Set Index dim index as byte CFT RS LATD index 0 2i 1 end sub sub procedure Write _ Command dim cmd as byte TFT RS 1 LATD cmd 0 1 end sub sub procedure Write Data dim data as byte TFT RS 1 LATE Hi data LATD Lo data T WR T WR end sub main TRISI TRIS Set Active Set Index Write Command Write Data Init 320 240 MikroElektronika 536 mikroBasic PRO for PIC32 TFT Set Font Prototype sub procedure TFT Set Font dim activeFont as far const byte dim font color as word dim font orientation as 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
32. This kind of selective access is an intrinsic feature of mikroBasic PRO for PIC32 and can be used anywhere in the code Identifiers BO B15 are not case sensitive and have a specific namespace You may override them with your own members 50 815 within any given structure When using literal constants as bit designators instead of predefined ones make sure not to exceed the appropriate type size Also you can access the desired bit by using its alias name in this case Z bit Set Zero Bit 5 pit 1 In this way if the Zero bit changes its register or position in the register you are sure that the appropriate bit will be affected MikroElektronika 136 mikroBasic PRO for PIC32 See Predefined Globals and Constants for more information on register bit names sbit type The mikroBasic PRO for PIC32 compiler has sbit data type which provides access to registers SFRs variables etc You can declare a sbit varible in a unit in such way that it points to a specific bit in SFR register module MyModule dim Abit as sbit sfr external Abit is precisely defined in some external file for example in the main program unit dupl atia end In the main program you have to specify to which register this sbit points to for example program MyProgram din Abit as sbit at PORTB O0 this is where Abit is fully defined main end In this way the variable Abit will actually point to PORTB 0 Please note that we used the keyword
33. a rn byte to fill Glcd memory with Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Clear screen SPI Gleda F3ll Notes None eee SPI Glcd Dot Prototype sub procedure SPI Glcd Dot dim x pos y pos color as 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 O clears dot 1 puts a dot and 2 inverts dot state Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Invert the dot in the upper left corner SPI Glcd Dot 0 0 2 Notes For x and y axis layout explanation see schematic at the bottom of this page 461 MikroElektronika mikoBasic PRO for PIC32 SPI Glcd Line Prototype sub procedure SPI Glcd Line dim x start y start x end y end as integer dim color as byte Description Draws a line on Glcd Parameters Parameters x start x coordinate of the line start Valid values 0 127 y start y coordinate of the line start Valid values 0 63 x end x coordinate of the line end Valid values 0 127 y end y coordinate of the line end Valid values 0 63 color color parameter Valid values 0 2 Parameter color determines the line color 0 white 1 black and 2 inverts each dot Glcd needs to be initialized for SPI comm
34. iiu a sub function isupper dim character as byte as 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 MikroElektronika 580 mikroBasic PRO for PIC32 isxdigit Prototype sub function isxdigit dim character as byte as word p Function returns OxFF if the character is a hex digit 0 9 A F a f otherwise returns zero res isxdigit A returns OxFF res isxdigit P returns 0 toupper Prototype sub function toupper dim character as byte as 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 res toupper a returns A res toupper B returns B tolower Prototype sub function tolower dim character as byte as byte Description If the character is an uppercase letter A Z function returns a lowercase letter Otherwise function returns an unchanged input parameter res tolower A returns a res tolower b returns b 581 MikroElektronika mikoBasic PRO for PIC32 Conversions Library mikroBasic PRO for PIC32 Conversions Library provides routines for numerals to strings and BCD decimal conversions Library Dependency Tree Conversions C_String Library Routines You can get text representation
35. mikoBasic PRO for PIC32 Library Routines SPI Ethernet 24j600 Init SPI Ethernet 24j600 Enable SPI Ethernet 24j600 Disable SPI Ethernet 24j600 doPacket SPI Ethernet 24j600 putByte SPI Ethernet 24j600 putBytes SPI Ethernet 24j600 putString SPI Ethernet 24j600 putConstString SPI Ethernet 24j600 putConstBytes SPI Ethernet 24j600 getByte SPI Ethernet 24j600 getBytes SPI Ethernet 24j600 UserTCP SPI Ethernet 24j600 UserUDP SPI Ethernet 24j600 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 440 mikroBasic PRO for PIC32 SPI Ethernet 24j600 Init Prototype Description Parameters sub procedure SPI Ethernet 24j600 Init dim mac as byte dim ip as byte dim fullDuplex as byte This is MAC module routine It initializes ENC24J600 controller This function is internaly 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 bu
36. mikoBasic PRO for PIC32 Routine List Routine list diplays list of routines and enables filtering routines by name Routine list window can be accessed by pressing Ctrl L You can jump to a desired routine by double clicking on it or pressing the Enter button Also you can sort routines by size or by address Routine List Sort By Name Sort By Line CgiMove Delay Qishift Text Left Cishift Text Right Project Manager Project Manager is IDE feature which allows the users to manage multiple projects Several projects which together make project group may be open at the same time Only one of them may be active at the moment Setting project in active mode is performed by double clicking the desired project in the Project Manager which will result in bolding the project s name Also the name of the currently active project will be diplayed in the Program Manager window title alongside with the number of projects in project group Project Manager dM RS FSS M i n a gs Lcd mbp32 4 Sources amp Lcd mbas Binaries E Project level defines Image Files EEPROM Files C7 Active Comments Files 5 Output Files 23 Lcd hex 23 Lcd asm E Other Files MikroElektronika 58 mikroBasic PRO for PIC32 Following options are available in the Project Manager icon Description EIC TN EIN E Remove project from the project group Add file to the active project Remove se
37. mikroBasic PRO for PIC32 TestBit Prototype sub function TestBit dim register rbit as byte as byte Description Function tests if the bit roit of register is set If set function returns 1 otherwise returns 0 Parameter rbit needs to be a variable or literal with value 0 7 See Predefined globals and constants for more information on register identifiers This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Parameters register desired register rbit desired bit Returns If the bit is set returns 1 otherwise returns 0 Nothing flag TestBit PORTE 1 if RE2 is set otherwise 0 Delay us Prototype sub procedure Delay us const time in us as longword Description Creates a software delay in duration of time in us microseconds 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 time in us delay time in microseconds Valid values constant values range of applicable constants depends on the oscillator frequency eum Noting Example Delay us 1000 One millisecond pause etes None OOO 151 MikroElektronika mikroBasic PRO for PIC32 Delay ms Prototype sub procedure Delay ms const time in ms as longword Description Creates a software delay in duration of time in ms milliseconds This is an inlin
38. 0 i 0 curs 0 cposx 0 cposy 0 Initialize T6369C T6963C init 240 128 8 Enable both graphics and text display at the same time T6963C graphics 1 T6963C text 1 A Text messages T6963C write text txt 0 0 T6963C ROM MODE XOR T6963C write text txtl 0 15 T6963C ROM MODE XOR 1 X Cursor T6963C cursor height 8 8 pixel height T6963C set cursor 0 0 Move cursor to top left T6963C cursor 0 Cursor off MikroElektronika 026 mikroBasic PRO for PIC32 Y y Draw solid boxes Y T6963C box 0 0 239 8 T6963C WHITE T6963C box 0 119 239 127 T6963C WHITE Y 3 Draw rectangles Y IFDEF LINE DEMO T6963C rectangle 0 0 239 127 T6963C WHITE T6963C rectangle 20 20 219 107 T6963C WHITI 40 40 199 87 T6963C WHITE 60 60 179 67 T6963C WHITE T6963C rectangle T6963C rectangle ENDIF Y 3 Draw rounded edge rectangle Y IFDEF LINE DEMO T6963C Rectangle Round Edges 10 10 229 117 12 T6963C WHIT T6963C Rectangle Round Edges 30 30 209 97 12 T6963C WHITI T6963C Rectangle Round Edges 50 50 189 77 12 T6963C WHITI ENDIF 7 i i m E m E Y y Draw filled rounded edge rectangle Y IFDEF FILL DEMO T6963C Rectangle Round Edges Fill 10 10 229 117 12 T6963C WHITE T6963C Rectangle Round Edges Fill 20 20 219 107 12 T6963C B
39. 11 binary literal equals decimal 3 The allowed range of values is imposed by the largest data type in mikroBasic PRO for PIC32 longword The compiler will report an error if the literal exceeds 4294967295 SFFFFFFFF Floating Point Literals A floating point value consists of Decimal integer Decimal point Decimal fraction eor E and a 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 mikroBasic PRO for PIC32 limits floating point constants to the range of 1 17549435082 107 6 80564774407 10 Here are some examples gu 20 0 1 23 Y mci 23 45e6 23 45 10 6 2e 5 vom ug ges 3E 10 3 0 10 10 09E34 0 09 10 34 181 MikroElektronika mikoBasic PRO for PIC32 Character Literals Character literal is one character from the extended ASCII character set enclosed with quotes for example A Character literal can be assigned to variables of 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 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
40. A is 45 in the mikroBasic PRO for PIC32 character set aFontOffs is 20 Demo fonts supplied with the library have an offset of 32 which means that they start with space The user can use fonts given in the file Lib GLCDFonts file located in the Uses folder or create his own fonts List of supported fonts Font Glcd System3x5 Font Glcd System5x7 Font Glcd 5x7 Font Glcd Character8x7 For the sake of the backward compatibility these fonts are supported also System3x5 equivalent to Font G1cd System3x5 FontSystem5x7_ v2 equivalent to Font G1cd System5x7 font5x7 equivalent to Font Glcd 5x7 Character8x7 equivalent to Font Glcd Character8x7 Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Use the custom 5x7 font myfont which starts with space 32 SPI Gled Set Font G8myfont 5 7 32 467 MikroElektronika mikoBasic PRO for PIC32 Glcd Write Char Prototype sub procedure SPI Glcd Write Char dim chrl Xx pos page num color as byte Prints character on Glcd Parameters chr1 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 Requires Glcd needs to be initi
41. DATA3 if exists UNCHANGED DATA2 if exists WAS XORed with 1 IT WAS EQUAL TO START BYTE or STOP DATA2 if exists UNCHANGED DATA1l if exists WAS XORed with 1 IT WAS EQUAL TO START BYTE or STOP DATA1 if exists UNCHANGED 0 to 3 NUMBER OF DATA BYTES SEND CRC generation ero se erc se ere se ere se ete se nd nd nd nd nd datalen xor address crc send xor data 0 if exists crc send xor data 1 Ef exists crc send xor data 2 v if exists cre send not cre send if cro send START BYTE or cre send STOP BYTE then cre send crc send 1 end if NOTE DATALEN 4 0 can not take the START BYTE lt 4 0 gt or STOP BYTE lt 4 0 gt values mikroBasic PRO for PIC32 Software lC Library The mikroBasic PRO for PIC32 provides routines for implementing Software C communication These routines are hardware independent and can be used with any MCU The Software lC library enables you to use MCU as Master in lC communication Multi master mode is not supported Important This library implements time based activities so interrupts need to be disabled when using Software l C All Software C Library functions are blocking call functions they are waiting for I 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
42. Description Library gim o Canppi UN aF SPEE BEE chipsecie dim CanSpi CS as abit at LATFO bit external A fr dim CanSpi Rst S Sbit sfr i A SP a Reset line dim CanSpi Rst as sbit at LATF1 bit external dim CanSpi_CS_ Direction as dim CanSpi CS Direction as sbit at sbie afr extorndi Direction of the Chip Select pin TRISFO bit dim CanSpi Rst Direction as Direction of the Reset pin dim CanSpi Rst Direction as sbit at sbit sfr external Tet pin TRISFI bit 243 MikroElektronika mikoBasic PRO for PIC32 Library Routines CANSPISetOperationMode CANSPIGetOperationMode CANSPIInit CANSPISetBaudRate CANSPISetMask CANSPISetFilter CANSPIRead CANSPIWrite CANSPISetOperationMode Prototype sub procedure CANSPISetOperationMode dim mode as byte dim WAIT as byte Sets the CANSPI module to requested mode Parameters mode CANSPI module operation mode Valid values CANSPT OP MODE constants See CANSPI OP MODE constants WAIT CANSPI mode switching verification request If WAIT 0 the call is non blocking The function does not verify if the CANSPI module is switched to requested mode or not Caller must use CANSPIGetOperationMode to verify correct operation mode before performing mode specific operation If WATT 0 the call is blocking the function won t return until the requested mode is set Requires The CANSPI routines are supported only by MCUs with the SPI module
43. Draws a dot in the current graphic panel of Glcd at coordinates x y x dot position on x axis y dot position on y axis color color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine DETUR SPI T6963C dot x0 SPI T6963C BLACK E SPI_T6963C_write_char DD sub Grey Ghar he Goan fone GIST SPI T6963C write char dim c y mode as byte Writes a char in the current text Writes a char in the current text panel of Glcd at coordinates x y 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 SPI T6963C ROM MODE OR SPI T6963C ROM MODE XOR SPI T6963C ROM MODE AND and SPI T6963C ROM MODE TEXT Mode parameter explanation OR Mode In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in negative mode i e white text on black background AND Mode The text and graphic data shown on display are combined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in t
44. Fill current panel in full graphic text with appropriate value 0 to clear Parameters v value to fill panel with Nothing Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine clear current panel SPI T6963C panelFill 0 None SPI T6963C grFill penes clear current graphic panel SPI T6963C grFill 0 INoes oO SPI T6963C txtFill Toshiba Glcd module needs to be initialized See SPI T6963C Config routine clear current text panel SPI T6963C txtFill 0 Nes None LL 499 MikroElektronika mikoBasic PRO for PIC32 SPI T6963C cursor height Prototype sub procedure SPI T6963C cursor height dim n as byte Parameters n cursor height Valid values 0 7 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example serre cursor height O O OOS Moes None SPI T6963C graphics Enable disable graphic displaying Parameters n graphic enable disable parameter Valid values 0 disable graphic dispaying and 1 enable graphic displaying Toshiba Glcd module needs to be initialized See SPI T6963C Config routine enable graphic displaying SPI T6963C graphics 1 None SPI T6963C text Prototype sub procedure SPI T6963C text dim n as word Enable disable text displaying Parameters n text enable disable parameter Valid values 0 disable text dispaying and 1 enable text displaying Toshiba
45. 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 CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page check the CANSPI1 module for received messages If any was received do something dim msg rcvd rx flags data len as byte data as byte 8 msg id as longint CANSPISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode CANSPI1 module must be in mode in which receive is possible rx flags 0 clear message flags msg rcvd CANSPIRead msg id data data len rx flags then MikroElektronika 250 mikroBasic PRO for PIC32 CANSPIWrite Prototype sub function CANSPIWrite dim id as longint dim byref Data as byte 8 dim DataLen CANSPI TX MSG FLAGS as byte as 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 mea oam TX MSG FLAGS constants 0 if all Transmit Buffers are b
46. PWM Start PWM Stop MikroElektronika 372 mikroBasic PRO for PIC32 PWM Init Prototype sub function PWM Init dim freq hz as longword dim enable channel x timer prescale use timer x as word as word Initializes the PWM module with duty ratio O Parameters freq hz PWM frequency in Hz refer to device datasheet for correct values in respect with Fosc enable channel x number of PWM channel to be initialized Refer to MCU s datasheet for available PWM channels timer prescale timer prescaler parameter Valid values 1 8 64 and 256 use timer x timerto be used with the PWM module Valid values 2 Timer2 and 3 Timer3 OxFFFF if timer settings are not valid otherwise returns calculated timer period MCU must have the HW PWM Module Initializes the PWM module at 5KHz channel 1 no clock prescale timer2 dim pwm periodi as word pwm periodi PWM Init 5000 1 0 2 Number of available PWM channels depends on MCU Refer to MCU datasheet for details PWM Init Advanced Prototype sub function PWM Init Advanced dim freq hz Fpb kHz as longword dim enable channel x timer prescale use timer x as word as word Initializes the PWM module with duty ratio O Parameters freq hz PWM frequency in Hz Fpb kHz Peripheral Bus Clock frequency in kHz enable channel x number of PWM channel to be initialized Refer to MCU s datasheet for available PWM channels timer prescale timer prescale
47. Requires Software UART must be initialized before using this function See the Soft UART Init 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 dim some byte as byte some byte SOA Write a byte via Soft UART Soft UART Write some byte The Software UART library implements time based activities so interrupts need to be disabled when using it MikroElektronika 398 mikroBasic PRO for PIC32 Soft UART Break Prototype sub procedure Soft UART Break Description Soft UART Read is blocking routine and it can block the program flow Calling Soft UART Break routine from the interrupt will unblock the program execution This mechanism is similar to WDT dim datal error counter as byte sub procedure TimerlInt org IVT ADDR TIINTERRUPT counter 0 if counter gt 20 then Soft UART Break counter 0 reset counter else Inc counter increment counter end if TIIF bit 0 Clear Timerl overflow interrupt flag end sub main if Soft UART Init PORTF 2 3 14400 0 0 Soft UART Write 0x55 end if try Soft UART Read with blocking prevention mechanism IPCD IPCO or 0x1000 Interrupt priority level 1 TITE bit 1 Enable Timerl interrupts T1CON 0x8030 Timerl ON internal clock FCY prescaler 1 256 datal Soft UART Read amp error TIIE pit Disable Tim
48. SetBit ClearBit TestBit MikroElektronika 144 mikroBasic PRO for PIC32 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 ClrWat DisableContextSaving SetFuncCall SetOrg DoGetDateTime DoGetVersion KVAO TO KVA1 KVA1 TO KVAO KVA TO PA PA TO KVAO PA TO KVA1 CPO Get CPO Set Enablelnterrupts Disablelnterrupts 115 MikroElektronika mikoBasic PRO for PIC32 Prototype sub function Lo dim number as longint as 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 sub function Hi dim number as longint as 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
49. Sets calibration constants Parameters min X coordinate of the bottom left corner of the working area x coordinate of the upper right corner of the working area y coordinate of the bottom left corner of the working area E y coordinate of the upper right corner of the working area TP TFT Set Calibration Consts 148 3590 519 3370 Set calibration constants 559 MikroElektronika mikoBasic PRO for PIC32 HW Connection TFT 320x240 display MI0283QT2 Touch Panel TFT HW connection mikroBasic PRO for PIC32 UART Library The UART hardware module is available with a number of PIC32 MCUs The mikroBasic PRO for PIC32 UART Library provides comfortable work with the Asynchronous full duplex mode Important UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Switching between the UART modules in the UART library is done by the UART Set Active function UART modules have to be previously initialized Library Routines UARTx Init UARTx Init Advanced UARTx Data Ready UARTx Tx Idle UARTx Read UARTx Read Text UARTx Write UARTx Write Text UART Set Active 561 MikroElektronika mikoBasic PRO for PI
50. To clear file and start with new data for loop 1 to 99 UART1 Write file contents 0 loop div 10 48 file contents 1 loop mod 10 48 Mmc Fat Write file contents LINE LEN 1 next loop end sub ELEC Creates many new files and writes sub procedure M Create Multiple Files for loop2 B to zZ UART1 Write loop2 y filename 7 loop2 Mmc Fat Set File Date 2011 1 12 11 9 0 Mmc Fat Assign filename 0xA0 Mmc Fat Rewrite for loop_ 1 to 44 file_contents 0 byte loop_ div 10 48 file_contents 1 byte loop_ mod 10 48 Mmc Fat Write file contents 42 next loop next loop2 end sub this iSSSS ssSSsee Opens an existing file and sub procedure M Open File Rewrite filename 7 C Mmc Fat Assign filename Mmc Fat Rewrite for loop 1 to 55 file contents 0 byte loop div 10 file contents 1 byte loop mod 10 Mmc Fat Write file contents 42 next loop end sub 0 MocceepencereuEe Opens an existing file and 1 and alters the date time stamp sub procedure M Open File Append filename 7 B Mme Fat Assign filename 0 Mmc Fat Set File Date 2009 1 23 17 22 0 rewrites We want 5 files on the MMC card write data to the assigned file data to them line can slow down the performance set filename Set file date amp time info find existing file or create a new on To clear file and start with new data write da
51. mikoBasic PRO for PIC32 LoWord Prototype sub function LoWord dim val as longint as word Description The function returns low word of val The function does not interpret bit patterns of va1 it merely returns 16 bits as found in register Parameters val input value Returns Low word of val bits 15 0 0x12345678 tmp LoWord d Equals 0x5678 HiWord Prototype sub function HiWord dim val as longint as word Description The function returns high word of val The function does not interpret bit patterns of va1 it merely returns 16 bits as found in register Parameters val input value Parameters Returns High word of val bits 31 16 0x12345678 tmp HiWord d Equals 0x1234 MikroElektronika 118 mikroBasic PRO for PIC32 Inc eum Nong p 4 Inc p pis now 5 Dec eum Nong p 4 Inc p p is now 3 Chr Prototype sub function Chr dim code as byte as char Description Function returns a character associated with 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 withthe speciied charadler ci O Example c Chr 10 returns the linefeed character Noes Noe 149 MikroElektronika mikoBasic PRO for PIC32 Ord Prototype s
52. mikroBasic PRO for PIC32 Manual mikroBasic PRO for PIC32 is a full featured compiler for PIC32 MCUs from Microchip It is designed for developing building and debugging PIC32 based embedded applications This development environment has a wide range offeatures 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 3096 code reduction and many more Numerous ready to use and well explained examples will give a good start for your embedded project 7 MikroElektronika SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD waking ib si ple mikoBasic PRO for PIC32 Table of Contents CHAPTER 1 30 INTRODUCTION 30 Introduction to mikroBasic PRO for PIC32 31 Features 31 Where to Start 31 Software License Agreement 32 mikroElektronika Associates License Statement and Limited Warranty 32 IMPORTANT READ CAREFULLY 32 LIMITED WARRANTY 32 HIGH RISK ACTIVITIES 33 GENERAL PROVISIONS 33 Technical Support 34 How to Register 34 Who Gets the License Key 34 How to Get License Key 34 After Receving the License Key 36 CHAPTER 2 38 mikroBasic PRO for PIC32 38 Environment 38 Main Menu Options 39 File 40 File Menu Options 40 Edit 41 Edit Menu Options 41 Find Text 42 Replace Text 42 Find In Files 43 Go To Line 43 Regular expressions option 43 View 44 View Menu Options 44 Project 46 Project
53. o x e co CRC check flag When set CRC check will be disabled x and packets with invalid CRC field will be accepted o o X x N BE o MAC Unicast traffic receive filter flag When set MAC SPI Ethernet unicast traffic will be disabled UNICAST eo x e AR o x Co o Nothing Ethernet module has to be initialized See SPI Ethernet Init SPI Ethernet Disable SPI Ethernet CRC or SPI Ethernet UNICAST Y disable CRC checking and Unicast traffic Advanced filtering available in the ENC28J60 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 ENC28J60 module should be properly cofigured by the means of SPI Ethernet Init routine MikroElektronika 418 mikroBasic PRO for PIC32 SPI Ethernet doPacket Prototype sub function SPI Ethernet doPacket as 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 successf
54. sClock MikroElektronika 122 mikroBasic PRO for PIC32 Notes The user can change the clock in the Stopwatch Window which will recalculate values for the latest specified frequency Changing the clock in the Stopwatch Window does not affect actual project settings it only provides a simulation Stopwatch is available only when Software Simulator is selected as a debugger EEPROM Watch Window Note EEPROM Watch Window is available only when mikrolCD is selected as a debugger To show the EEPROM Watch Window select Debug Windows EEPROM from the View drop down menu The EEPROM Watch Window shows current content of the MCU s internal EEPROM memory There are two action buttons concerning the EEPROM Watch Window Read EEPROM Reads data from MCU s internal EEPROM memory and loads it up into the EEPROM window Write EEPROM Writes data from the EEPROM window into MCU s internal EEPROM memory EEPROM Watch agent nn ToS STATUS Idle 123 MikroElektronika mikoBasic PRO for PIC32 Code Watch Window Note Code Watch Window is available only when mikrolCD is selected as a debugger To show the Code Watch Window select Debug Windows Code from the View drop down menu The Code Watch Window shows code hex format written into the MCU There is one action button concerning the Code Watch Window Read code Reads code from the MCU and loads it up into the Code Window Code reading is
55. w C UART E Conversions ByteToBinaryStr WordToBinaryStr LongWordToBinaryStr BinaryToGray GrayToBinary Kal From the Library Manager the user can also uninstall the desired package by right clicking the the appropriate node and from the drop down menu choose Uninstall package E Library Manager a ESTIS IE C Sound amp spr amp E SPI Ethernet C SPI_Gled E sPr Lcd w SPI Lcde C sPI T seac CO Sprintf C Sprinti C Sprint v T6963c O Time amp C TeuchPanel Trigonometry a O Twi uaRT D E E E E Help Examples Uninstall package BinaryToGray GrayToBinary ivi Related topics mikroBasic PRO for PIC Libraries Creating New Library MikroElektronika 62 mikroBasic PRO for PIC32 Routine List Routine list diplays list of routines and enables filtering routines by name Routine list window can be accessed by pressing Ctrl L You can jump to a desired routine by double clicking on it or pressing the Enter button Also you can sort routines by size or by address Routine List Sort By Name Sort By Line C9iMove Delay Cishift Text Left Cishift Text Right Statistics After successful compilation you can review statistics of your code Click the Statistics Icon Bu Memory Usage Windows Provides overview of RAM and ROM usage in the various forms 63 MikroElektronika mikoBasic PRO for PIC32
56. 0 239 127 S1D13700 WHITE S1D13700 Rectangle Prototype sub procedure S1D13700 Rectangle dim x0 y0 x1 yl as word dim pcolor as ue ae Description Draws a rectangle on Glcd Parameters x0 x coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner pcolor color parameter Valid values S1D13700 BLACK Black color 1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine 1D13700 rectangle 20 20 219 107 S1D13700 WHITE 289 MikroElektronika mikoBasic PRO for PIC32 S1D13700 Box Prototype sub procedure S1D13700 Box dim x0 y0 xl yl as word dim pcolor as byte Description Draws a rectangle on Glcd Parameters x0 x coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner pcolor color parameter Valid values S 1D13700 BLACK Black color S1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine o S1D13700 Box 0 119 239 127 S1D13700 WHITE S1D13700 Rectangle Round Edges Prototype void S1D13700 Rectangle Round Edges unsigned int x upper left unsigned int y upper left un
57. 659Hz duration 250ms end sub sub procedure Tone2 Sound Play 698 250 Frequency 698Hz duration 250ms end sub sub procedure Tone3 Sound Play 784 250 Frequency 784Hz duration 250ms end sub sub procedure Melody Plays the melody Yellow house Tonel Tone2 Tone3 Tone3 Tonel Tone2 Tone3 Tone3 Tonel Tone2 Tone3 Tonel Tone2 Tone3 Tone3 Tonel Tone2 Tone3 Tone3 Tone3 Tone2 Tone2 Tonel end sub sub procedure ToneA Tones used in Melody2 function Sound Play 880 50 end sub sub procedure ToneC Sound Play 1046 50 end sub sub procedure ToneE Sound Play 1318 50 end sub sub procedure Melody2 Plays Melody2 dim counter as byte for counter 9 to 1 step 1 ToneA ToneC r oneE next counter end sub n main CHECON 0x32 ADIPCFG OxFFFF Configure AN pins as digital I O MikroElektronika 402 mikroBasic PRO for PIC32 TRISB Sound Ini Sound Play 880 while TRU if But while nop wend end if Rt ad OxF8 PORTD 3 1000 on PORTB 7 1 1 RB7 bit lt gt 0 if Button PORTB 6 1 1 Tone2 while nop wend end if RB6 bit 0 if Button PORTB 5 1 1 Tone3 while nop wend end if RB5 bit 0 if Button PORTB 4 1 1 Melody2 while nop wend end if RB4 bit lt gt 0 if Button PORTB 3 1 1 Melody while nop wend end
58. Active Comment Actions New Rename Properties 3 Attributes Url Image File Events OnLeftClick Alt OnRightClick OnDblClick OnMouseOver Add Image To Project Add File To Project You can notice that when you start typing a name properties pane is automatically displayed so you can edit properties if you wish 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 Images File File has to be previously added to Project Project Manager gt Other Files There are four predefined event types you can apply to an Active Comment 1 OnLeftClick Alt 2 OnRightClick 3 OnDoubleClick 4 OnMouseOver 95 MikroElektronika mikoBasic PRO for PIC32 First three event types can have one of the following three actions 1 OpenUrl Opens entered URL in default Web browser 2 OpenFile Opens a file within a default program associated with the file extension defined by Windows 3 None Does nothing The fourth event OnMouseOver has only 2 actions 1 Previewlmage Shows image when cursor is moved over a comment 2 None Does nothing Attributes are tightly bounded with events For example you can not have OnLeftClick Alt gt OpenFile if there is no file attribute set or if there is no file
59. All the routines constants in main program will be above the address 0x9D000000 end MikroElektronika 236 mikroBasic PRO for PIC32 CHAPTER 9 mikroBasic PRO for PIC32 Libraries mikroBasic PRO for PIC32 provides a set of libraries which simplify the initialization and use of PIC32 and their modules Use Library manager to include mikroBasic PRO for PIC32 Libraries in you project 231 MikroElektronika mikoBasic PRO for PIC32 Hardware Libraries ADC Library CANSPI Library Compact Flash Library Epson S1D13700 Graphic Lcd Library Flash Memory Library Graphic Lcd Library PC Library Keypad Library Lcd Library Manchester Code Library Memory Manager Library Multi Media Card Library OneWire Library Peripheral Pin Select Library Port Expander Library PS 2 Library PWM Library RS 485 Library Software C Library Software SPI Library Software UART Library Sound Library SPI Library SPI Ethernet Library SPI Ethernet ENC24J600 Library SPI Graphic Lcd Library SPI Lcd Library SPI Lcd8 Library SPI T6963C Graphic Lcd Library T6963C Graphic Lcd Library TFT Display Library Touch Panel Library Touch Panel TFT Library UART Library USB Library Miscellaneous Libraries Button Library C Type Library Conversions Library Setjmp Library String Library Time Library Trigon Library Trigono
60. Changes selected text case to lowercase Changes selected text case to uppercase Changes selected text case to titlercase Find Text Dialog box for searching the document for the specified text The search is performed in the direction specified If the string is 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 MikroElektronika 40 mikroBasic PRO for PIC32 Find In Files Dialog box for searching for a text string in current file all opened files or in files on a disk The string to search for is specified in the Text to find field If Search in directories option is selected The files to search are specified in the Files mask and Path fields ok cance Go To Line Dialog box that allows the user to specify the line number at which the cursor should be positioned Regular expressions option By checking this box you will be able to advance your search through Regular expressions Search for unsigned x20int o He RI lt Related topics Keyboard shortcuts Edit Toolbar Advanced Edit Toolbar a MikroElektronika mikoBasic PRO for PIC32 View View Menu Options View Menu contains commands for controlling the on screen display of the current project Debug Windows gt Toolbars
61. Direction of the Data 5 pin D6 Direction Direction of the Data 6 pin D7 Direction Direction of the Data 7 pin CI RS uU Uu Cu t UC VI uU l must be defined before using this function LCD module connections dim LC as sbit at LATDO bit dim LCD EN as sbit at LATD1 bit dim LC as sbit at LATBO bit dim LC as Sbit at LATBl bit dim LC as sbit at LATB2 bit dim LC as sbit at LATB3 bit dim LC Direction as sbit at TRISDO bit dim LCD EN Direction as sbit at TRISD1 bit dim LCD D4 Direction as sbit at TRISBO bit dim LCD D5 Direction as sbit at TRISB1 bit dim LCD D6 Direction as sbit at TRISB2 bit dim LCD D7 Direction as sbit at TRISB3 bit End LCD module connections Led rnc 321 MikroElektronika mikoBasic PRO for PIC32 Lcd Out DE sub procedure Lcd Out dim row column as word dim byref text as 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 aes Hello on Lcd starting from row 1 column 3 Lcd Out 3 Hello Notes Noe Lcd Out Cp Prototype sub procedure Lcd Out Cp dim byref text as string Prints text on Lcd at current cursor position Both string variables and literals can be passed as a text text tex
62. DriveB Direction as sbit at TRISC14 bit End Touch Panel module connections TP Press Detect lt gt 0 then MikroElektronika 092 mikroBasic PRO for PIC32 TP Get Coordinates y coordinate as word as 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 if reading is within display dimension range Prototype sub function TP Get Coordinates dim byref x coordinate as word dim byref 0 if reading is out of display dimension range if TP Get Coordinates 8x coord Gy coord gna if TP Calibrate Bottom Left Remms Nom bump secerinrere Botton lefe0 T Calibration of Terum qe umet TP Calibrate Upper Right Rems Nothing Example TP Calibrate Upper Right Calibration of upper right corner ee Me 553 MikroElektronika mikoBasic PRO for PIC32 TP Get Calibration Consts Prototype sub procedure TP Get Calibration Consts dim byref x min as word dim byref x max as word dim byref y min as word dim byref y max as word Description Gets calibration constants after calibration is done and stores them in x min x max y min and y max parameters Parameters x min x coordinate of the bottom left corner of the working area x max X coordinate of the upper right corner of the working area y mi
63. Gled Rectangle Round Edges Fill Gled Box Gled Circle Gled Circle Fill Gled Set Font Gled Write Char Glcd Write Text Gled Image Glcd Partiallmage Glcd Init Prototype sub procedure Glcd Init Description Initializes the Glcd module Each of the control lines are both port and pin configurable while data lines must be on a single port pins lt 0 7 gt Requires Global variables DO Data pin 0 D1 Data pin 1 D2 Data pin 2 03 Data pin 3 D4 Data pin 4 D5 Data pin 5 D6 Data pin 6 D7 Data pin 7 CS1 Chip select 1 signal pin CS2 Chip select 2 signal pin RS Register select signal pin RW Read Write Signal pin de oat t sd ed AA d t ad MikroElektronika 298 mikroBasic PRO for PIC32 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 D CS1 Direction Direction of the Chip select 1 pin D CS2 Direction Direction of the Chip select 2 pin D RS Direction Direction of the Register select signal pin LCD RW Direction Direction of the Read Write signal pin LCD EN Direction Direction of the Enable signal pin
64. However the user can specify any clock rate up to 1 MHz scl requested serial clock rate MCU with the IC module Initialize the I2C1 module with clock_rate 100000 I2C1 Init 100000 Refer to the MCU s datasheet for correct values of the sc1 in respect with Fosc C library routines require you to specify the module you want to use To select the desired lC module simply change the letter x in the routine prototype for a number from 1 to 3 Number of I C modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 310 mikroBasic PRO for PIC32 I2Cx Init Advanced Prototype sub procedure I2Cx Init Advanced dim Fclk Khz scl as dword Description This function configures and initializes the desired IC module using Peripheral Bus Clock and default initialization settings As per the lC standard SCL clock may be 100 kHz or 400 kHz However the user can specify any clock rate up to 1 MHz Parameters Fclk Khz Peripheral Bus Clock frequency in kHz scl requested serial clock rate Nothing Requires MCU with the I C module PC library routines require you to specify the module you want to use To select the desired 1 C module simply change the letter x in the routine prototype for a number from 1 to 3 Number of IC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library
65. 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 nul 1 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 null character You can assign string literal to a string variable or to an array of char Here are several string literals Hello world message 12 chars long Temperature is stable message 21 chars long mo M two spaces 2 chars long TOC letter 1 char long wi null string 0 chars long The quote itself cannot be a part of the string literal i e there is no escape sequence You could use the built in function Chr to print a quote Chr 34 Also see String Splicing MikroElektronika 182 mikoBasic PRO for PIC32 Keywords Keywords are special purpose words which cannot be used as normal identifier names Beside standard BASIC keywords all relevant SFR are defined as global variables and represent reserved words that cannot be redefined for example PO TMR1 T1CON etc Probe Code Assistant for specific letters Ctrl Space in Editor or refer to Predefined Globals and Constants Here is the alphabetical listing of keywords in mikroBasic PRO for PIC32 absolute abstract and array as asm assembler zd Bi automated bdata
66. OnMouseOver gt OnLeftClick Alt lt Events gt OnRightClick aes o OnDblClick activeCommen OnMouseOver Add Image To Project Add File To Project As we mentioned above you can add image or file which are already included in project If the the desired image or file aren t added you can do it directly from here by clicking the Add Image To Project Or Add File To Project button 97 MikroElektronika mikoBasic PRO for PIC32 Next file dialog will be opened Images My Recent Documents File name Easy GSM GPRS Files of type Image Files bmp ipg png My Network C Open as read only There you should select the desired image to be added In our example Easy GSM GPRS jpg image will be added Selected picture is automatically added to the drop down list of the Image field in Active Comment Editor Active Comments Editor Select Active Comment activeComment Active Comment Actions New Rename Properties 3 Attributes www mikroe com Easy G5M GPRS jpg B 3 Events OnLeftClick Alt Mo OnRightClick None OnDblClick lor OnMouseOver No Add Image To Project Add File To Project MikroElektronika 98 mikroBasic PRO for PIC32 Now when image has been selected we can assign an event to it For example OnMouseOver will be used for Previewlmage action and OnLeftClick Alt will be assigned to OpenUrl action m
67. Relational Operators in Expressions 219 Bitwise Operators 220 Bitwise Operators Overview 220 MikroElektronika mikoBasic PRO for PIC32 Logical Operations on Bit Level Unsigned and Conversions Signed and Conversions Bitwise Shift Operators Boolean Operators Unary Operators Unary Arithmetic Operators Unary Bitwise Operator Address and Indirection Operator Sizeof Operator Sizeof Applied to Expression Sizeof Applied to Type Expressions Expression Evaluation Statements Assignment Statements Conditional Statements If Statement Nested If statements Select Case Statement Nested switch Iteration Statements Loops For Statement Endless Loop While Statement Do Statement Jump Statements Break and Continue Statements Break Statement Continue Statement Exit Statement Return Statement Goto Statement Gosub Statement asm Statement Accessing variables Asm code and SSA optimization Directives Compiler Directives Directives ZDEFINE and ZUNDEFINE Directives IFDEF IFNDEF ELSE and ZENDIF Include Directive zl 220 221 221 221 222 222 222 222 222 223 223 223 224 224 225 225 226 226 226 227 228 228 228 229 229 230 230 230 230 231 231 231 232 233 233 233 234 235 235 235 235 236 MikroElektronika 10 mikroBasic PRO for PIC32 Explicit Path 237 Directive absolute 237 Directive org 237 Directive orgall 238 CHAPTER 9 239 mikroBasic PRO for PIC32 Libraries 239 Hardware Libraries
68. S1D13700 BLACK Black color 1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine 1D13700 Rectangle Round Edges Fill 20 20 219 107 12 S1D13700 WHITE S1D13700 Circle dim radius as word dim color as byte Description Draws a circle on Glcd Prototype sub procedure S1D13700 Circle dim x center as word dim y center as word Parameters x center X coordinate of the circle center y center y coordinate of the circle center radius radius size color color parameter Valid values S1D13700 BLACK Black color S1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine amie S1D13700 Circle 120 64 110 S1D13700 WHITE 291 MikroElektronika mikoBasic PRO for PIC32 S1D13700 Circle Fill Prototype sub procedure S1D13700 Circle Fill dim x center as word dim y center as word dim radius as word dim color as 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 S 1D13700 BLACK Black color S1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine 1D13700 Circle Fi11 120 64 110 S1D13700 WHITE S1D13700 Image Prototype sub procedure S1D13700 Image dim image as const byte Descri
69. SPI variables Ethernet 243600 CS Chip Select line Ethernet_24j600_CS_Direction Direction of the Chip Select pin Ethernet_24j600_RST Reset line Ethernet 243600 RST must be defined before using this function T Direction Direction of the Reset pin The SPI module needs to be initialized See the SPIx Init and SPIx Init Advanced routines mE ehternet NIC pinout PI Ethernet 243600 CS as sbit at LATF1 bit PI Ethernet 243600 CS Direction as sbit at TRISF1 bit dim S dim end my my my my my my my my myI myI myI myI SPI SPI EGOTIATION PD10 acAddr as byte 6 pAddr as byte 4 acAddr acAddr acAddr acAddr acAddr acAddr pAddr 0 pAddr 1 2 3 pAddr pAddr 2 3 1 Init 0 0x00 0x14 0x45 0x76 0x19 Ox3F 192 168 20 60 mE ehternet NIC pinout my MAC address my IP addr Ethernet 243600 FULLDUPLI Ethernet 243600 Init myMacAddr myIpAddr SPI and SPI EX and SPI Ethernet 243600 MANUAL Ethernet 243600 MikroElektronika 442 mikroBasic PRO for PIC32 SPI Ethernet 24j600 Enable Prototype sub procedure SPI Ethernet 245600 Enable dim enFlt as 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 enable
70. The number of assigned values must not exceed the specified length Vice versa is possible when the trailing excess elements will be 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 dim m as byte 5 10 2 dimensional array of size 5x10 A variable m is an array of 5 elements which in turn are arrays of 10 byte each Thus we have a matrix of 5x10 elements where the first elementis n 0 0 and last one is m 4 9 The first element of the 4th row would be m 3 0 Strings A string represents a sequence of characters equivalent to an array of char It is declared like this string string length The specifier string length is anumber of characters a string consists of The string is stored internally as the given sequence of characters plus a final nu1 1 character zero This appended stamp does not count against 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 The string on the right side of an assignment operator has to be shorter than another one or of equal length For example dim msgl as string 20 dim msg2 as string 19 main
71. Variables Displays variables sorted by addresses TA ku static used 44 bytes 0 1 ed on avatabie 32768 bytes 99 9 Total 32768 bytes Project Name C Development Systems LV32MX v l CD COG 2x16 iLedmep32 Tie 1 31 2011 1 03 40 PM sere mbit com Used RAM Locations Displays used RAM memory locations and their names Variables Sorted By Address Click on column header to sort table by Address Name Unique Assembler Name or Size 64 mikroBasic PRO for PIC32 SFR Locations Displays list of used SFR locations 8855825858908 8H TESTEN BRBRBESSRBUIRHTEBGREBecmavauneawneo n 8 411 ROM Memory Usage Displays ROM memory space usage in a pie like form ka ve 3O7Sbytes 0 6 E re 521214 bytes 99 4 Total 524289 bytes Project Name C Development Systems V32MX v lLCD COG 2x16 Lcd mcp32 Teme 1 31 2011 1 03 40 PM verew triroe coen mikoBasic PRO for PIC32 ROM Memory Constants Displays ROM memory constants and their addresses ROM Memory Constants Project Name C Development Systems V32MX VEILED COG 2x16 cd mda Time 1 31 2011 1 03 40 FM ves m cos com Functions Sorts and displays functions in various ways Functions Sorted By Address Chick on column header to sort table by Address Name Urigue Assembler Name or Size H dl d M Project Name C Development SystemslL V32MX VEILED COG 2x16 l cd mcpdz Time 1 31 20
72. dim CF CE1 direction as sbit sfr external Direction of the Chip Detect pin Direction of the Chip Enable pin TRISB4 bit dim CF CE1 direction TRISB3 bit as i i dim CF OE direction as sbit at TRISB5 dim CF CD1 direction as sbit at as sbit at dim CF A2 direction as P x n dim CF A2 direction as sbit at TRISB2 z S e Direction of the Address 2 pin sbit sfr external bit dim CF A1 direction as p 3 dim CF Al direction as sbit at TRISB1 a Direction of the Address 1 pin i sbit sfr external bit dim CF AO direction as g dim CF A0 direction as sbit at TRISBO TUM Direction of the Address 0 pin f recti sbit sfr external bit MikroElektronika 260 mikroBasic PRO for PIC32 Library Routines Cf Init Cf Detect Cf Enable Cf Disable Cf Read Init Cf Read Byte Cf Write Init Cf Write Byte Cf Read Sector Cf Write Sector Routines for file handling Cf Fat Init Cf Fat QuickFormat Cf Fat Assign Cf Fat Reset Cf Fat Read Cf Fat Rewrite Cf Fat Append Cf Fat Delete Cf Fat Write Cf Fat Set File Date Cf Fat Get File Date Cf Fat Get File Date Modified Cf Fat Get File Size Cf Fat Get Swap File The following routine is for the internal use by compiler only Cf Issue ID Command 261 MikroElektronika mikoBasic PRO for PIC32 Cf Init Rums Wm OOOO Requires Global variables CF Data Port Compact Flas
73. 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 RBI Rx RB2 Tx at 9600 bps Soft UART Init PORTB 1 2 9600 0 The Software UART library implements time based activities so interrupts need to be disabled when using it 397 MikroElektronika mikoBasic PRO for PIC32 Soft UART Read Prototype sub function Soft UART Read dim byref error as byte as byte Description The function receives a byte via software UART This is a blocking function call waits for start bit Programmer can unblock it by calling Soft UART Break routine Parameters error Error flag Error code is returned through this variable Values 0 no error 1 stop bit error 255 user abort Soft UART Break called Byte received via UART Requires Software UART must be initialized before using this function See the Soft UART Init routine dim data as byte error as word wait until data is received do data Soft UART Read error loop until error 0 mec The Software UART library implements time based activities so interrupts need to be disabled when using it Soft UART Write Prototype sub procedure Soft UART Write dim udata as byte This routine sends one byte via the Software UART bus udata data to be sent
74. 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 dim s as string 5 s mik s 0 is char literal m YSTI zs char literal i s 2 is char literal k s 3 is zero s 4 is undefined s 5 is undefined 203 MikroElektronika mikoBasic PRO for PIC32 Be careful when handling strings in this way since overwriting the end of a string will cause an unpredictable behavior Array of string is declared in this manner typedef str as string 5 first declare str as a string of 5 elements dim buffer as str 5 now declare buffer as a array of str elements String Concatenating mikroBasic PRO for PIC32 allows you to concatenate strings by means of plus operator This kind of concatenation is applicable to string variables literals character variables literals For control characters use the non quoted hash sign and a numeral e g 13 for CR Here is an example dim msg as string 20 res txt as string 5 res channel as word main 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 Notes In current version plus operator for concatenating strings will accept at most two operands mikroBasic PRO
75. receive buffer start address 0x0000 receive buffer end address 0x19AD transmit buffer start address 0x19AF 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 0x0012 in full duplex mode 0x0C12 in half duplex mode Collision window is set to 63 in half duplex mode to accomodate some ENC28J60 revisions silicon bugs CLKOUT output is disabled to reduce EMI generation half duplex loopback disabled LED configuration default LEDA link status LEDB link activity 415 MikroElektronika mikoBasic PRO for PIC32 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 Requires Global variables SPI Ethernet CS Chip Select line SPI Ethernet CS Direction Direction of the Chip Select pin SPI Ethernet RST Resetline SPI Ethernet RST Direction Direction of the Reset pin must be defined before using this function The SPI module needs to be initialized S
76. the upper bytes are filled with zeroes if sign bit is 0 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 dim a as byte dim b as word a 12 70FF b b and a o ll ais sign extended upper byte is SFF b becomes 70F4 Bitwise Shift Operators The binary operators and 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 lt lt left most bits are discarded and new bits on the right are assigned zeroes Thus shifting unsigned operand to the left by n positions is equivalent to multiplying it by 2n if all discarded bits are zero This is also true for signed operands if all discarded bits are equal to the sign bit With shift right gt gt 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 2n 219 MikroElektronika mikoBasic PRO for PIC32 Boolean Operators Although mikroBasic PRO for PIC32 does not support boolean type you have Boolean operators at your disposal for building complex conditional expressions These operators conform to standard Bo
77. x Epoch Gts1 epoch 1148404020 what date is epoch 1234567890 x epoch 1234567890 Time epochToDate epoch ts2 ts2 ss 30 N de ts2 mn 31 ts2 hh 23 v ts2 md 13 ts2 wd 4 t ts2 mo 2 v ts2 yy 2009 how much seconds between this two dates Ae diff Time dateDiff tsl ts2 diff 86163870 end MikroElektronika mikroBasic PRO for PIC32 TimeStruct type definition structure TimeStruct dim ss as byte seconds dim mn as byte minutes dim hh as byte hours dim md as byte day in month from 1 to 31 dim wd as byte day in week monday 0 tuesday 1 sunday 6 dim mo as byte month number from 1 to 12 and not from 0 to 11 as with unix C time dim yy as word year Y2K compliant from 1892 to 2038 end structure Trigon Library The mikroBasic PRO for PIC32 provides a set of library functions for floating point math handling See also Predefined Globals and Constants for the list of predefined math constants Library Functions acos asin atan atan2 ceil COS cosh eval poly exp fabs floor frexp Idexp log log10 modf pow sin sinh sqrt tan tanh 607 MikroElektronika mikoBasic PRO for PIC32 acos Prototype sub function acos dim x as float as float Description Function returns the arc cosine of parameter x that is the value whose cosine is x The input
78. 020308 000000 2FFFFO B7A2A8 O7FFID 2000C0 781F80 O7FF4F ETX2 STX 8 BI002F 208610 781F80 200060 781F80 200010 781F80 07FF87 lt DLE gt t lt SPC gt lt B1006F 208690 781F80 781F80 200020 781F80 O7FF7F O0 amp D f SPC lt US gt B1006F 200CC8 273987 SAFFFE ED2010 3AFFFC 200010 o E lt FF gt lt SPC gt 9 781F80 07FF35 B1002F 781F80 200010 781F80 200010 U5 x5 BELL 781F80 07FF6D B1006F 781F80 200050 781F80 200020 U5 x m BELL o civ gt STATUS Idle E 131 MikroElektronika mikoBasic PRO for PIC32 Software Simulator Debugger Options Debugger Options A Function Toolbar Description Key Icon Executes the current program line then halts If the executed Step Into program line calls another routine the debugger steps into the F7 PO routine and halts after executing the first instruction within it Executes the current program line then halts If the executed program line calls another routine the debugger will not step into o pea ONET it The whole routine will be executed and the debugger halts at FB indi the first instruction following the call Executes all remaining program lines within the subroutine The debugger halts immediately upon exiting the subroutine this da ERIS option is provided with the PIC18 microcontroller family but not i id with the PIC16 family Executes the program until r
79. 10 CANSPIWrite ID 1st RxTx Data 1 Can Send Flags send incremented data back end if wend end Code for the second CANSPI node Copy Code To Clipboard program Can Spi 2nd const ID 1st as longint 12111 const ID 2nd as longint 3 dim Can Init Flags Can Send Flags Can Rcv Flags as word can flags Rx Data Len as word received data length in bytes RxTx Data as byte 8 can rx tx data buffer Msg Rcvd as byte reception flag Tx_ID Rx_ID as longword can rx and tx ID CANSPI module connections dim CanSpi CS as sbit at LATFO bit CanSpi CS Direction as sbit at TRISFO bit CanSpi Rst as sbit at LATF1 bit CanSpi Rst Direction as sbit at TRISF1 bit End CANSPI module connections main CHECON 0x32 ADIPCFG OxFFFF configure AN pins as digital I O PORTB 0 clear PORTB TRISB 0 set PORTB as output MikroElektronika 296 mikroBasic PRO for PIC32 Can Init Flags 0 Can Send Flags 0 Can Rcv Flags 0 clear flags 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 F
80. 10001 to UDP port 10001 427 MikroElektronika mikoBasic PRO for PIC32 SPI Ethernet dnsResolve Prototype sub function SPI Ethernet dnsResolve dim byref host as string dim tmax as byte as 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 dim remoteHostIpAddr as string 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 dnsResolve swisstime ethz ch 5 4 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 MikroElektron
81. 12 10 15 16 32 8Bimage Use the mikroBasic PRO for PIC32 integrated Glcd Bitmap Editor Tools gt Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd 469 MikroElektronika mikoBasic PRO for PIC32 Library Example The example demonstrates how to communicate to KS0108 Glcd via the SPI module using serial to parallel convertor MCP23S17 Copy Code To Clipboard program SPI Glcd Port Expander module connections dim SPExpanderRST as sbit at LATD8 bit SPExpanderCS as sbit at LATD9 bit SPExpanderRST Direction as sbit at TRISD8 bit SPExpanderCS Direction as sbit at TRISD9 bit End Port Expander module connections dim someText as char 20 counter as byte sub procedure Delay2S Delay ms 2000 end sub main CHECON 0x32 ADIPCFG OxFFFF Configure AN pins as digital If Port Expander Library uses SPI2 module Initialize SPI module used with PortExpander SPI2 Init Advanced SPI MASTER SPI 8 BIT 4 SPI SS DISABLI MIDDLE SPI CLK IDLE LOW SPI ACTIVE 2 IDLE Fl Fl SPI DATA SAMPL SPI Glcd Init 0 Initialize Glcd via SPI SPI Glecd Fill 0x00 Clear Glcd while TRUE SPI Glcd Image G8truck bmp Draw image Delay2s Delay2s SPI_Glcd_fill 0x00 Clear GLCD SPI Glcd PartialImage 0 0 68 30 128 64 truck_bmp Partial image Delay ms 500 SPI Glcd Partiallmage 24 16 68 30 128 64 8
82. 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 flags structure consisted of two bit fields Copy Code To Clipboard structure TEthj600PktFlags dim canCloseTCP as boolean flag which closes socket dim isBroadcast as boolean flag which denotes that the IP package has been received via subnet broadcast address end structure 0 there should not be a reply to the request Length of TCP reply data field otherwise Ethernet module has to be initialized See SPI Ethernet 24600 Init Example This function is internally called by the library and should not be called by the user s code The function source code is provided with appropriate example projects The code should be adjusted by the user to achieve desired reply MikroElektronika 448 mikroBasic PRO for PIC32 SPI Ethernet 24j600 UserUDP Prototype sub function SPI Ethernet 243600 UserUDP dim byref remoteHost as byte 4 dim remotePort as word dim destPort as word dim reqLength as word dim byref flags as TEthJ600PktFlags as word Description This is UDP module routine It is internally called
83. 3 entries For ARP cash structure refer to eth enc283 60LibDef mbas file in the compiler s Uses folder Parameters ip IP address to be resolved tmax time in seconds to wait for an reply MAC address behind the IP address the requested IP address was resolved 0 otherwise Ethernet module has to be initialized See SPI Ethernet Init dim IpAddr as IP address IpAddr 0 IpAddr 0 TpAddr 0 IpAddr 0 SPI Ethernet 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 sendUDP Prototype sub function SPI Ethernet sendUDP dim byref destIP as byte 4 dim sourcePort destPort as word dim pkt as byte dim pktLen as word as byte This is UDP module routine It sends an UDP packet on the network Parameters dest IP remote host IP address sourcePort local UDP source port number destPort destination UDP port number pkt packet to transmit pktLen length in bytes of packet to transmit 1 UDP packet was sent successfully 0 otherwise Ethernet module has to be initialized See SPI Ethernet Init IpAddr as byte 4 remote IP address 192 168 ii 1 Ethernet sendUDP IpAddr 10001 10001 Hello 5 send Hello message to the above IP address from UDP port
84. 420 mikroBasic PRO for PIC32 SPI Ethernet putConstString Prototype sub function SPI Ethernet putConstString const ptr as byte as word Description This is MAC module routine It stores whole const string excluding null termination into ENC28760 RAM starting from current ENC28760 write pointer EWRPT location Parameters ptr const string to be written into ENC28760 RAM Number of bytes written into ENC28760 RAM Requires Ethernet module has to be initialized See SPI Ethernet Init const buffer as string 16 buffer mikroElektronika SPI Ethernet putConstString buffer put a const string into ENC28J60 buffer SPI Ethernet getByte Prototype sub function SPI Ethernet getByte as byte Description This is MAC module routine It fetches a byte from address pointed to by current ENC28J60 read pointer ERDPT Retums Byte read from ENC28760 RAM Ethernet module has to be initialized See SPI Ethernet Init dim buffer as byte lt gt buffer SPI Ethernet getByte read a byte from ENC28J60 buffer SPI Ethernet getBytes Prototype sub procedure SPI Ethernet getBytes dim ptr as byte dim addr as word dim n as 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
85. 438 ms Finished successfully 01 Feb 2011 11 11 49 Unit C Program Files Mikroelektronika mikroBasic PRO for PIC Lib Delays mbas lib Delays mbas C Program Files Mikroelektronika mikroBasic PRO For PIC C Program Files Mikroelektronika mikroBasic PRO for PIC LCD mbas LCD mbas C Program Files Mikroelektronika mikroBasic PRO For PIC Used RX bytes 32 100 Free RX bytes 0 0 Static RAM bytes 48 Dynamic RAM bytes 32716 Used ROM bytes 3356 1 Free ROM bytes 52093 LCD mbp32 LCD mbp32 MikroElektronika mikroBasic PRO for PIC32 Quick Converter Quick Converter enables the user to easily transform numbers from one base to another Quick Converter Size Sign DECIMAL HEXADECIMAL BINARY CHARACTER p unsigned 77 0000004D 00000000 00000000 00000000 01001101 Its S32bis O Signed FLOAT DECIMAL 136 893 Format P OBin FLOAT 32 bit IEEE FLOAT 32 bit MICROCHIP RADIX 1 15 Hex 43 08 E4 9C 8608E49C 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
86. 64 110 T6963C WHITE T6963C image Prototype sub procedure T6963C image dim const pic as 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 mikroBasic PRO for PIC32 pointer to const and pointer to RAM equivalency Toshiba Glcd module needs to be initialized See the T6963C init routine Example reese mese mrimen CS Image dimension must match the display dimension Use the integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd 919 MikroElektronika mikoBasic PRO for PIC32 T6963C Partiallmage Prototype sub procedure T6963C Partiallmage dim x left y top width height picture width picture height as word const image as 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 mikroBasic PRO for PIC pointer to const and pointer to RAM equivalency Toshiba Glcd module needs to be initialized See T6963C init routine
87. ADCx_Init_ Advanced Before using the function be sure to configure the appropriate TRISx bits to designate pins as inputs The function sets the appropriate bit in the AD1PCFG registers to enable analog function of the chosen pin Refer to the appropriate Datasheet for channel to pin mapping dim adc value as word adc value ADCI Get Sample 10 read analog value from ADC module channel 10 ADCx Read dini is sub function ADC1 Read dim channel as word as word The function initializes enables ADC module and reads the specified analog channel input channel represents the channel from which the analog value is to be acquired Returns 10 bit unsigned value from the specified channel Requires The MCU with built in ADC module Before using the function be sure to configure the appropriate TRISx bits to designate pins as inputs dim adc value as word adc value ADC1 Read 10 read analog value from ADCmodule channel 10 The function sets the appropriate bit in the ADPCFG registers to enable analog function of the chosen pin Refer to the appropriate Datasheet for channel to pin mapping This is a standalone routine so there is no need for a previous initialization of ADC module 241 MikroElektronika mikoBasic PRO for PIC32 Library Example This code snippet reads analog value from the channel 1 and sends readings as a text over UART1 Copy Code To Clipboard program Temperature Se
88. Code To Clipboard const CANSPI FILTER B1 F1 as byte CANSPI FILTER Bl F2 as byte CANSPI FILTER B2 F1 as byte CANSPI FILTER B2 F2 as byte CANSPI FILTER B2 F3 as byte CANSPI FILTER B2 F4 as byte MikroElektronika 254 OT abs 1G IND po mikroBasic PRO for PIC32 Library Example The code is a simple demonstration of CANSPI protocol This node initiates the communication with the 2nd node by sending some data to its address The 2nd node responds by sending back the data incremented by 1 This 1st node then does the same and sends incremented data back to the 2nd node etc Code for the first CANSPI node Copy Code To Clipboard program Can Spi 1st 12113 3 const ID 1st as longint const ID 2nd as longint dim Can Init Flags Can Rx Data Len as word RxTx Data as byte 8 Msg Rcvd as byte Tx ID Rx ID as longword Send Flags CANSPI module connections dim CanSpi CS as sbit at CanSpi CS Direction as sbit at CanSpi Rst as sbit at CanSpi Rst Direction as sbit at End CANSPI module connections Can Rcv Flags as word can flags received data length in bytes can rx tx data buffer reception flag can rx and tx ID LATFO bit TRISFO bit LATFl bit TRISFl bit main CHECON 0x32 ADIPCFG OxFFFF configure AN pins as digital I O PORTB 0 clear PORTB TRISB 0 set PORTB as output C
89. Directive org specifies the starting address of a constant or a routine in ROM It is appended to the constant or a routine declaration To place a constant array in Flash memory write the following Constant array MONTHS will be placed starting from the address 0x9D000000 const MONTHS as byte 12 31 28 31 30 31 30 31 31 30 31 30 31 org 0x9D000000 If you want to place simple type constant into Flash memory instead of following declaration const SimpleConstant as byte 0xAA org 0x9D000000 use an array consisting of single element const SimpleConstant as byte 1 0xAA org 0x9D000000 235 MikroElektronika mikoBasic PRO for PIC32 In first case compiler will recognize your attempt but in order to save Flash space and boost performance it will automatically replace all instances of this constant in code with it s literal value In the second case your constant will be placed in Flash in the exact location specified To place a routine on a specific address in Flash memory you should write the following sub procedure proc dim par as word org 0x9D000000 Procedure will start at the address 0x9D000000 end sub org directive can be used with main routine too For example program Led Blinking main org 0x9D000000 main procedure starts at 0x9D000000 end Directive orgall Use the orgal1 directive to specify the address above which all routines and constants will be placed Example main orgall 0x9D000000
90. EEPROM from the View drop down menu The EEPROM Watch Window shows current content of the MCU s internal EEPROM memory There are two action buttons concerning the EEPROM Watch Window Read EEPROM Reads data from MCU s internal EEPROM memory and loads it up into the EEPROM window Write EEPROM Writes data from the EEPROM window into MCU s internal EEPROM memory EEPROM Watch Read EEPROM Write EEPROM STATUS Idle MikroElektronika 130 mikroBasic PRO for PIC32 Code Watch Window Note Code Watch Window is available only when mikrolCD is selected as a debugger To show the Code Watch Window select Debug Windows Code from the View drop down menu The Code Watch Window shows code hex format written into the MCU There is one action button concerning the Code Watch Window Reads code from the MCU and loads it up into the Code Window Code reading is resources consuming operation so the user should wait until the reading is over Also you can set an address scope in which hex code will be read CODE Watch Address Scope 000000 008000 A7S010 AS22CA 470060 A64010 ASO2CA A74010 A802CA 2088C0 DLE PS G DLE A60010 A802D6 A70010 A902D6 07FF96 470060 A63010 A962CA DLE STX DL A73010 AB62CA 470060 A62010 AS42CA A72010 AG42CA 470060 lt DLE gt 05 b G DLI A61010 AS22CA AT1010 AB22CA 470060 A60010 ASO2CA A70010
91. ERDPT location Parameters ptr buffer for storing bytes read from ENC28760 RAM addr ENC28 J60 RAM start address Valid values 0 8192 n number of bytes to be read Ethernet module has to be initialized See SPI Ethernet Init dim buffer as byte 16 SPI Ethernet getBytes buffer 0x100 16 read 16 bytes starting from address 0x100 471 MikroElektronika mikoBasic PRO for PIC32 SPI Ethernet UserTCP PI Prototype sub function SPI Ethernet UserTCP dim remoteHost as byte dim remotePort as word dim localPort as word dim reqLength as word dim byref flags as TEthPktFlags as word Description This is TCP module routine It is internally called by the library The user accesses to the TCP request by using some of the SPI Ethernet get routines The user puts data in the transmit buffer by using some of the SPI Ethernet put routines The function must return the length in bytes of the TCP reply or 0 if there is nothing to transmit If there is no need to reply to the TCP requests just define this function with return 0 as a single statement Parameters remoteHost client s IP address remotePort client s TCP port localPort port to which the request is sent regLength TCP request data field length flags structure consisted of two bit fields Copy Code To Clipboard structure TEthPktFlags dim canCloseTCP as boolean flag which closes socket d
92. Example reescwemeey OOOO moes noe OOo 913 MikroElektronika mikoBasic PRO for PIC32 T6963C fill deaa sub procedure T6963C fill dim v as byte dim start len as word Fills controller memory block with given byte Parameters v byte to be written start starting address of the memory block len length of the memory block in bytes ums Noi OOOO Example resescsiress 0x00FF 0x00 tes Nee OOS T6963C dot Prototype sub procedure T6963C dot dim x y as integer dim color as byte Draws a dot in the current graphic panel of Glcd at coordinates x y Parameters x dot position on x axis y dot position on y axis color color parameter Valid values T6963C BLACK and T6963C WHITE Rems Noting OOOO SS Example 16963C_dot x0 yO pcolor Notes Nam OOOO MikroElektronika 514 mikroBasic PRO for PIC32 T6963C write char Prototype sub procedure T6963C write char dim c x y mode as byte Writes a char in the current text panel of Glcd at coordinates x y Parameters c char to be written x char position on x axis y char position on y axis mode mode parameter Valid values T6968C ROM MODE OR T6963C ROM MODE XOR T6963C ROM MODE AND and T6963C ROM MODE TEXT Mode parameter explanation OR Mode In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics
93. GLCD D4 Direction as sbit xcd e Direction of the Data 4 pin sfr external dim GLCD D5 Direction as sbit UT Direction of the Data 5 pin sfr external as sbit dim GLCD D6 Direction sfr external Direction of the Data 6 pin dim GLCD D7 Direction as sbit i Direction i Direction of the Data 7 pin i sfr external dim GLCD CS1 Direction as sbit e A dim GLCD CS1 Direction d E Direction of the Chip Select 1 pin m P sfr external B4 bit dim GLCD CS2 Direction as sbit i A dim GLCD CS2 Direction sre ae Direction of the Chip Select 2 pin sfr external B5 bat dim GLCD RS Direction as sbit Direction of the Register select di LCD RS Direction sfr external pin FO bit dim GLCD EN Direction as sbit i i LCD RW Direction dad Direction of the Read Write pin x sfr external Fl bit dim GLCD EN Direction as sbit i GLCD EN Direction Direction of the Enable pin za rode sfr external F4 bit dim GLCD RST Direction as sbit A i LCD RST Direction as sbit M ES Direction of the Reset pin ee noe sfr external BO bit 297 MikroElektronika mikoBasic PRO for PIC32 Library Routines Basic routines Glcd Init Glcd Set Side Glcd Set X Gled Set Page Glcd Read Data Gled Write Data Advanced routines Glcd Fill Glcd Dot Gled Line Glcd V Line Gled H Line Glcd Rectangle Gled Rectangle Round Edges
94. LCD RST Direction Direction of the Reset signal pin See eho Pe must be defined before using this function Glcd module connections LCD D7 as sbit at RD3 bit LCD D6 as sbit at RD2 bit LCD DS as sbit at RDI bit LCD D4 as sbit at RDO bit LCD D3 as sbit at RB3 bit LCD D2 as sbit at RB2 bit LCD DI as sbit at RBl bit LCD DO as sbit at RBO bit LCD D7 Direction as sbit at TRISD3 bit LCD D6 Direction as sbit at TRISD2 bit LCD D5 Direction as sbit at TRISD1 bit LCD D4 Direction as sbit at TRISDO bit LCD D3 Direction as sbit at TRISB3 bit LCD D2 Direction as sbit at TRISB2 bit LCD D1 Direction as sbit at TRISB1 bit LCD DO Direction as sbit at TRISBO bit G G G G G G G G G G G G G G G QU UUUUUUUUUUUUU lU LCD CS1 as sbit at LATB4 bit D CS2 as sbit at LATB5 bit D RS as sbit at LATFO bit D RW as sbit at LATF1 bit LCD EN as sbit at LATF4 bit LCD RST as sbit at LATF5 bit Q2QQ2Q9eQ LCD_CS1 Direction as sbit at TRISB4 bit LCD_CS2 Direction as sbit at TRISB5 bit LCD RS Direction as sbit at TRISFO bit LCD RW Direction as sbit at TRISF1 bit LCD EN Direction as sbit at TRISF4 bit LCD RST Direction as sbit at TRISF5 bit End Glcd module connections AAAAAA 299 MikroElektronika mikoBasic PRO for PIC32 Glcd Set Side Prototype sub procedure Glcd Set Side dim x pos as byte Selects Glcd side Refer to the Glcd datasheet for detailed explanation Paramet
95. LCD display f rn cursor off Prepare and output static text on LCD Lcd Init Y Lcd Cmd LCD CLEAR 3 Lcd Cmd LCD CURSOR OFF l Led Qut 1 l1 Date 3 Lcd Che 148 2 Lcd Chr 1 11 Lcd Out 2 1 Time Lod 6Chr 2 9 2 Led Ohr 2 11 7 Lcd Out 1 12 201 end sub lt Main procedure main Delay ms 1000 Init Main Y while TRUE Read Time Transform Time Display Time wend 7 end Perform initialization Endless loop Read time from RTC PCF8583 Format date and time Prepare and display on LCD MikroElektronika 392 mikroBasic PRO for PIC32 Software SPI Library The mikroBasic PRO for PIC32 provides routines for implementing Software SPI communication These routines are hardware independent and can be used with any MCU The Software SPI Library provides easy communication with other devices via SPI A D converters D A converters MAX7219 LTC1290 etc Library configuration SPI to Master mode Clock value 20 kHz Data sampled at the middle of interval Clock idle state low Data sampled at the middle of interval Data transmitted at low to high edge The library configures SPI to the master mode clock 20kHz data sampled at the middle of interval clock idle state low and data transmitted at low to high edge Important The Software SPI library implements time based activities so interrupts need to be disabled when using it External dependencies of Softwa
96. Menu Options 46 Build 47 Build Menu Options 47 Run 48 Run Menu Options 48 Tools 49 Tools Menu Options 49 Help 50 Help Menu Options 50 MikroElektronika mikroBasic PRO for PIC32 mikroBasic PRO for PIC32 IDE 51 IDE Overview 51 Code Editor 52 Editor Settings 52 Auto Save 53 Highlighter 53 Spelling 53 Comment Style 53 Code Folding 53 Code Assistant 54 Parameter Assistant 54 Bookmarks 54 Go to Line 54 Column Select Mode 55 Editor Colors 55 Auto Correct 56 Auto Complete Code Templates 57 Code Explorer 59 Routine List 60 Project Manager 60 Project Settings 62 Library Manager 63 Managing libraries using Package Manager 64 Routine List 65 Statistics 65 Memory Usage Windows 65 Variables 66 Used RAM Locations 66 SFR Locations 67 ROM Memory Usage 67 ROM Memory Constants 68 Functions 68 Functions Sorted By Name Chart 69 Functions Sorted By Size Chart 69 Functions Sorted By Addresses 70 Function Tree 70 Memory Summary 71 Messages Window 72 Quick Converter 73 Macro Editor 73 Image Preview 74 Toolbars 76 File Toolbar 77 Edit Toolbar 77 MikroElektronika mikoBasic PRO for PIC32 Advanced Edit Toolbar Find Replace Toolbar Project Toolbar Build Toolbar Debug Toolbar Styles Toolbar Tools Toolbar View Toolbar Layout Toolbar Help Toolbar Customizing IDE Layout Docking Windows Saving Layout Auto Hide Options Code editor Tools Output settings Integrated Tools Active Comments Editor ASC
97. PI T6963C cireL PI T6963C circl 000000000000 ZNnNNnNNNNNNNNNMN ENDIF Fl Delay _ms 1000 Delay ms 1000 IFDEF PARTIAL IMAGE SPI T6963C sprite 76 Delay ms 1000 ER Eh Eh Eh EAER Eh hob Ei ER Fs perpe poa pr es ee pg esi esi pes peser pd pecie peti pese peer pe p SPI T6963C image mikro SPI T6963C displayGrPanel 1 PI T6963C circle 120 64 PI T6963C circle 120 64 PI T6963C circle 120 64 PI T6963C circle PI T6963C circle 120 64 PI T6963C circle 120 64 PI T6963C circle 120 64 120 64 120 120 199 120 120 120 120 120 120 120 150 120 4 einstein bmp SPI T6963C setGrPanel 1 DE O SPI T6963C grFill 0 partial image Delay ms 1000 SPI T6963C graphics 0 ENDIF NM WM PI T6963C image mikro PI T6963C graphics 1 PI T6963C displayGrPanel 0 SPI T6963C Partiallmage 0 10 30 50 70 90 110 130 64 64 64 64 64 64 64 64 64 64 64 64 OS OA A UNDO SO AS SS CN 0 SPI 1 SPI 3 SPI 1 SPI 4 SPI 1 SPI 1 SPI 3 SPI 1 SPI 3 60 55 50 45 40 35 30 25 20 15 10 ANNNNNNNNNMN PI j PI j PI 1 PI 1 PI j PI j PI 1 PI j PI j PI 1 PI j 6963C_ WHITE 6963C WHITE C6963C WHITI 6963C WHITI 6963C WHITI 6963C WHIT C6963C WHIT 6963C WHITI 6963C WHITI r6963C w pd Ed Hd Ed Ed DH C
98. PIC32 Cf Read Init Anni sub procedure Cf Read Init dim address as longword dim sectcnt as byte Initializes CF card for reading Parameters address the first sector to be prepared for reading operation sector count number of sectors to be prepared for reading operation The corresponding MCU ports must be appropriately initialized for CF card See Cf Init initialize compact flash for reading from sector 590 Cf Read Init 590 1 Nos Nm Cf Read Byte Description Reads one byte from m Compact Flash sector buffer location currently pointed to by internal read pointers These pointers will be autoicremented upon reading Returns Returns a byte read from Compact Flash sector buffer Requires The corresponding MCU ports must be appropriately initialized for CF card See Cf Init CF card must be initialized for reading operation See Cf Read Init Read a byte from compact flash dim data as byte data Cf Read Byt Notes Higher byte of the unsigned return value is cleared Cf Write Init Prototype sub procedure Cf Write Init dim address as longword dim sectcnt as 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 sec
99. PIC32 S1D13700 Init Prototype sub procedure S1D13700 Init dim width as word dim height as word Description Initializes S1D13700 Graphic Lcd controller Parameters width width of the Glcd panel height height of the Glcd panel Requires Global variables 1D13700 Data Port Data Bus Port 51D13700 WR Write signal pin 51D13700 RD Read signal pin 51D13700 A0 Command Data signal pin 51D13700 RES Reset signal pin 51D13700 CS Chip Select signal pin 1D13700 Data Port Direction Data Bus Port Direction 51D13700 WR Direction Direction of Write signal pin 81D13700 RD Direction Direction of Read signal pin 51D13700 A0 Direction Direction of Command Data signal pin S 1D13700 RES Direction Direction of Reset signal pin 51D13700 CS Direction Direction of Chip Select signal pin must be defined before using this function S1D13700 module connections dim S1D13700 Data Port as byte at PORTD dim S1D13700 WR as sbit at LATC2 bit dim S1D13700 RD as sbit at LATCI bit dim S1D13700 AO as sbit at LATCO bit dim S1D13700 RES as sbit at LATC4 bit dim 1D13700 CS as sbit at LATC5 bit dim S1D13700 Data Port Direction as byte at TRISD dim S1D13700 WR Direction as sbit at TRISC2 bit dim S1D13700 RD Direction as sbit at TRISC1 bit dim S1D13700 AO Direction as sbit at TRISCO bit dim S1D13700 RES Direction as sbit at TRISC4 bit dim S1D13700 CS Direction as sbit at TRISC5 bit
100. Parameters input byte to be converted output destination string dim t as byte txt as string 2 t 22 ByteToHex t txt Y tee ss WS MikroElektronika 588 mikroBasic PRO for PIC32 ShortToHex Prototype sub Bom ShortToHex dim input as short dim byref output string 2 pere 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 output destination string dim t as short txt as string 2 100 ShortToHex t txt n ESE gist UCH WordToHex Prototype sub procedure WordToHex dim input as word dim byref output as string 4 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 word to be converted output destination string dim t as word txt as string 4 1111 WordToHex t txt t pxt xo 0457 589 MikroElektronika mikoBasic PRO for PIC32 IntToHex Prototype sub procedure IntToHex dim input as integer dim byref output as string 4 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 an
101. 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 321 MikroElektronika mikoBasic PRO for PIC32 Man Receive Prototype sub function Man Receive dim byref error as word as 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 Retums A byte read from the incoming signal To use this function the user must prepare the MCU for receiving See Man Receive Init routines dim data error as word error 0 data_ 0 data_ Man Receive error if error 0 then error handling end if Man Send Init ems Noting Requires Global variables MANTXPIN Transmit line MANTXPIN Direction Direction of the transmit pin must be defined before using this function Initialize Transmitter dim MANTXPIN as sbit at LATF1 bit dim MANTXPIN Direction as sbit at TRISF1 bit Man Send Init MikroElektronika 328 mikroBasic PRO for PIC32 Man Send Prototype sub procedure Man Send dim data as byte Description Sends one byte Parameters tr data data to be sent Nothing Requires To use this function the user must prepare the MCU for sending See Man Send Init routine dim msg as byte Man Send msg Baud rate used is 500 bps Man
102. Rems Nam CS TP TFT Init has to be called before using this routine TP TFT Set ADC Threshold 900 Set touch panel ADC threshold MikroElektronika 556 mikroBasic PRO for PIC32 TP TFT Press Detect Prototype sub function TP TFT Press Detect as byte Detects if the touch panel has been pressed 1 if touch panel is pressed 0 otherwise Requires Global variables DriveX Left DriveX Left pin DriveX Rignt 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 as sbit at LATB13 bit Drivex Right as sbit at LATB11 bit DriveY Up as sbit at LATB12 bit DriveY Down as sbit at LATB10 bit DriveX Left Direction as sbit at TRISB13 bit Drivex Right Direction as sbit at TRISB11 bit DriveY Up Direction as sbit at TRISB12 bit DriveY Down Direction as sbit at TRISB10 bit End Touch Panel module connections Press Detect lt gt 0 then 997 MikroElektronika mikoBasic PRO for PIC32 TP TFT Get Coordinates Prototype sub function TP TFT Get Coordinates dim byref x coordinate as word dim byref y coordinate as word as byte Get touch panel coordinates and store them
103. 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 Init 329 MikroElektronika mikoBasic PRO for PIC32 Man Break Prototype sub 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 dim datal error counter as byte sub procedure TimerlInt org IVT ADDR TIINTERRUPT counter 0 if counter gt 20 then Man Break counter 0 reset counter else Inc counter increment counter end if Tite Bae Clear Timerl overflow interrupt flag end sub main if Man Receive Init end if try Man Receive with blocking prevention mechanism IPCO IPCO or 0x1000 Interrupt priority level 1 TIIE bit 1 Enable Timerl interrupts T1CON 0x8030 Timerl ON internal clock FCY prescaler 1 256 datal Man Receive Gerror Ltd j 0 Disable Timerl interrupts end pe Interrupts should be disabled before using Manchester routines again see note at the top of this page MikroElektronika 330 mikroBasic PRO for PIC32 Library Example The following code is cod
104. T6963C_setGrPanel 1 Delay ms 1000 T6963C graphics 0 ENDIF T6963C image mikrol T6963C graphics 1 T6963C displayGrPanel 0 If RB8 is pressed RB8 bit 0 then T6963C graphics 1 T6963C text 0 Delay ms 300 64 64 64 64 64 64 64 64 64 64 64 64 0 60 55 50 45 40 39 30 295 20 15 19 a 4 q a a L6963C WHIT C6963C BLAC C6963C WHIT C 6963C BLACK C6963C WHITE C 6963C BLACK C6963C WHITI C 6963C BLACK C 6963C WHITE C 6963C BLACK DE AW pH H 1 3 mi C6963C WHITI 5 T6963C BLACK T6963C sprite 76 4 einstein Delay ms 1000 64 88 119 E 240x128 bmp 64 240 128 E 240x128 bmp V Des Sel mikrol w a sprite ect other graphic panel E 240x128 bmp Display partial Endless loop toggle the display between graphic panel 0 and graphic 1 If RB9 is pressed display only graphic panel else if RB9 bit 0 the Inc panel panel panel and 1 n T6963C displayGrPanel panel Delay ms 300 MikroElektronika 928 mikroBasic PRO for PIC32 If RB10 is pressed display only text panel else if RB10 bit 0 then T6963C graphics 0 T6963C text 1 Delay ms 300 If RB11 is pressed display text and graphic panels else if RB11 bit lt gt 0 then T6963C_graphics 1 T6963C text 1 Delay ms 300
105. Templates and more Use included mikroBasic PRO for PIC32 libraries to dramatically speed up the development data acquisition memory displays conversions communication etc Monitor your program structure variables and functions in the Code Explorer Generate commented human readable assembly and standard HEX compatible with all programmers Use the integrated mikroICD In Circuit Debugger Real Time debugging tool to monitor program execution on the hardware level Inspect program flow and debug executable logic with the integrated Software Simulator Use Single Static Assignment optimization to shrink your code to even smaller size Get detailed reports and graphs RAM and ROM map code statistics assembly listing calling tree and more Active Comments enable you to make your comments alive and interactive mikroBasic PRO for PIC32 provides plenty of examples to expand develop and use as building bricks in your projects Copy them entirely if you deem fit that s why we included them with the compiler Where to Start In case that you re a beginner in programming the PIC32 microcontrollers read carefully the PIC32 Specifics chapter It might give you some useful information on the PIC32 constraints code portability and good programming practices If you are experienced in Basic programming you will probably want to consult the mikroBasic PRO for PIC32 Specifics first For language issues you can a
106. UARTx Read PIOS sub function UARTx Read as word The function receives a byte via UART Use the UARTx Data Readgy 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 dim receive as word read data if ready if UART1 Data Ready receive UART1 Read end if UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 565 MikroElektronika mikoBasic PRO for PIC32 UARTx Read Text Prototype sub procedure UARTx Read Text dim byref output delimiter as string dim Attempts as 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
107. Valid values 0 63 round radius radius of the rounded edge color color parameter Valid values 0 2 The parameter color determines the color of the rectangle border 0 white 1 black and 2 inverts each dot Nothing Requires Glcd needs to be initialized see Glcd Init routine Draws a filled rounded edge rectangle between dots 5 5 and 40 40 with the radius of 12 Glcd Rectangle Round Edges Fill 5 5 Glcd Box Prototype sub procedure Glcd Box dim x upper left y upper left x bottom right bottom right color as 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 Nothing Glcd needs to be initialized see Glcd Init routine Draw a box between dots 5 15 and 20 40 eled Box 5 15 20 40 1 305 MikroElektronika mikoBasic PRO for PIC32 Glcd Circle Prototype sub procedure Glcd Circle dim x center y center radius as integer dim color as byte Draws a circle on Glcd 1 Parameters x center x coordinate of
108. 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 decompile or disassemble it except and only to the extent that such activity is expressly permitted by applicable law notwithstanding this limitation If you have purchased an upgrade version of Software it constitutes a single product with the mikroElektronika Associates software that you upgraded You may use the upgrade version of Software only in accordance with the License Agreement LIMITED WARRANTY Respectfully excepting the Redistributables which are provided as is without warranty of any kind mikroElektronika Associates warrants that Software once updated and properly used will perform substantially in accordance with the accompanying documentation and Software media will be free from defects in materials and workmanship for a period of ninety 90 day
109. as 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 the second comparison parameter Returns Time difference in seconds as a signed long dim tsl ts2 as TimeStruct diff as longint how many seconds between these two dates contained in tsl and ts2 buffers diff Time dateDiff tsl1 ts2 605 MikroElektronika mikoBasic PRO for PIC32 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 vk structure dim ss dim mn dim hh dim md dim wd dim mo C time dim yy TimeStruct as as as as as as as byte byte byte byte byte byte word end structure dim Esl main tsl ss tsl mn tsl hh tsl md tsl mo ESI yy x ts2 epoch diff as longint 2006 seconds minutes hours day in month from 1 to 31 day in week monday 0 tuesday 1 sunday 6 month number from 1 to 12 and not from 0 to 11 as with unix year Y2K compliant from 1892 to 2038 as TimeStruct what is the epoch of the date in ts Yk poch Time dateTol
110. as sbit at TRISD8 bit SPExpanderCS Direction as sbit at TRISD9 bit End Port Expander module connections dim panel as byte current panel i as word general purpose register curs as byte Cursor visibility Cposx cposy as word acursor x y position txt txtl as string 29 501 MikroElektronika mikoBasic PRO for PIC32 txt2 as string 21 main DEFINE COMPLETE EXAMPLE DEFINE LINE DEMO Uncomment to demonstrate line drawing routines DEFINE FILL DEMO Uncomment to demonstrate fill routines DEFINE PARTIAL IMAGE DEMO Uncomment to demonstrate partial image routine txtl EINSTEIN WOULD HAVE LIKED mE GLCD LIBRARY DEMO WELCOME Partial image demo e x e ll v CHECON 0x32 ADIPCFG OxFFFF 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 TRISB13 bit 1 Set RB13 as input panel 0 i 0 curs 0 cposx 0 cposy 0 If Port Expander Library uses SPI1 module Initialize SPI module used with PortExpander SPI2 Init Advanced SPI MASTER SPI 8 BIT 4 SPI SS DISABLE initialize AN pins as digital SPI DATA SAMPLE MIDDLE SPI CLK IDLE LOW SPI ACTIVE 2 IDLE If Port Expander Library uses SPI2 module SPI2 Init Advanced SPI MASTER SPI 8 BIT SPI SS DISABLE SPI DA
111. at RFO bit MANRXPIN Direction as sbit at MANTXPIN as sbit at LATF1 bit RISFO bit MANTXPIN Direction as sbit at 1 URISFl bit End Manchester module connections dim index character as byte sl as char 17 main sl mikroElektronika CHECON 0x32 ADIPCFG OxFFFF J Man Send Init while TRUI Man Send 0xOB Delay ms 100 Fl Configure AN pins as digital I O Initialize transmitter Endless loop Send start byte Wait for a while MikroElektronika 332 mikroBasic PRO for PIC32 character s1 0 index 0 while character lt gt 0 Man_Send character Delay ms 90 Inc index character wend Man Send 0x0E Delay ms 1000 wend end sl index Connection Example Antenna vcc Take first char from string Initialize index variable String ends with zero Send character Wait for a while Increment index variable Take next char from string Send end byte Transmitter RF module OSCILLATOR JU PIC32MX460F512L E Simple Transmitter connection Antenna Recevier RF module vec VCC3 vcc A RR4 our ID GND 5 vcc3 Simple Receiver connection MikroElektronika mikoBasic PRO for PIC32 Memory Manager Library This library provides routines for manipulating dynamic memory allocation Dynamic memory allocation also known as heap based memory allocation is the allocation of memory storag
112. be built for SSA SPI Ethernet getlpAddress Prototype sub function SPI Ethernet getIpAddress as word Description This routine should be used when DHCP server is present on the network to fetch assigned IP Mm e Parameters Non 0 Retums Pointer to the global variable holding IP address Ethernet module has to be initialized See SPI Ethernet Init di ipAddr as byte 4 user IP address buffer memcpy ipAddr SPI Ethernet getIpAddress fetch IP address User should always copy the IP address from the RAM ET returned by this routine into it s own IP address buffer These locations should not be altered by the user in any case Ethernet_getGwlpAddress Prototype Prototype sub function SPI Ethernet sub function SPI_Ethernet_getGwIpAddress as word sub function SPI Ethernet getGwIpAddress as word word This routine should be used when DHCP server is present on the network to fetch assigned gateway IP address Retums Pointer to the global variable holding gateway IP address Ethernet module has to be initialized See SPI Ethernet Init di gwlpAddr as byte 4 user gateway IP address buffer sexa Adde SPI Ethernet getGwIpAddress 4 fetch gateway IP address User should always copy the IP address from the RAM location returned by this routine into it s own DNS IP address buffer These locations should not be altered by the user in any case MikroElektronika mikroBa
113. 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 591 MikroElektronika mikoBasic PRO for PIC32 StrToWord Prototype sub function StrToWord dim byref input as string 5 as word Converts a string to word input string to be converted Returns Word variable 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 dim ww as word main Bcd2Dec pem fosen 000000 dim a b as byte a 22 Bcd2Dec a b equals 34 MikroElektronika 592 mikoBasic PRO for PIC32 Dec2Bcd Rem emere dim a b as byte a 22 Dec2Bcd a b equals 34 Bcd2Dec16 Prototype sub function Bcd2Decl6 dim bcdnum as word as word Description Converts 16 bit BCD numeral to its decimal equivalent bcdnum 16 bit BCD numeral to be converted Returns Converted decimal value dim a b as word 0x1234 a equals 4660 Bcd2Dec16 a b equals 1234 Dec2Bcd16 Prototype sub function Dec2Bcdl6 dim decnum as word as word eums GmeeiBobwe T dim a b as word a 2345 Dec2Bcdl16 a b equals 9029 MikroElektronika 593 mikoBasic PRO for PIC32 Setjmp Library The Setjmp library contains functions and types definitions for bypassing the
114. bit fields Copy Code To Clipboard structure TEthPktFlags dim canCloseTCP as boolean flag which closes socket not relevant to UDP dim isBroadcast as boolean flag which denotes that the IP package has been received via subnet broadcast address end structure 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 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 423 MikroElektronika mikoBasic PRO for PIC32 SPI Ethernet setUserHandlers Prototype sub procedure SPI Ethernet setUserHandlers dim TCPHandler as TSPI Ethernet UserTCP dim UDPHandler as TSPI Ethernet UserUDP Description Sets pointers to User TCP and UDP handler function implementations which are automatically called by SPI Ethernet library Parameters TC PHandler TCP request handler UDPHandler UDP request handler SPI Ethernet UserTCP and SPI Ethernet UserUDP have to be previously defined PI SPI Ethernet setUserHandlers 8SPI Ethernet UserTCP SPI Ethernet UserUDP Since all libraries are built for SSA SSA restrictions regarding function pointers dictate that modules that use SPI Ethernet setUserHandlers must also
115. 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 Y Scy MikroElektronika 434 mikroBasic PRO for PIC32 if you don t need to reply to UDP requests just define this function with a return 0 as single statement sub function Spi Ethernet UserUDP dim byref remoteHost as byte 4 dim remotePort destPort reqLength as word dim byref flags as TEthPktFlags as word dim txt as string 5 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 txt second dyna 4 txt 0 dyna 5 txt 1 dyna 6 txt 2 dyna 7 byteToStr remoteHost 2 txt second dyna 8 txt 0 dyna 9 txt 1 dyna 10 txt 2 dyna 11 byteToStr remoteHost 3 txt second dyna 12 txt 0 dyna 13 txt 1 dyna 14 txt 2 dyna 15 add separator then remote host port number WordToStr remotePort txt dyna 16 txt 0 dyna 17 txt 1 dyna 18 txt 2 dyna 19 txt 3 dyna 20 txt 4 dyna 21 WordToStr destPort txt dyna 22 txt 0 dyna 23 txt 1 dyna 24 txt 2 dyna 25 txt 3 dyna 26 txt 4 dyna 27 dyna 28 0 the total length of the req
116. case res nl n2 case res nl n2 case res nl n2 case else res 0 ent cnt 1 end select 225 MikroElektronika mikoBasic PRO for PIC32 Also you can group values together for a match Simply separate the items by commas select case reg case 0 opmode 0 case 1 2 3 4 opmode 1 case 5 6 7 opmode 2 end select Nested switch Note that the select case statements can be nested values are then assigned to the innermost enclosing select case statement Iteration Statements Loops Iteration statements let you loop a set of statements There are three forms of iteration statements in mikroBasic PRO for PIC32 for while 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 continue 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 tor statement is for counter initial value to final value step step value statement list next counter counter is a variable which increments with each iteration of the loop Before the first iteration counter is set to initial value and will increment 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
117. case sensitive You can use 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 begun Directives 2ZDEFINE and ZUNDEFINE 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 DEFINE extended format Use UNDEFINE to undefine clear previously defined flag Directives IFDEF IFNDEF ELSE and ENDIF Conditional compilation is carried out by the IFDEF and 1FNDEF 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 Directives 4 1FDbEF and 1FNDEF are terminated with the ENDIF directive and can have an optional 4 ELSE clause IFDEF flag THEN block of code ELSE alternate block of code ENDIF First 4 1FDEF checks if flag is defined by means of DEFINE If so only block of code will be compiled Otherwise alternate block of code in ELSE if any will be compiled NDIF ends the conditional sequence The result of the preceding sce
118. char 30 buffer for dynamic response httpCounter as word counter of HTTP requests txt as string 11 Y ko oe o oe oe oe oe oe oe o o x Xx x6 KKK x KKK x KKK B Bn n Bx Bx Bx BB gx xL ttt S x amp SxAA amp user defined functions T ox ae Y 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 sub function Spi Ethernet UserTCP dim byref remoteHost as byte 4 dim remotePort localPort reqLength as word dim byref flags as TEthPktFlags as word dim i as word my reply length bitMask as byte for bit mask EXE as string 11 result 0 MikroElektronika 432 mikroBasic PRO for PIC32 should we close tcp socket after response is sent library closes tcp socket by default if canClose flag is not reset here canClose 0 0 do not close socket otherwise close socket if localPort lt gt 80 then I listen only to web request on port 80 result 0 exit end if get 10 first bytes only of the request the rest does not matter here for i 0 to 10 getRequest i Spi Ethernet getByte next i getRequest
119. comfortable work with RS485 system using Master Slave architecture Master and Slave devices interchange packets of information Each of these packets contains synchronization bytes CRC byte address byte and the data Each Slave has unique address and receives only packets addressed to it The Slave can never initiate communication It is the user s responsibility to ensure that only one device transmits via 485 bus at a time The RS 485 routines require the UART module Pins of UART need to be attached to RS 485 interface transceiver such as LTC485 or similar see schematic at the bottom of this page Library constants START byte value 150 STOP byte value 169 Address 50 is the broadcast address for all Slaves packets containing address 50 will be received by all Slaves except the Slaves with addresses 150 and 169 Important The library uses the UART module for communication The user must initialize the appropriate UART module before using the RS 485 Library For MCUs with multiple UART modules it is possible to initialize them and then switch by using the UART Set Active routine Library Dependency Tree Rs485 uaRT External dependencies of RS 485 Library The following variable must be defined bescHatioiE in all projects using RS 485 Library P dim RS485 rxtx pin as sbit sfr Control RS 485 Transmit Receive dim RS485 rxtx pin as sbit at RF2 external operation mode bit dim RS485 rxtx
120. const PI as byte 3 14159 MikroElektronika 211 mikroBasic PRO for PIC32 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 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 mikroBasic PRO for PIC32 Arithmetic Operators Bitwise Operators Boolean Operators Relational Operators Operators Precedence and Associativity There are 4 precedence categories in mikroBasic PRO for PIC32 Operators in the same category have equal precedence with each other Each category has an associativity rule left to right gt or right to left In the absence of parentheses these rules resolve the grouping of expressions with operators of equal precedence 215 MikroElektronika mikoBasic PRO for PIC32 Arithmetic Operators Arithmetic operators are used to perform mathematical computations They have numerical operands and return numerical results Since the char operators are technical
121. cposy Noes Nowe OSS T6963C_displayGrPanel Rum Noting OOOO RE TU CC T6963C displayGrPanel 1 T6963C displayTxtPanel Remum NM 0 Toshiba Glcd module needs to be initialized See the T6963C init routine display text panel 1 T6963C displayTxtPanel 1 521 MikroElektronika mikoBasic PRO for PIC32 T6963C setGrPanel Prototype sub procedure 7T6963C setGrPanel dim n as word Description Compute start address for selected graphic panel and set appropriate internal pointers All subsequent graphic operations will be preformed at this graphic panel n graphic panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See the T6963C init routine set graphic panel 1 as current graphic panel T6963C setGrPanel 1 T6963C setTxtPanel Description Compute start address for selected text panel and set appropriate internal pointers All subsequent text operations will be preformed at this text panel n text panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See the T6963C init routine set text panel 1 as current text panel T6963C setTxtPanel 1 oes Noe OOOO T6963C_panel Fill Rumes Noting OO Toshiba Glcd module needs to be initialized See the T6963C init routine clear current panel T6963C panelFill 0 MikroElektronika 522 mikroBasic PRO for PIC32 T6963C grFill Rems NM OSS Toshiba Glcd module need
122. ctrlmd as sbit at LATE5 bit MD signal dim T6963C ctrlce Direction as sbit at TRISE3 bit CE signal direction dim T6963C ctrlfs Direction as sbit at TRISE6 bit FS signal direction dim T6963C ctrlmd Direction as sbit at TRISE5 bit MD signal direction End T6963C module connections dim panel as byte current panel i as word general purpose register curs as byte cursor visibility Cposx 925 MikroElektronika mikoBasic PRO for PIC32 cposy as word cursor x y position txtcols as byte number of text coloms txt txtl txt2 as string 29 main DEFINE LINE DEMO Uncomment to demonstrate line drawing routines DEFINE FILL DEMO Uncomment to demonstrate fill routines DEFINE PARTIAL IMAGE DEMO Uncomment to demonstrate partial image routine txtl EINSTEIN WOULD HAVE LIKED mE txt GLCD LIBRARY DEMO WELCOME txt2 Partial image demo CHECON 0x32 ADIPCFG OxFFFF initialize AN pins as digital TRISB8 bit 1 Set RB8 as input TRISB9 bit 1 Set RB9 as input Set RB10 as input Set RB11 as input Set RB12 as input Set RB12 as input TRISB10 bit TRISB11 bit TRISB12 bit TRISB13 bit Buauomo T6963C ctrlce Direction 0 T6963C ctrlce 0 Enable T6963C T6963C ctrlfs Direction 0 T6963C ctrlfs 0 Font Select 8x8 T6963C ctrlmd Direction 0 T6963C ctrlmd 0 Column number select panel
123. dim SPExpanderRST as sbit at LATFO bit SPExpanderCS as sbit at LATF1 bit SPExpanderRST Direction as sbit at TRISFO bit SPExpanderCS Direction as sbit at TRISF1 bit End Port Expander module connections If Port Expander Library uses SPI1 module SPIT Tnit Initialize SPI module used with PortExpander SPI Gled Inst 0 MikroElektronika 458 mikroBasic PRO for PIC32 SPI Glcd Set Side Prototype sub procedure SPI Glcd Set Side dim x pos as 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 Reums 2235 page number vaid vawe o7 SSCS Example ser orca see eae OOOO OOOO Notes For side x axis and page layout explanation see schematic atthe bottom ofthis pags SPI Glcd Set X Prototype sub procedure SPI Glcd Set X dim x pos as byte Sets x axis position to x pos dots from the left border of Glcd within the selected side x pos position o
124. div T6963C CHARACTER HEIGHT then Delay ms 100 wend end MikroElektronika 530 mikroBasic PRO for PIC32 HW Connection 1 amp Toshiba T6963C Graphic LCD 240x128 V aa 8883888838888 4 Contrast Adjustment SPI T6963C Glcd HW connection 531 MikroElektronika mikoBasic PRO for PIC32 TFT Library Thin film transistor liquid crystal display TFT LCD is a variant of liquid crystal display LCD which uses thin film transistor TFT technology to improve image quality e g addressability contrast TFT LCD is one type of active matrix LCD though all LCD screens are based on TFT active matrix addressing TFT LCDs are used in television sets computer monitors mobile phones handheld video game systems personal digital assistants navigation systems projectors etc The mikroBasic PRO for PIC32 provides a library for working with HX8347 D 320x240 TFT Lcd controller The HX8347 D is designed to provide a single chip solution that combines a gate driver a source driver power supply circuit for 262 144 colors to drive a TFT panel with 320x240 dots at maximum The HX8347 D is suitable for any small portable battery driven and long term driving products such as small PDAs digital cellular phones and bi directional pagers External dependencies of TFT Library The following variables must be defined in all projects using TFT Description library dim TFT D P byt f gy ee ee See TFT Data Port d
125. for PIC32 New Project The easiest way to create a project is by means of the New Project Wizard drop down menu Project New Project or by clicking the New Project Icon E 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 New Project Wizard Select the device you want to use Device Name P32MX460F512L MikroElektronika 614 mikroBasic PRO for PIC32 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 mbp32 Cancel 615 MikroElektronika mikoBasic PRO for PIC32 Step Four Add project file to the project if they are avaiable at this point You can always add project files later using Project Manager New Project Wizard Step 4 6 Add project files if they are available at this point You can always add project files later using the Project Manager in IDE Add File To Project C Projects Hello World mbas
126. for PIC32 includes a String Library which automatizes string related tasks MikroElektronika 204 mikroBasic PRO for PIC32 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 dim p as word A pointer can be assigned to another pointer However note that only the address not the value is copied Once you modify the data located at one pointer the other pointer when dereferenced also yields modified data Pointers and memory spaces Pointers can point to data in any available memory space Pointers can reside in any available memory space except in program code memory space dim ptrl as const byte ptrl1 pointer in data space pointing to a byte in code space dim ptr2 as 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 dim ptr3 as data byte code error pointers can not be placed in code space Due to backward compatibility pointers to progr
127. from main DisableContextSaving instruct the compiler not to automatically perform context switching ws None SOS SetFuncCall Prototype sub procedure SetFuncCall dim FuncName as 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 SetFunCCall directive is called in the code no matter whether any of them was explicitly called or not Thus placing Set FuncCall directive in main will make compiler link specified routines always sub procedure first p q as byte SetFuncCall second let linker know that we will call the routine second end sub MikroElektronika 156 mikroBasic PRO for PIC32 SetOrg Prototype sub procedure SetOrg dim RoutineName as string dim address as longint Use the SetOrg routine to specify the starting address of a routine in ROM Parameters RoutineName routine name address starting address This routine must be called from main SetOrg UART1 Write 0x1234 DoGetDateTime Retums Sting with da
128. holding the IP address the requested host name was resolved 0 otherwise Ethernet module has to be initialized See SPI Ethernet 24j600 Init dim remoteHostIpAddr as string 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 243600 dnsResolve swisstime ethz Ch 5 4 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 MikroElektronika 454 mikroBasic PRO for PIC32 SPI Ethernet 24j600 initDHCP Prototype sub function SPI Ethernet 243600 initDHCP dim tmax as byte as 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
129. i 0 copy httpMethod to ram for use in memcmp routine for i 0 to 4 txt i httpMethod i next i if memcmp GgetRequest txt 5 lt gt 0 then only GET method is supported here result 0 exit end if Inc httpCounter one more request done if getRequest 5 s then if request path name starts with s store dynamic data in transmit buffer stat the text string replied by this request can be interpreted as javascript ements by browsers result SPI Ethernet putConstString httpHeader HTTP header result result SPI Ethernet putConstString 8httpMimeTypeScript with text MIME type add ANO value to reply WordToStr ADC1 Get Sample 0 dyna txt var AN0O result result Spi Ethernet putString txt result result Spi Ethernet putString dyna Ext Ww result result Spi Ethernet putString txt add AN1 value to reply WordToStr ADCl Get Sample 1 dyna txt var AN1 result result Spi Ethernet putString txt result result Spi Ethernet putString dyna txt result result Spi Ethernet putString txt 433 MikroElektronika mikoBasic PRO for PIC32 add PORTB value buttons to reply txt var PORTB result result Spi Ethernet putString txt WordToStr PORTB dyna result result Spi Ethernet putString dyna txt Ww result result Spi Ethernet putString txt add PORTD value LEDs to
130. if wend end RB3 bit lt gt 0 then then then then then Configure RB7 RB3 as endless loop If PORTB Wait for If PORTB Wait for If PORTB Wait for If PORTB Wait for If PORTB Wait for 7 is pressed button to be 6 is pressed button to be 5 is pressed button to be 4 is pressed button to be 3 is pressed button to be input play Tonel released play Tonel released play Tonel released play Tonel released play Tonel released 403 MikroElektronika mikoBasic PRO for PIC32 HW Connection OSCILLATOR SPEAKER Example of Sound Library MikroElektronika 404 mikroBasic PRO for PIC32 SPI Library The SPI module is available with all PIC32 MCUs mikroBasic PRO for PIC32 provides a library for initializing the Slave mode and initializing and comfortable work with the Master mode The PIC32 can easily communicate with other devices via SPI A D converters D A converters MAX7219 LTC1290 etc Important SPI library routines require you to specify the module you want to use To select the desired SPI module simply change the letter x in the routine prototype for a number from 1 to 3 Number of SPI modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Switching between the SPI modules in the SPI library is done by the SPI Set Acti
131. 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 TFT Get Coordinates 6x coord y coord 0 then end if TP TFT Calibrate Min ums Nothing amp Jw mer Caira n0 Calibration of Torta deft comer OO TP TFT Calibrate Max Reums nona Example TP TFT Calibrate Max Calibration of upper right corner mem foe MikroElektronika 558 mikroBasic PRO for PIC32 TP TFT Get Calibration Consts Prototype sub procedure TP TFT Get Calibration Consts dim byref x min as word dim byref x max as word dim byref y min as word dim byref y max as word Description Gets calibration constants after calibration is done and stores them in x min x max y min and y max sica 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 8x max Qy max calibration constants TP TFT Set Calibration Consts Prototype sub procedure TP TFT Set Calibration Consts dim x min as word dim x max as word dim y min as word dim y max as word
132. j next i Error error handling code MikroElektronika 230 mikroBasic PRO for PIC32 Gosub Statement Use the gosub statement to unconditionally jump to a local label for more information refer to Labels The syntax of the gosub statement is gosub label name jobs nad return This will transfer control to the location of a local label specified by label name Also the calling point is remembered Upon encountering the return statement program execution will continue with the next statement line after gosub The gosub line can come before or after the label It is not possible to jump into or out of routine by means of gosub Never jump into a loop or other structured statement since this can have unpredictable effects Note Like with goto the use of gosub statement is generally discouraged mikroBasic PRO for PIC32 supports gosub only for the sake of backward compatibility It is better to rely on functions and procedures creating legible structured programs asm Statement mikroBasic PRO for PIC32 allows embedding assembly in the source code by means of the asm statement Note that you cannot use numerals as absolute addresses for register variables in assembly instructions You may use symbolic names instead listing will display these names as well as addresses You can group assembly instructions with the asm keyword asm block of assembly instructions end asm The only types whose name remains t
133. ko ko ko Program body Nok ck ok ck ck ck ck ck ck kk kk kk ck kk ko kk KKK KEK ck ko ko ko kk KK kk ck ko ck ko ko ck kk ck ko kv kA Sk kv ck ko A Ao main write your code here end MikroElektronika 188 mikroBasic PRO for PIC32 Organization of Other Modules Modules other than main start with the keyword module Implementation section starts with the keyword implements Follow the model presented below module module name include include other modules Nok ck ok KK KK kk kk kk ck ck KK kk kk ok kk ok koc kk ck ko ko ck KK ck ko ck ko Sk ke kk Ck ck ck ko kv kA kc k ko ko ke Ao Interface globals Nokckok ck kk ck kk ck kk Ck kk KK ck kk KKK KK KKK KKK ck ko kk ck ck kk kc ko kckckckockck ck ckck ck ck ck ck k symbols declarations symbol constants declarations const structures declarations structure variables declarations dim Name Name2 as type absolute 0x123 external volatile register sfr procedures prototypes sub procedure sub procedure name dim byref const ParamName as type dim byref const ParamName2 ParamName3 as type functions prototypes sub function sub function name dim byref const ParamName as type dim byref const ParamName2 ParamName3 as type as type VK KKKKKKKKKKKKKKKK kk kk kk ck ck kk ck kk kk kk ck kk ck kk ke kk kk ck Mk kv kx ko ko ko ko ko ko Implementation VK ok ok kk ck ck Ck 0k 0k 0k kk ck
134. make sure you don t overwrite boot or FAT sector as it could make your card on PC or digital camera unreadable Drive mapping tools such as Winhex can be of a great assistance Library uses SPI module for communication The user must initialize the appropriate SPI module before using the MMC Library For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by using the SPI Set Active function See the SPI Library functions The SPI module has to be initialized through SPIx Init Advanced routine with the following parameters SPI Master bit 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 Mmoc Fat Init routines MikroElektronika 336 mikroBasic PRO for PIC32 Library Dependency Tree MMC MMC FAT16 C String C Type External dependencies of MMC Library The following variable must be defined bescrintion in all projects using MMC library P dim Mmc Chip Select as sbit sfr i dim Mmc Chip Select as sbit at LATFO Chip select pin z external bit dim Mmc Chip Select Direction Direction of the chip select pin dim Mmc Chip Select Direction as sbit
135. may also be required Every Software I C library routine has its own counterpart in Hardware I C library except 12C Repeated Start Soft I2C Start is used instead of 12C Repeated Start Working clock frequency of the Software I C is 20kHz External dependencies of Software C Library The following variable must be defined bescrintion in all projects using RS 485 Library P dim Soft I2C_Scl as sbit sfr Sait le Clock ine dim Soft I2C Scl as sbit at RF3 bit external cs i ae dim Soft I2C Sd as sbit sfr i z i S HS ata Soft lC Data line dim Soft I2C Sda as sbit at RF2 bit external dim Soft I2C Scl Direction as Direction of the Soft IPC Clock dim Soft I2C Scl Direction as sbit sbit sfr external pin at TRISF3 bit dim Soft I2C Sda Direction as 5 dim Soft I2C Sda Direction as sbit abit sfr external Direction of the Soft I C Data pin at TRISF2 bit Library Routines Soft I2C Init Soft I2C Start Soft I2C Read Soft I2C Write Soft I2C Stop Soft I2C Break 387 MikroElektronika mikoBasic PRO for PIC32 Soft I2C Init Rums non OOOO SSS Requires Global variables Soft I2C Scl Soft I C clock line Soft I2C Sda Soft FC data line Soft I2C Scl Pin Direction Direction of the Soft I C clock pin Soft I2C Sda Pin Direction Direction of the Soft I C data pin must be defined before using this function Software I2C connections dim Soft I2C Scl as i RES bit Soft I2C Sda as i R
136. 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 Ext sub mikr memcpy Gtxt 4 Qtxt sub 4 string txt will be populated with the first 4 characters of the txt sub string beginning from the 4th character 597 MikroElektronika mikoBasic PRO for PIC32 memmove Prototype sub procedure memmove dim pl p2 as byte dim nn as word Description The function copies nn words from the memory area starting at the address p2 to the memory area starting at p1 If these memory buffers overlap the Memmove function ensures that the words in p2 are copied to p1 before being overwritten For parameters p1 and p2 you can use either a numerical value literal variable constant indicating memory address or a dereferenced value of an object for example mystring or PORTB txt 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 sub pr
137. more resources for making it than what we used for mikroPascal and mikroBasic We also worked on some very complex topics such as floating point typedef union a completely new debugger and many other Because of that there is difference in price Why do your PIC compilers don t support 12F508 and some similar chips Unfortunately our PIC compilers don t support 12F508 and similar chips because these chips are designed to use 12 bit wide instructions Our compiler support MCUs which use 14 bit or wider instructions What are limitations of demo versions of mikroElektronika s compilers The only limitation of the free demo version is that it cannot generate hex output over 2K of program words Although it may sound restrictive this margin allows you to develop practical working applications without ever thinking of demo limit If you intend to develop really complex projects in one of our compilers you should consider purchasing the license key Why do still get demo limit error when purchased and installed license key If you are first time installing and registering compiler you need to follow instructions exactly as described in registration procedure License is valid only for the computer from which 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 h
138. 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 GLCD LIBRARY DE 0 0 T6963C ROM MODE XOR T6963C line Prototype sub procedure T76963C line dim x0 xl yl as integer dim pcolor as byte Draws a line from x0 y0 to x1 y1 Parameters x0 x coordinate of the line start y0 y coordinate of the line end x1 X coordinate of the line start y1 y coordinate of the line end pcolor color parameter Valid values T6963C BLACK and T6963C WHITE Ree fg o ooo UU Example 16963C_line 0 239 127 T6963C WHITE Nu EE e MikroElektronika 516 mikroBasic PRO for PIC32 T6963C rectangle Prototype sub procedure T6963C rectangle dim x0 y0 xl yl as integer dim pcolor as byte Draws a rectangle on Glcd Parameters x0 x coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner pcolor color parameter Valid values T6963C BLACK and T6963C W
139. non word boundary Metacharacters Iterators Any item of a regular expression may be followed by another type of metacharacters iterators Using this metacharacters you can specify number of occurences of previous character metacharacter or subexpression zero or more greedy similar to 0 one or more greedy similar to 1 zero or one greedy similar to 0 1 n exactly n times greedy n atleast n times greedy n m atleast n but not more than m times greedy Zero or more non greedy similar to 0 one or more non greedy similar to 1 zero or 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 107 MikroElektronika mikoBasic PRO for PIC32 Examples count r B matches strings like counter countelkjdflkj9r and countr count 4r matches strings like counte
140. 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 integer short longint integer gt longint integral gt float 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 dim a as byte dim b as 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 destination range If expression evaluates to a more complex type than expected excess of data will be simply clipped higher bytes are lost dim i as byte dim j as word j FFOF i j i becomes SOF higher byte SFF is lost MikroElektronika 212 mikroBasic PRO for PIC32 Explicit Conversion Explicit conversion can be executed at any point by inserting type keyword byte word short integer longint Or float ahead of the expression to be converted The expr
141. 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 mikroBasic PRO for PIC32 SSA s main goal is in allocating local variables into the RX space instead onto the frame To do that SSA has to make an alias and data flow analysis of the Control Flow Graph Besides these savings there are a number of compiler optimization algorithms enhanced by the use of SSA like Constant Propagation Dead Code Elimination Global Value Numbering Register Allocation Changes that SSA brings is also in the way in which routine parameters are passed When the SSA is enabled parameters are passed through a part of the RX space which is reserved exclusively for this purpose Allocating local variables and parameters in RX space has its true meaning for those architectures with hardware frame Enabling SSA optimization in compiler is done by checking box from the Output Settings Menu Lets consider a trivial case program Example sub procedure SSA Test dim y as integer dim k as integer if yt k then asm nop end asm end if end sub main SSA Test 5 5 end With SSA enabled sub procedure 53A Test this example is consisted of 3 asm instructions Example mbas 29 if yt k then 0x9D000000 0x033A1021 ADDU R2 R25 R26 163 MikroElektronika mikoBasic PRO for PIC32 0x9D00
142. 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 Gica L ine 0 0 20 30 1 MikroElektronika 302 mikroBasic PRO for PIC32 Glcd V Line Prototype sub procedure Glcd V Line dim y start y end x pos color as byte Description Draws a vertical line on Glcd Parameters y start y coordinate of the line start Valid values 0 63 y end y coordinate of the line end Valid values 0 63 x pos X coordinate of vertical line Valid values 0 127 color color parameter Valid values 0 2 The parameter color determines the line color 0 white 1 black and 2 inverts each dot Nothing Requires Glcd needs to be initialized see Glcd Init routine Draw a vertical line between dots 10 5 and 10 25 Glcd V Line 5 25 10 1 None Glcd H Line Prototype sub procedure Glcd H Line dim x start x end y pos color as byte Description Draws a horizontal line on Glcd Parameters x start x coordinate of the line start Valid values 0 127 x end X coordinate of the line end Valid values 0 127 y
143. or delete character decimal 0 31 and 127 otherwise returns zero isentrl Nr returns OxFF res isentrl oe returns 0 isdigit Prototype sub function isdigit dim character as byte as word Function returns OxFF if the character is a digit 0 9 otherwise returns zero res isdigit o Y returns OxFF res isdigit 1 Y returns 0 519 MikroElektronika mikoBasic PRO for PIC32 isgraph Prototype sub function isgraph dim character as byte as word Description Function returns OxFF if the character is a printable excluding the space decimal 32 otherwise returns zero res isgraph o returns OxFF res isgraph returns 0 islower EU Be sub function islower dim character as byte as word Function returns OxFF if the character is a lowercase letter a z otherwise returns zero res islower 0 returns OxFF res islower A returns 0 ispunct Prototype sub function ispunct dim character as byte as word Description Function returns OxFF if the character is a punctuation decimal 32 47 58 63 91 96 123 126 otherwise returns zero ispunct Y returns OxFF ispunct 1 returns 0 isspace Prototype sub function isspace dim character as byte as 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 res Gea returns 0 isupper
144. or on our site you may include them in your project however you are not allowed to charge your users for these Why does an example provided with your compilers doesn t work All of the examples provided with our compilers are tested and work fine You need to read commented header of the example and be sure that you have used the same MCU example is written for and that you have hardware connections DIP switches jumpers etc set as described Your example works if use the same MCU you did but how to make it work for another MCU You should read your MCU s datasheet Different MCUs can have different pin assignments and may require different settings If you need help regarding this you can find free online books on our website and recommend you starting there You can also ask for help on our forum mikroBasic PRO for PIC32 need this project finished can you help me We currently do not do custom projects however we can give you some directions when you start working on your project and come to a problem Also our forum is very active community and as you can find there experts in different fields we encourage you to look for 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
145. 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 dim buf as word 4 sub procedure func33 Delay ms 1000 nop longjmp buf 2 nop end sub sub procedure func PORTB 3 if setjmp buf 2 then PORTB 1 else func33 end if end sub main ADPCFG OxFFFF PORTB 0 TRISB 0 nop func nop Delay ms 1000 PORTB OxFFFF end Note Program flow diagrams are indexed according to the sequence of execution MikroElektronika mikoBasic PRO for PIC32 String Library mikroBasic PRO for PIC32 includes a library which automatizes string related tasks Library Functions memchr memcmp memcpy memmove memset strcat strcat2 strchr strcmp strcpy strlen strncat strncpy strspn strncmp strstr strcspn strpbrk strrchr Itrim rtrim strappendpre strappendsuf length memchr Prototype sub function memchr dim p as byte dim ch as byte dim n as word as 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 indicati
146. packet filtering schemes to limit incoming packets It also provides an internal DMA module for fast data throughput and hardware assisted IP checksum calculations Communication with the host controller is implemented via two interrupt pins and the SPI with data rates of up to 10 Mb s Two dedicated pins are used for LED link and network activity indication This library is designed to simplify handling of the underlying hardware ENC283560 It works with any PIC32 with integrated SPI and more than 4 Kb ROM memory 38 to 40 MHz clock is recommended to get from 8 to 10 Mhz SPI clock otherwise PIC32 should be clocked by ENC28J60 clock output due to its silicon bug in SPI hardware If you try lower PIC32 clock speed there might be board hang or miss some requests SPI Ethernet library supports IPv4 protocol ARP requests ICMP echo requests UDP requests TCP requests no stack no packet reconstruction ARP client with cache DNS client UDP client DHCP client packet fragmentation is NOT supported Important Global library variable SPI Ethernet userTimerSec is used to keep track of time for all client implementations ARP DNS UDP and DHCP It is user responsibility to increment this variable each second in it s code if any of the clients is used For advanced users thereis EchEnc285360Private mbas unit in Uses folder of the compiler with description of all routines and global variables
147. parameter x must be between 1 and 1 inclusive The return value is in radians between 0 and M inclusive 1 047198 asin Prototype sub function asin dim x as float as float Description Function returns the arc sine of parameter x that is the value whose sine is x The input parameter x must be between 1 and 1 inclusive The return value is in radians between 1 2 and 11 2 inclusive Example res asin 0 5 res 5 235987e 1 atan Prototype sub function atan dim arg as float as float Description Function computes the arc tangent of parameter f that is the value whose tangent is The return value is in radians between I1 2 and 1 2 inclusive 7 853982e 1 atan2 Prototype sub function atan2 dim y as float dim x as float as float Description This is the two argument arc tangent function It is similar to computing the arc tangent of y x except that the signs of both arguments are used to determine the quadrant of the result and x is permitted to be zero The return value is in radians between M and N inclusive Example res atan2 2 1 4 636475e 1 ceil EON sub function ceil dim x as float as float Function returns value of uo Anal x rounded up to the next whole number Example res ceil 0 5 res 1 000000 COS Prototype sub function cos dim arg as float as float Function returns the cosine of in radians The return value is from 1 to 1 re
148. 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 dim i j x as byte variables ptrl as byte pointers to byte ptr2 as byte main i 10 assign value 10 to variable i is at the address 0x0039 j 5 assign value 5 to variable j is at the address 0x003A ptrl Qi ptrl is pointer to byte pointing to i ptr2 Qj v ptr2 is a pointer pointing to j x ptr2 ptrl result is equal to the distance between the two pointed addresses x 1 1 byte x ptrl ptr2 result is equal to the difference of the values pointed to x 5 end Structures A structure represents a heterogeneous set of elements Each element is called a member the declaration of a structure type specifies a name and type for each member The syntax of a structure type declaration is structure structname dim memberl as typel ki dim membern as typen end structure where structname is a valid identifier each type denotes a type and each member is a valid identifier The scope of a member identifier is limited to the structure in which it occurs so you don t have to worry about naming conflicts between member identifiers and other variables MikroElektronika 210 mikroBasic PRO for PIC32 For example the following declaration creates a structure type called Dot structure Dot dim x as float dim y as float end s
149. pointing to a 3 ptr 6 a 3 now equals 6 Inc ptr ptr now points to the next element of array a a 4 end Also you may sum values pointed to by pointers For example dim i j x as byte variables ptrl as byte pointers to byte ptr2 as byte main i 10 assign value 10 to variable i is at the address 0x0038 j4 5 assign value 10 to variable j is at the address 0x003A ptrl i v ptrl is pointer to byte pointing to i ptr2 Qj Y ptr2 is a pointer pointing to j x ptri 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 209 MikroElektronika mikoBasic PRO for PIC32 For example dim a as byte 10 array a containing 10 elements of type byte ptr as byte pointer to byte main ptr al Y ptr is pointer to byte pointing to a 6 ptr e pir 3 ptr 3 is a pointer pointing to a 3 ptr 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
150. rectangle round edges fil1 20 20 219 107 12 T6963C WHITE T6963C box Prototype sub procedure T6963C box dim x0 y0 xl yl as integer dim pcolor as byte Draws a box on Glcd Parameters x0 x coordinate of the upper left box corner y0 y coordinate of the upper left box corner x1 X coordinate of the lower right box corner y1 y coordinate of the lower right box corner pcolor color parameter Valid values T6963C BLACK and T6963C WHITE mum umm LIGA fave imm box 0 119 239 127 T6963C WHITE Notes No O T6963C circle Prototype sub procedure T6963C circle dim x y as integer dim r as longint dim pcolor as word Draws a circle on Glcd Parameters x x coordinate of the circle center y y coordinate of the circle center r radius size pcolor color parameter Valid values T6963C BLACK and T6963C WHITE pme pe ooo U Example T6963C_circle 120 110 T6963C_WHITE me e O e MikroElektronika 918 mikroBasic PRO for PIC32 T6963C circle fill Prototype sub procedure 76963C circle fill dim x y as integer dim r as longint dim pcolor as byte Draws a filled circle on Glcd Parameters x x coordinate of the circle center y y coordinate of the circle center r radius size PISTE color parameter Valid values 16963C BLACK and T6963C WHITE Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C circle fill 120
151. relevant to the user implemented in the SPI Ethernet Library The appropriate hardware SPI module must be initialized before using any of the SPI Ethernet library routines Refer to SPI Library For MCUs with multiple SPI modules it is possible to initialize them and then switch by using the SPI Set Active routine Library Dependency Tree SPI Ethernet I String 43 MikroElektronika mikoBasic PRO for PIC32 External dependencies of SPI Ethernet Library The following variables must be defined in all projects using SPI Ethernet Description Library dim SPI Ethernet CS as sbit sfr dim SPI Ethernet CS as sbit at RC1 d ENC28J60 chip select pin external bit dim SPI Ethernet RST as sbit sfr dim SPI Ethernet RST as sbit at RCO PE ENC28J60 reset pin ea external bit dim SPI Ethernet CS Direction Direction of the ENC28J60 chip dim SPI Ethernet CS Direction as as sbit sfr external select pin sbit at TRISC1 bit dim SPI Ethernet RST Direction Direction of the ENC28J60 reset dim SPI Ethernet RST Direction as as sbit sfr external pin sbit at TRISCO bit The following routines must be defined in all project using SPI Ethernet Description Library sub function SPI Ethernet UserTCP dim byref remoteHost as byte 4 dim remotePort as word dim localPort as word dim regLength as word dim byref flags as TEthPktFlags as word sub function SPI Ethernet UserUDP dim byref
152. remoteHost as byte 4 dim remotePort as word dim destPort as word dim regLength as word dim byref flags as TEthPktFlags as word TCP request handler UDP request handler Refer to the library example at the bottom of this page for code implementation Refer to the library example at the bottom of this page for code implementation MikroElektronika 414 mikroBasic PRO for PIC32 Library Routines SPI Ethernet Init SPI Ethernet Enable SPI Ethernet Disable SPI Ethernet doPacket SPI Ethernet putByte SPI Ethernet putBytes SPI Ethernet putString SPI Ethernet putConstString SPI Ethernet putConstBytes SPI Ethernet getByte SPI Ethernet getBytes SPI Ethernet UserTCP SPI Ethernet UserUDP SPI Ethernet getlpAddress SPI Ethernet getGwlpAddress SPI Ethernet getDnslpAddress SPI Ethernet getlpMask SPI Ethernet confNetwork SPI Ethernet arpResolve SPI Ethernet sendUDP SPI Ethernet dnsResolve SPI Ethernet initDHCP SPI Ethernet doDHCPLeaseTime SPI Ethernet renewDHCP SPI Ethernet Init Prototype sub procedure SPI Ethernet Init dim mac as byte dim ip as byte dim fullDuplex as 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
153. 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 008000 Ps A75010 AS22CA 470060 A64010 4902C4 474010 AB802CA 2088C0 DLE PS G DLE E A60010 AS02D6 A70010 A902D6 07FF96 470060 463010 A962CA lt DLE gt STX DL A73010 A862CA 470060 A62010 A942CA A72010 A842CA 470060 lt DLE gt 05 b G lt DLI A61010 A922CA A71010 AS22CA 470060 A60010 a902cA A70010 DLE lt DLE gt E DI AB02CA 2088CO A60010 A802D6 A70010 A902D6 O7FF7C 2088C0 STX SPC D A60010 370002 07FF64 370001 O7FF86 FAB8000 060000 FA0002 DLE STX 7dy lt 37000F 200800 9FBF40 370019 200C00 9FBF40 370016 200940 SI 7 B5 SPC S9FBF40 370013 200D40 9FBF40 370010 200800 9FBF40 370000 lt DC3 gt 7 CR 97B84E 10061 32FFEE 97B84E E10062 32FFEE 97B84E E10063 N a iy2N b 32FFEE 97BB84E E10064 32FFEE 37FFF 97B83E 5000E1 5700068 iy2N d iy28y7 gt 408010 9FBF40 781F80 07FF98 B1002F 2088CO0 A10010 EF2000 lt DLE gt US 980700 97B8AE 470060 408010 E00410 32000C 97B8AE 470060 BELL 9 G t 408010 784010 FB8000 781F80 07FF32 B1002F 200011 470060 DLE Q DLE Qx
154. s x 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 module Mymodule dim AnotherBit as sbit external Abit is precisely defined in some external file for example in the main program unit implements end program MyProgram dim MyVar as byte dim Abit as sbit at MyVar 0 this is where Abit is fully defined main end 137 MikroElektronika mikoBasic PRO for PIC32 at keyword You can use the keyword at to make an alias to a variable for example you can write a library without using register names and later in the main program to define those registers for example module MyModule dim PORTAlias as byte external here in the library we can use its symbolic name implements end program MyProgram dis PORTAlias byte as at PORTB this is where PORTAlias is fully defined main 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 mikroBasic PRO for PIC32 compiler provides a bit data type that may be used for variable declarations It can not be used for argument lists and function return values dim bf as bit bit variable There are no pointers to bit variables invalid 1 psp
155. see schematic below Parameters width width of the Glcd panel height height of the Glcd panel ntW font width Requires Global variables 6963C_dataPort Data Port r6963C_ ctrilwr Write signal pin 6963C_ctrlrd Read signal pin r6963C_ ctrlca Command Data signal pin r6963C ctrirst Reset signal pin L6963C ctrlwr Direction Direction of Write signal pin L6963C ctrlrd Direction Direction of Read signal pin r6963C ctrlcd Direction Direction of Command Data signal pin L6963C ctrlrst Direction Direction of Reset signal pin must be defined before using this function 911 MikroElektronika mikoBasic PRO for PIC32 T6963C module connections dim T6963C dataPort as byte at PORTB DATA port dim T6963C ctrlwr as sbit at LATF2 bit WR write signal dim T6963C ctrlrd as sbit at LATF1 bit RD read signal dim T6963C ctrlcd as sbit at LATFO bit CD command data signal dim T6963C ctrlrst as sbit at LATF4 bit RST reset signal dim T6963C ctrlwr Direction as sbit at TRISF2 bit WR write signal direction dim T6963C ctrlrd Direction as sbit at TRISF1 bit RD read signal direction dim T6963C ctrlcd Direction as sbit at TRISFO bit CD command data signal direction dim T6963C ctrlrst Direction as sbit at TRISF4 bit RST reset signal direction Signals not used by library they are set in main function dim T6963C ctrlce as sbit at LATF3 bit C
156. see special offers page on our website Also you can contact our Sales Department and see if you are eligible for some additional discount have a question about your compilers which is not listed here Where can find an answer Firstly look for it in your compiler s Help If you don t find an answer there please create a support ticket on our website UJO9 e0Jyuu 9 eoujo je sn j9ejuoo oj ejejiseu jou op sjesodoud sseulsnq Jo ponh ua suonsenb Aue ney no poddns ue ios Soiu MMM ye 1exon INOA eoejd se jd uoneuuojJul EUSUUUS pasu uneni spnpoud ino Jo ie YIM V Sueqoid aulos ete de ale noA j WOT G0 XIU WM 3 9JISq9A JNO YISA esed sionpoid igne aow uJee A nof Q THOM Q30Q038WH HO4 SNOILL YTIOS 3H VMQHVH ANY gps eshte
157. sequence is expected If Attempts is set to 255 this routine will continuously try to detect the Delimiter sequence Requires Routine requires at least one UART module Used UART module must be initialized before using this routine See UARTx Init and UARTx Init Advanced routines UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Read text until the sequence OK is received and send back what s been received UART1 Init 4800 initialize UART module Delay ms 100 while TRUE if UART1 Data Ready if data is received UART1 Read Text output OK 10 reads text until OK is found UART1 Write Text output sends back text end if wend MikroElektronika 566 mikroBasic PRO for PIC32 UARTx Write Prototype sub procedure UARTx Write dim data as word The function transmits a byte via the UART module data data 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 dim data as byte data_ OxlE UART1 Write data UART library routines require you to specify the module you want to use To select the d
158. that represents difference between the mikroBasic PRO for PIC32 character set and regular ASCII set eg if A is 65 in ASCII character and A is 45 in the mikroBasic PRO for PIC32 character set aFontOffs is 20 Demo fonts supplied with the library have an offset of 32 which means that they start with space The user can use fonts given in the file Lib GLCDFonts file located in the Uses folder or create his own fonts List of supported fonts Font Glcd System3x5 Font Glcd System5x7 Font Glcd 5x7 Font Glcd Character8x7 For the sake of the backward compatibility these fonts are supported also System3x5 equivalent to Font Gl1cd System3x5 FontSystem5x7 v2 equivalent to Font G1cd System5x7 font5x7 equivalent to Font G1cd 5x7 Character8x7 equivalent to Font Glcd Character8x7 Nothing Glcd needs to be initialized see Glcd Init routine myfont which starts with space 32 Ya 32 307 MikroElektronika mikoBasic PRO for PIC32 Glcd Write Char Prototype sub procedure Glcd Write Char dim character x pos page num color as byte 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 whit
159. the SPI module with user defined settings Parameters Parameters master mode data mode clock divider slave select data sample clock idle and determine the working mode for SPI The master mode parameter determines the working mode for SPI module he parameter data mode the data length mode which can be 8 bits per transmitions cycle 16 bits br 32 bits he parameter clock divider determines the value of the SPI clock speed Used only in the Maste Mode Clock Divider Value Valid values from 2 to 1024 he parameter slave select determines whether the Slave Select SS pin is used in communication alid in the Slave Mode only he parameter data sample determines the sample moment phase of input data Data Sampling Moment ed sampled in the middle of data output SPI DATA SAMPL IDDLE Data sampled at end of data output time SPI DATA SAMPLE END 407 MikroElektronika mikoBasic PRO for PIC32 Parameters The parameter clock idle determines the behaviour of the SPI clock CLK line in IDLE phase Clock Polarity IDLE state is Lo ACTIVE state is Hi SPI CLK IDLE LOW E state is Hi ACTIVE state is Lo SPI CLK IDLE HIGH The parameter edge determines on which clock edge data is considered to be valid Clock Edge Data is valid on ACTIVE to IDLE transition SPI ACTIVE 2 IDLE Data is valid on IDLE to ACTIVE transition SPI IDLE 2 ACTIV
160. 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 Crrole 50 50 10 1 Glcd Circle Fill Prototype sub procedure Glcd Circle Fill dim x center as integer dim y center as integer dim radius as integer dim color as byte Draws a filled circle on Glcd Parameters x center x coordinate of the circle center Valid values 0 127 y center y coordinate of the circle center Valid values 0 63 radius radius size color color parameter Valid values 0 2 Glcd needs to be initialized see Glcd Init routine Draw a circle with center in 50 50 and radius 10 Gled Circle F ill 50 50 10 1 MikroElektronika 306 mikroBasic PRO for PIC32 Glcd Set Font Prototype sub procedure Glcd Set Font dim byref const activeFont as byte dim aFontWidth aFontHeight as byte dim aFontOffs as byte Sets font that will be used with Glcd Write Char and Glcd Write Text routines Parameters activeFont font to be set Needs to be formatted as an array of char aFontWidth width of the font characters in dots aFontHeight height of the font characters in dots aFontOffs number
161. then if in 100000 poll cycles the answer Inc PORTD y was not detected signal cnt 0 failure of send message RS485Master Send dat 1 160 if PORTD gt 10 then if sending failed 10 times RS485Master Send dat 1 50 A send message on broadcast address end if end if wend end Copy Code To Clipboard program RS485 Slave Example dim dat as byte 20 buffer for receving sending messages i j as byte dim rs485 rxtx pin as sbit at RF2 bit s t transcieve pin rs485 rxtx pin direction as sbit at TRISF2 bit set transcieve pin direction Interrupt routine sub procedure interrupt iv IVT UART 2 ilevel 7 ics ICS SRS RS485Slave Receive dat U2RXIF bit 0 ensure interrupt not pending end sub 383 MikroElektronika mikoBasic PRO for PIC32 main CHECON 0x32 ADIPCFG OxFFFF TRISB TRISD PORTB PORTD e Oo UART2 Init 19200 Delay ms 100 RS485Slave Init 160 dat 0 OxAA dat 1 OxFO0 dat 2 Ox0F dat 4 0 dat 5 0 dat 6 0 U2IPO bit 1 U2IPl bit 1 U2IP2 bit 1 URXISEL1 U2STA bit 0 received U2RXIF bit 0 ei RO end asm E if dat 5 0 then dat 5 0 end if if dat 4 0 then dat 4 0 j dat 3 for i 1 to dat 3 PORTB dat i 1 initialize UART2 module Intialize MCU as slave address 160 ensure that message received flag is 0 ensure that error flag is 0 set interrupt priority to Z 0x In
162. 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 OxFF set CONFIGURATION mode CANSPI1 module must be in config mode for mask settings Set all B1 mask bits to 1 all filtered bits are relevant Note that 1 is just a cheaper way to write OxFFFFFFFF Complement will do the trick and fill it up with ones CANSPISetMask CANSPI MASK Bl l CANSPI CONFIG MATCH MSG TYP CANSPI CONFIG XTD MSG MikroElektronika 248 mikroBasic PRO for PIC32 CANSPISetFilter Prototype sub procedure CANSPISetFilter dim CAN FILTER as byte dim val as longint dim CANSPI CONFIG FLAGS as byte Description Configures message filter The parameter value is bit adjusted to the appropriate filter registers Parameters CANSPI FILTER CAN module filter number Valid values CANSPI FILTER constants See CANSPI FILTER constants val filter register value This value is bit adjusted to appropriate filter registers CANSPI CONFIG FLAGS selects type of message to filter Valid values CANSPI CONFIG STD MSG and CANSPI CONFIG XTD MSG See CANSPI CONFIG FLAGS constants Nothing Requires The CANSPI module must be in Config mode otherwise the function will be ignored See CANSPISetOperationMode The CANSPI routines are supported on
163. to the assigned file next loopl next loop2 end sub Ser SaaS SaaS Opens an existing file and rewrites it sub procedure M Open File Rewrite filename 7 C Set filename for single file tests Cf Fat Assign filename 0 Cf Fat Rewrite for loopl 1 to 55 file contents 0 byte loopl div 10 48 file contents 1 byte loopl mod 10 48 Cf Fat Write file contents LINE LEN 1 write data to the assigned file next loopl end sub EUUSESCEESERES Opens an existing file and appends data to it and alters the date time stamp sub procedure M Open File Append 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 2009 Prepare file for append file contents 26 13 CR file contents 27 10 LF Cf Fat Write file contents 27 Write data to assigned file end sub seguenti e eueeeeides Opens an existing file reads data from it and puts it to USART sub procedure M Open File Read filename 7 B Cf Fat Assign filename 0 Cf Fat Reset size To read file procedure returns size of file while size gt 0 Cf Fat Read character UART1 Write character Write data to USART Dec size wend 215 MikroElektronika mikoBasic PRO for PIC32 Y Deletes a file If file doesn t exist it will first be created j and then deleted sub procedure M Delete File filena
164. v Show Notification J Output This option is already set up to automatically correct some words For example if you type whie1 it will be corrected to while when you press the spacebar while Autocorrect from whiel to while MikroElektronika 54 mikroBasic PRO for PIC32 The user can easily add its common typos by entering original typo for example 5t ye to the Original box and replacement byte to the Replacement box and just click Add button Next time when the typo occurs it will be automatically corrected Auto Complete Code Templates Auto Complete option saves lots of keystrokes for commonly used phrases by automatically completing user s typing Options ee Editor Settings V Enable Auto Complete iy Key word dow e Colors Description do while Auto Correct do while A for no 9 Auto Complete for statement c2 Function header template e int func declaration Style 1 if no if no begin end else no begin end if else if statement void func declaration ptemplate header comment for a project switch switch statement do J Output mikoBasic PRO for PIC32 The user can insert the Code Template by typing the name of the template for instance dow then press Ctrl J and the Code Editor will automatically generate a code do L Auto Complete You can add yo
165. 000 WL OV lo addr proc WO retrieve hi address byte of routine proc and move it to WO 0x0001 gt W1 OV lo addr msg WO retrieve low address word of constant msg and move it to WO 0x3652 gt W1 MOV myvarl 42 w0 accessing hi word of myvarl variable and move it to W1 OxABCD gt W1 end asm end Asm code and SSA optimization If asm code is mixed with the Basic 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 MikroElektronika 232 mikroBasic PRO for PIC32 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 Any line in source code with leading is taken as a compiler directive The initial can be preceded or followed by whitespace excluding new lines The compiler directives are not
166. 0004 0x9D000008 L SSA Test 0x10400002 0x70000000 BEO NOP R2 RO L SSA Test2 Without SSA enabled sub procedure 554 Test this example is consisted of 5 asm instructions Example mbas 29 0x9D000000 0x9D000004 0x9D000008 0x9D00000C 0x9D000010 L SSA Test 0x87A30002 0x87A20000 0x00431021 0x10400002 0x70000000 if yt k then LH R3 2 SP LH R2 O SP ADDU R2 R2 BEQ NOP Proper Coding Recommendations R3 R2 RO L SSA Test2 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 function2 parameters then parameter order should remain the same sub procedure f2 dim a as integer end sub sub procedure f1 dim x as integer routine call f2 x y f2 y x end sub xeos and yb 1 tod and 2 y gt a and x gt b 1 to 2 and 2 dim b as dim y as to to integer integer 2 is far more efficient than 1 Large amount of nested loops and complex structures as its members should be avoided When writing a code in assembly keep in mind that there are registers reserved exclusively for routine parameters Using goto and label statements in nested loops should be avoided Obtaining address
167. 0truck bmp Delay ms 500 SPI Glcd Partiallmage 56 34 68 30 128 64 80truck bmp Delay2s Delay2s SPI Glcd Fill 0x00 Clear GLCD SPI Glcd Box 62 40 124 56 1 Draw box SPI Gled Rectangle 5 5 84 35 1 Draw rectangle Delay ms 1000 SPI Glcd Rectangle Round Edges 2 2 87 38 7 1 Delay ms 1000 MikroElektronika A10 mikroBasic PRO for PIC32 SPI Glcd Rectangle Round Edges Fill 8 8 81 32 12 1 Delay ms 1000 SPI Glcd Line 0 0 127 63 1 Draw line Delay2s counter 5 while counter lt 59 Draw horizontal and vertical lines Delay ms 250 SPI Glcd V Line 2 54 counter 1 SPI Glcd H Line 2 120 counter 1 counter counter 5 wend Delay2S SPI Glcd Fill 0x00 Clear GLCD SPI Glcd Set Font G8Font Gled Character8x7 8 7 32 Choose font Character8x7 SPI Glcd Write Text mikroE 1 7 2 Write string for counter 1 to 10 Draw circles SPI Glcd Circle 63 32 3 counter 1 next counter Delay28S SPI Glod Circle Fill 63 32 30 1 Draw circles Delay2s SPI Glcd Box 10 20 70 63 2 Draw box Delay2s SPI Glcd Fill OxFF Fill GLCD SPI Glcd Set Font G6Font Gled Character8x7 8 7 32 Change font someText 8x7 Font SPI Glcd Write Text someText 5 0 2 Write string Delay2s SPI Glcd Set Font G8Font Glcd System3x5 3 5 32 Change font someText 3X5 CAPITALS ONLY SPI Glcd Write Text someText 60 2 2 Write string Delay2s SPI
168. 1 Read seconds byte Read minutes byte Read hours byte Read year day byte Read weekday month byte Issue stop signal and time 391 MikroElektronika mikoBasic PRO for PIC32 seconds seconds and OxF0 gt gt 4 10 seconds and OxOF Transform seconds minutes minutes and OxF0 gt gt 4 10 minutes and 0x0F Transform months hours hours and OxFO gt gt 4 10 hours and OxOF Transform hours year day and 0xC0 gt gt 6 Transform year day day and 0x30 gt gt 4 10 day and OxOF Transform day month month and 0x10 gt gt 4 10 month and 0x0F Transform month end sub SsSSSSSassseeessesss Output values to LCD sub procedure Display Time Lcd Chr 1 6 day 10 48 Print tens digit of day variable Lcd Chr 1 7 day mod 10 48 Print oness digit of day variable Lcd Chr 1 9 month 10 48 Lcd Chr 1 10 month mod 10 48 Lcd Chr 1 15 year 49 Print year vaiable 1 start from year 2011 Lcd Chr 2 6 hours 10 48 Lcd Chr 2 7 hours mod 10 48 Lcd Chr 2 9 minutes 10 48 Lcd Chr 2 10 minutes mod 10 48 Lcd Chr 2 12 seconds 10 48 Lcd Chr 2 13 seconds mod 10 48 end sub sub procedure Init Main CHECON 0x30 ADIPCFG OxFFFF Soft I2C Init Performs project wide init Initialize AN pins as digital Initialize Soft I2C communication Initialize LCD Clear
169. 1 RS485Slave Init 382 RS485Slave Receive 383 RS485Slave Send 383 Library Example 384 HW Connection 387 Message format and CRC calculations 388 Software l C Library 389 External dependencies of Software 1 C Library 389 Library Routines 389 Soft I2C Init 390 Soft I2C Start 390 Soft I2C Read 391 Soft I2C Write 391 Soft I2C Stop 391 Soft I2C Break 392 Library Example 393 Software SPI Library 395 External dependencies of Software SPI Library 395 Library Routines 395 Soft SPI Init 396 Soft SPI Read 397 Soft SPI Write 397 Library Example 397 Software UART Library 399 MikroElektronika 16 mikroBasic PRO for PIC32 Library Routines 399 Soft UART Init 399 Soft UART Read 400 Soft UART Write 400 Soft UART Break 401 Library Example 402 Sound Library 403 Library Routines 403 Sound Init 403 Sound Play 403 HW Connection 406 SPI Library 407 Library Routines 407 SPIx Init 408 SPIx Init Advanced 409 SPIx Read 411 SPIx Write 411 SPI Set Active 412 Library Example 412 HW Connection 414 SPI Ethernet Library 415 Library Dependency Tree 415 External dependencies of SPI Ethernet Library 416 Library Routines 417 SPI Ethernet Init 417 SPI Ethernet Enable 419 SPI Ethernet Disable 420 SPI Ethernet doPacket 421 SPI Ethernet putByte 421 SPI Ethernet putBytes 422 SPI Ethernet putConstBytes 422 SPI Ethernet putString 422 SPI Ethernet putConstString 423 SPI Ethernet getByte 423 SPI Ethernet getBytes 423 SPI Ethernet UserTCP 424 SPI
170. 1 Write Text outstr WordToStr day outstr UART1 Write Text outstr WordToStr hour outstr UART1 Write Text outstr WordToStr minute outstr UART1 Write Text outstr file has been found get its modified date mc Fat Get File Date Modified year month day hour minute UART1 Write Text modified WordToStr year outstr UART1 Write Text outstr MikroElektronika 392 mikroBasic PRO for PIC32 ByteToStr month outstr UART1 Write Text outstr WordToStr day outstr UART1 Write Text outstr WordToStr hour outstr UART1 Write Text outstr WordToStr minute outstr UART1 Write Text outstr get file size fsize Mmc Fat Get File Size LongWordToStr longint fsize outstr UART Write Line outstr else file was not found signal it UART1 Write 0x55 Delay ms 1000 UART1 Write 0x55 end if end sub Bc leere Tries to create a swap file whose size will be at least 100 Y sectors see Help for details sub procedure M Create Swap File dim i as word for i 0 to 511 Buffer i i next i size Mmc Fat Get Swap File 5000 mikroE txt 0x20 see help on this sub function for details if size 0 then LongIntToStr size fat txt UART Write Line fat txt for i 0 to 4999 Mmc Write Sector size Buffer size size 1 UART1 Write next i end if end sub Y
171. 11 1 03 40 FM vere miros com mikroBasic PRO for PIC32 Functions Sorted By Name Chart Sorts and displays functions by their name in the ascending order 1 000 1 00 1200 1300 Double cick on diagram to open R in a new window Project Name CY Development Systems V32M v i CD COG zat6yiLedumep32 S w ASTON ve miros com Functions Sorted By Size Chart Sorts and displays functions by their sizes in a chart like form Double cick on diagram to open R in a new window Project Name C Development Systemsl VIZ vBILCD COG 2xi6 iLed mep32 Tene 1 31 2011 1 03 40 FM ee mb com mikoBasic PRO for PIC32 Functions Sorted By Addresses Sorts and displays functions by their addresses in the ascending order 71 500 000 000 1 500 000 000 71 400 000 000 Double cick on diagram to open it in a new window Project Name C Development SystemslL V32MX v6lLCD COG 2x16 iLed mep32 ewnmiros com Function Tree Displays Function Tree with the relevant data for each function Project Name C l Development Systemsll V32MX v l CD COG 2x16 Lcd mcp32 Time 1 31 2011 1 03 40 PM weeny mires com mikroBasic PRO for PIC32 Memory Summary Displays summary of RAM and ROM memory in a pie like form mikoBasic PRO for PIC32 Messages Window Messages Window displays various informations and notifications about the compilation process It reports f
172. 2 SPI T6963C WHITE Notes None 493 MikroElektronika mikoBasic PRO for PIC32 SPI T6963C box Prototype sub procedure SPI T6963C box dim x0 y0 x1 yl as integer dim pcolor as 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 y1 y coordinate of the lower right box corner pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE meme pg ILNIUUIEDECEEETULGL Example SPI T6963C box 0 119 239 127 SPI T6963C WHITE CREE OOOO NC RE OR ROM T6963C circle Prototype sub procedure SPI T6963C circle dim x y as integer dim r as longint dim pcolor as 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 pam hom IUEUEDGCEDESEIHLAR Example SPI T6963C circle 120 64 110 SPI T6963C WHITE ROM ie y y SPI T6963C circle fill Prototype sub procedure SPI T6963C circle fill dim x as integer dim y as integer dim r as longint dim pcolor as byte Draws a filled circle on the Glcd Parameters Parameters x X coordinate of the circle center y y coordinate of the circle center ri radius size pcolor color parameter Valid values SPI T6963C B
173. 240 Miscellaneous Libraries 240 Hardware Libraries 241 ADC Library 241 Library Routines 242 ADCx Init 242 ADCx Init Advanced 242 ADCx Get Sample 243 ADOCx Read 243 Library Example 244 CANSPI Library 245 Library Dependency Tree 245 External dependencies of CANSPI Library 245 Library Routines 246 CANSPISetOperationMode 246 CANSPIGetOperationMode 247 CANSPIInit 247 CANSPISetBaudRate 249 CANSPISetMask 250 CANSPISetFilter 251 CANSPIRead 252 CANSPIWrite 253 CANSPI Constants 253 CANSPI OP MODE Constants 253 CANSPI CONFIG FLAGS Constants 254 CANSPI TX MSG FLAGS Constants 255 CANSPI RX MSG FLAGS Constants 255 CANSPI MASK Constants 256 CANSPI FILTER Constants 256 Library Example 257 HW Connection 260 Compact Flash Library 261 Library Dependency Tree 261 External dependencies of Compact Flash Library 262 Library Routines 263 Cf_Init 264 Cf_Detect 265 Cf_Enable 265 Cf_Disable 265 MikroElektronika 11 mikoBasic PRO for PIC32 Cf Read Init 266 Cf Read Byte 266 Cf Write Init 266 Cf Write Byte 267 Cf Read Sector 267 Cf Write Sector 267 Cf Fat Init 268 Cf Fat QuickFormat 268 Cf Fat Assign 269 Cf Fat Reset 270 Cf Fat Read 270 Cf Fat Rewrite 271 Cf_Fat_Append 271 Cf_Fat_Delete 271 Cf_Fat_Write 272 Cf Fat Set File Date 272 Cf Fat Get File Date 273 Cf Fat Get File Date Modified 273 Cf Fat Get File Size 274 Cf Fat Get Swap File 274 Library Example 275 HW Connection 280 Epson S1D13700 Graphic Lcd Library 281 Exte
174. 2Cx Start 313 I2Cx Restart 314 I2Cx Is Idle 314 I2Cx Read 315 I2Cx Write 315 I2Cx Stop 316 Library Example 316 Keypad Library 318 External dependencies of Keypad Library 318 13 MikroElektronika mikoBasic PRO for PIC32 Library Routines 318 Keypad Init 318 Keypad Key Press 319 Keypad Key Click 319 Library Example 320 HW Connection 321 Lcd Library 322 Library Dependency Tree 322 External dependencies of Lcd Library 322 Library Routines 322 Lcd Init 323 Lcd Out 324 Lcd Out Cp 324 Lcd Chr 324 Lcd Chr Cp 325 Lcd Cmd 325 Available Lcd Commands 325 Library Example 326 Manchester Code Library 328 External dependencies of Manchester Code Library 328 Library Routines 329 Man Receive Init 329 Man Receive 330 Man Send Init 330 Man Send 331 Man Synchro 331 Man Break 332 Library Example 333 Connection Example 335 Memory Manager Library 336 Library Routines 336 Heap Init 336 GetMem 336 FreeMem 337 MM LargestFreeMemBlock 337 MM TotalFreeMemSize 337 Multi Media Card Library 338 Secure Digital Card 338 Secure Digital High Capacity Card 338 Library Dependency Tree 339 External dependencies of MMC Library 339 Library Routines 339 Mmc Init 340 Mmc Read Sector 341 Mmc Write Sector 341 Mmc Read Cid 342 MikroElektronika 1 mikroBasic PRO for PIC32 Mmc Read Csd 342 Mmoc Fat Init 343 Mmc Fat QuickFormat 344 Mmc Fat Assign 345 Mmc Fat Reset 346 Mmc Fat Read 346 Mmc Fat Rewrite 347 Mmc Fat Append 347 Mmc Fat D
175. 32 recognizes the following kinds of tokens keywords identifiers constants operators punctuators also known as separators Token Extraction Example Here is an example of token extraction Take a look at the following example code sequence end flag 0 First note that end flag would be parsed as a single identifier rather than as the keyword end followed by the identifier flag The compiler would parse it as the following four tokens end flag variable identifier assignment operator 0 literal newline statement terminator 180 MikroElektronika mikroBasic PRO for PIC32 Literals Literals are tokens representing fixed numeric or character values The data type of a constant is deduced by the compiler using such clues as numeric value and format used in the Source code Long and Unsigned Suffixes 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 Ox indicates a hexadecimal numeral for example S8F or 0x8F The percent sign prefix indicates a binary numeral for example 0101 Here are some examples T decimal literal 11 hex literal equals decimal 17 0x11 hex literal equals decimal 17
176. 34 4 if PORTB amp 1 lt lt i strt chr 34 lt td bgcolor red gt ON chr 34 else strt tchr 34 td bgcolor cccccc gt OFF chr 34 7 strt chr 34 lt td gt lt tr gt chr 34 7 document write str Ne ecTPIDU 431 MikroElektronika mikoBasic PRO for PIC32 const indexPage2 as string 470 lt table gt lt td gt lt td gt lt table border 1 style chr 34 font size 20px font family terminal chr 34 gt tr th colspan 3 gt PORTD lt th gt lt tr gt lt script gt Var Str aig str chr 34 chr 34 for i 0 1i lt 8 itt 7 strt chr 34 lt tr gt lt td bgcolor yellow gt LED chr 34 it chr 34 lt td gt chr 34 if PORTD amp 1 lt lt i str chr 34 lt td bgcolor red gt ON chr 34 else strt tchr 34 lt td bgcolor cccccc gt OFF t chr 34 7 strt tchr 34 lt td gt lt td gt lt a href t chr 34 it t chr 34 gt Toggl e lt a gt lt td gt lt tr gt chr 34 3 document write str script table td tr table This is HTTP request lt script gt document write REQ lt script gt lt BODY gt lt HTML gt dim getRequest as byte 15 HTTP request buffer dyna as
177. 3600 putBytes dim ptr as byte dim n as word Description This is MAC module routine It stores requested number of bytes into ENC247600 RAM starting from current ENC24J600 write pointer EWRPT location Parameters ptr RAM buffer containing bytes to be written into ENC247600 RAM n number of bytes to be written Nothing Requires Ethernet module has to be initialized See SPI Ethernet 24 600 Init dim buffer as byte 17 buffer mikroElektronika SPI Ethernet 243600 putBytes buffer 16 put an RAM array into ENC24J600 buffer SPI Ethernet 24j600 putConstBytes Prototype sub procedure SPI Ethernet 24 600 putConstBytes const ptr as byte dim n as word Description This is MAC module routine It stores requested number of const bytes into ENC24J600 RAM starting from current ENC247600 write pointer EWRPT location Parameters ptr const buffer containing bytes to be written into ENC247600 RAM n number of bytes to be written Nothing Ethernet module has to be initialized See SPI Ethernet 24600 Init const buffer as byte 17 buffer mikroElektronika SPI Ethernet 24 600 putConstBytes buffer 16 put a const array into ENC24J600 buffer MikroElektronika 446 mikroBasic PRO for PIC32 SPI Ethernet 24j600 putString Prototype sub function SPI Ethernet 243600 putString dim ptr as byte as word Description This is MAC module r
178. 6963C WHITE 6963C BLACK WHITE C 6963C BLACK C 6963C WHITE C 6963C BLACK 6963C WHITE 6963C BLACK 6963C WHITE C 6963C BLACK C 6963C WHITE 5 SPI T6963C BLACK E 240x128 bmp 64 E 240x128 bmp 64 88 119 240 128 Draw a sprite Select other graphic panel Qmikrol E 240x128 bmp Y Display MikroElektronika 904 mikroBasic PRO for PIC32 while TRUE LE If RB8 is pressed 33 if RB8 bit 0 then Inc panel panel and 1 panel SPI T6963C setPtr SPI T6963C grMemSize SPI T6963C txtMemSize T6963C GRAPHIC HOME ADDRESS S Delay ms 300 Ve Tf RBI is pressed display only graphic panel Ve else if RB9 bit lt gt 0 6963C_ graphics 1 T6963C_ text 0 SPI_1 SPI_1 ET Delay ms 300 Ve Tf RB10 is pressed display only text panel Ve else if LE d RB10 bit 0 SPI T6963C graphics 0 SPI T6963C text 1 Delay ms 300 then then Endless loop If RB11 is pressed display text and graphic panels uS else if RB11 Ve SPI 1 bit lt gt 0 then L6963C graphics 1 SPI 4 T6963C_ text 1 Delay ms 300 If RB12 is pressed Ve else change cursor if RB12 bit lt gt 0 then Inc curs if curs curs 0 end if select case curs case 0 no cursor SPI T6963C cursor 0 3 then pa
179. 6963C rectangle round edges fill 520 T6963C box 520 T6963C circle 520 T6963C circle fill 521 T6963C image 521 T6963C Partiallmage 522 T6963C sprite 522 T6963C set cursor 523 T6963C displayGrPanel 523 T6963C displayTxtPanel 523 T6963C setGrPanel 524 T6963C setTxtPanel 524 T6963C panelFill 524 T6963C grFill 525 T6963C txtFill 525 T6963C cursor height 525 T6963C graphics 526 T6963C text 526 T6963C cursor 526 T6963C cursor blink 527 Library Example 527 HW Connection 533 TFT Library 934 External dependencies of TFT Library 534 Library Routines 535 TFT Init 536 TFT Set Index 537 TFT Write Command 537 TFT Write Data 537 TFT Set Active 538 TFT Set Font 539 TFT Write Char 540 TFT Write Text 540 TFT Fill Screen 541 TFT Dot 542 TFT Set Pen 543 TFT Set Brush 544 TFT Line 546 TFT H Line 547 TFT_V_Line 547 TFT_Rectangle 547 TFT_Rectangle_Round_Edges 548 MikroElektronika 21 mikoBasic PRO for PIC32 TFT Circle 548 TFT Image 548 TFT Partial Image 549 TFT Image Jpeg 549 TFT RGBToColor16bit 550 TFT Color16bitToRGB 550 HW Connection 551 Touch Panel Library 552 Library Dependency Tree 552 External dependencies of Touch Panel Library 552 Library Routines 552 TP Init 553 TP Set ADC Threshold 553 TP Press Detect 554 TP Get Coordinates 555 TP Calibrate Bottom Left 555 TP Calibrate Upper Right 555 TP Get Calibration Consts 556 TP Set Calibration Consts 556 Touch Panel TFT Library 557 Library Dependency Tree 557 External depen
180. 963C writeData dim data as byte Writes data to T6963C controller via SPI interface Reus Nothing S Example srrresscritepataata OO OOOO Notes None ooo SPI T6963C writeCommand Prototype sub procedure SPI T6963C writeCommand dim data as byte Writes command to T6963C controller via SPI interface data command to be written Toshiba Glcd module needs to be initialized See SPI T6963C c routine EN SPI T6963C writeCommand SPI T6963C CURSOR POINTE L L nMn MikroElektronika 488 mikroBasic PRO for PIC32 SPI T6963C setPtr Prototype sub procedure SPI T6963C setPtr dim p as word dim c as byte Description Sets the memory pointer p for command p Parameters p address where command should be written c command to be written Nothing Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine L6963C setPtr SPI T6963C grHomeAddr start SPI T6963C ADDRI ER SET SPI T6963C waitReady SPI T6963C fill Prototype sub procedure SPI T6963C fill dim v as byte dim start len as word Description Fills controller memory block with given byte Parameters v byte to be written start starting address of the memory block 1en length of the memory block in bytes 489 MikroElektronika mikoBasic PRO for PIC32 SPI T6963C dot eee sub procedure SPI T6963C dot dim x y as integer dim color as byte
181. ANSPI 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 245 MikroElektronika mikoBasic PRO for PIC32 Requires Global variables CanSpi CS Chip Select line CanSpi Rst Reset line CanSpi CS Direction Direction of the Chip Select pin CanSpi Rst Direction Direction of the Reset pin must be defined before using this function The CANSPI routines are supported only by MCUs with the SPI module The SPI module needs to be initialized See the SPIx Init and SPIx Init Advanced routines MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page CANSPI module connections dim CanSpi CS as sbit at LATFO bit CanSpi CS Direction as sbit at TRISFO bit CanSpi Rst as sbit at LATF12 bit CanSpi Rst Direction as sbit at TRISFl bit End CANSPI module connections dim CANSPI Init Flags as word CANSPI Init Flags CANSPI CONFIG SAMPLE THRIC CANSPI CONFIG PHSEG2 PRG ON CANSPI CONFIG STD MSG CANSPI CONFIG DBL BUFFER ON CANSPI CONFIG VALID XTD MSG CANSPI CONFIG LINE FILTER OFF
182. Bregg eA EY amp En RS485 Master Example mbp32 Sources RS485 Master Example mbas Binaries Project Level Defines E Image Files CT rs 46 gt EEPROM Files Active Comments Files S C Output Files RS485 Master Example hex E Other Files Next right click the added file and choose Set As Preview Image Project Manager 1 1 Rs4elmmbp32 Example mbp32 zu Ira Er mI TE Y a amp RS485_Master_Example mbp32 C Sources B R5485 Master Example mbas t Binaries Project Level Defines S E Image Files MES fh RS 485 jpg C EEPROM Files My Save Project Group Active Comments Fi Close Project Ctrl K S 5j Output Files B Add Project R5485 Master ARUM E Other Files EE G3 Add File To Project amp Remove File From Project M Build Ctrl F9 a mE Programmer Fil Set As Preview Image Ctrl Alt P 13 MikroElektronika mikoBasic PRO for PIC32 Once you have added the image it will appear in the Image Preview Window D oe fe per Oe pn pe ow ii 1884912ld 1884919ld 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 overv
183. C32 UARTx Init Prototype sub procedure UARTx Init dim baud rate as longword 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 The compiler will choose for which speed the calculation is to be performed high or low This does not mean that it is the best choice for desired baud rate If the baud rate error generated in this way is too big then UARTx Init Advanced routine which allows speed select be used UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Switching between the UART modules in the UART library is done by the UART Set Active function UART modules have to be previously initialized Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 962 m
184. Character Newline character CR LF is not a whitespace in BASIC and serves as a statement terminator separator In mikroBasic PRO for PIC32 however you may use newline to break long statements into several lines Parser will first try to get the longest possible expression across lines if necessary and then check for statement terminators Whitespace in Strings The ASCII characters representing whitespace can occur within string literals In that case they are protected from the normal parsing process they remain as 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 newline character MikroElektronika 119 mikroBasic PRO for PIC32 Comments Comments are pieces of 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 Use the apostrophe to create a comment Any text between an apostrophe and the end of the line constitutes a comment May span one line only There are no multi line comments in mikroBasic PRO for PIC32 Tokens Token is the smallest element of a mikroBasic PRO for PIC32 program meaningful to the compiler The parser separates tokens from the input stream by creating the longest token possible using the input characters in a left to right scan mikroBasic PRO for PIC
185. Click OnMouseOver X PreviewImage Add Image To Project Add File To Project MikroElektronika mikoBasic PRO for PIC32 Now click again Rename button Now you have renamed your Active Comment in such a way that its filename source code name are changed I V ac activeCommentRename 30 Deleting Active Comment Deleting active comment works similar like renaming it By clicking on delete button you will remove an active comment from both code and Project Manager MikroElektronika 102 mikroBasic PRO for PIC32 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 from Project menu select Export Project or hit Ctrl Alt E The following window will appear Export Project Select project to export hikroC PRO for PIC32 Examples Development SystemslLV32MXx velLed BlinkinglLedBlinking mcp32 E Select destination folder D Project EJ In the empty input boxes current location and the destination folder of the desired p
186. D1 bit main CHECON 0x32 ADIPCFG OxFFFF Configure AN pins as digital I O UART1 Init 56000 Initialize UART module at 19200 bps Ps2 Config Init PS 2 Keyboard Delay ms 100 Wait for keyboard to finish UART1 Write Text Ready Ready UART1 Write 13 Line Feed UART1 Write 10 Carriage return while TRUE Endless loop if Ps2 Key Read keydata special down then If data was read from PS 2 if down lt gt 0 and keydata 16 then Backspace read UART1 Write 0x08 Send Backspace to usart terminal else if down lt gt 0 and keydata 13 then Enter read UART1 Write 10 Send carriage return to usart terminal UART1 Write 13 Uncomment this line if usart terminal also expects line feed 1 for new line transition else if down lt gt 0 and special 0 and keydata lt gt 0 then Common key read UART1 Write keydata Send key to usart terminal end if end if end if end if Delay ms 1 Debounce period wend end 371 MikroElektronika mikoBasic PRO for PIC32 HW Connection PS2 1 CONNECTOR PIC32MX460F512L VCC3 5V Example of PS2 keyboard connection PWM Library The CCP module is available with a number of PIC32 MCUs mikroBasic PRO for PIC32 provides a library which simplifies using of the PWM HW Module Important PWM module uses either Timer2 or Timer3 module Library Routines PWM Init PWM Init Advanced PWM Set Duty
187. Divider USB PLL Enable Disabled and Bypassed Oscillator Frequency MHz 8 000000 Interrupt Control O Single Vector Base Address Use SRS EBASE Ox 9FCO 1000 System PLL Output Clock Divider H PuL Divi Multi Vector PLL Divide by 1 Vector Spacing V5 SRS Priority Level Oscillator Selection Bits Primary Osc XT HS EC Secondary Oscillator Enable Enabled Internal External Switch Over Enabled Primary Oscillator Configuration r 1FCOZFF4 Ox00008751 Default XT osc mode IFCOZFFS Ox001485A2 IFCOZFFC OxllOFFOOB CLKO Output Signal Active on the OSCO Pin Enabled Peripheral Clock Divisor Pb Clkis Sys Clk 1 Besides this user can control the Interrupt mechanism by selecting either Single or Multi Vector mode Base Ad dress and SRS Priority level Heap configuration can also be configured by changing the heap size Related topics Project Settings Customizing Projects Interrupts mikoBasic PRO for PIC32 Clean Project Folder This menu gives you option to choose which files from your current project you want to delete Files marked in bold can be easily recreated by building a project Other files should be marked for deletion only with a great care because IDE cannot recover them Clean Project Folder Below is the list of all files in the project folder Files in bold are those generated by the compiler and
188. E signal dim T6963C ctrlfs as sbit at LATF6 bit FS signal dim T6963C ctrlmd as sbit at LATF5 bit MD signal dim T6963C ctrlce Direction as sbit at TRISF3 bit CE signal direction dim T6963C ctrlfs Direction as sbit at TRISF6 bit FS signal direction dim T6963C ctrlmd Direction as sbit at TRISF5 bit MD signal direction End T6963C module connections init display for 240 pixel width 128 pixel height and 8 bits character width T6963C init 240 128 T6963C writeData Prototype sub procedure T6963C writeData dim mydata as byte Writes data to T6963C controller mydata data to be written ums Noi Example resescsriteparatddr OOOO Moes Nm OoOo MikroElektronika 512 mikroBasic PRO for PIC32 T6963C writeCommand Reume Nan 000000 T Toshiba Glcd module needs to be initialized See the T6963C init routine Example T6963C writeCommand T6963C CURSOR POINTER SE LT MI TNR RUM T6963C setPtr Prototype sub procedure 7T6963C setPtr dim p as word dim c as byte Sets the memory pointer for command p Parameters 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 POINTER T6963C waitReady Prototype sub procedure T6963C waitReady Pools the status byte and loops until Toshiba Glcd module is ready ums NM OOOO
189. EEP CPO DEBUG MCHECKP CPO DEBUG IBUSEP CPO DEBUG COUNTDM CPO0 DEBUG HALT CPO0 DEBUG DOZE CPO0 DEBUG LSNM CPO DEBUG NODCR CPO0 CONFIG AT CPO0 CONFIG BE CPO0 CONFIG DS CPO0 CONFIG MDU CPO CONFIG SB CPO DEBUG NOSST CPO DEBUG DEXCCODE CPO0 DEBUG VER CPO DEBUG DDBLIMPR CPO DEBUG DDBSIMPR CF TRACEOONTRGL ASD Fa TACEN SP CPO_CONFIG1_IS CPO CONFIG1 MMUSIZE CPO CONFIG1 M CPO0 CONFIG2 M CPO CONFIG3 TL CPO CONFIG3 SM CP0 CONFIG3 SP CPO_CONFIG3_VINT CPO_CONFIG3_VEIC CPO CONFIG3 ITL CPO CONFIG3 M CPO0 DEBUG DSS CP0 DEBUG DBP CPO DEBUG DDBL CPO DEBUG DDBS 161 MikroElektronika mikoBasic PRO for PIC32 Code Optimization Optimizer has been added to extend the compiler usability cut down the amount of code generated and speed up its execution The main features are Constant folding All expressions that can be evaluated in the compile time i e constant are being replaced by their results 3 5 gt 8 Constant propagation When a constant value is being assigned to a certain variable the compiler recognizes this and replaces the use of the variable by constant in the code that follows as long as the value of a variable remains unchanged Copy propagation The compiler recognizes that two variables have the same value and eliminates one of them further in the code Value numbering The compiler recognizes if two expressions yield the same result and can therefore eliminate the entire computation for one of them Dead co
190. ERNAL 2 VECTOR OxO00C IVT TIMER 3 VECTOR 0x000D IVT INPUT CAPTURE 3 VECTOR OxDO0E IVT OUTPLIT COMPARE 3 VECTOR OxOOOF IVT EXTERNAL 3 VECTOR 0x0010 IVT TIMER 4 VECTOR 0x0011 IVT INPUT CAPTURE 4 VECTOR 0x0012 IVT OUTPUT COMPARE 4 VECTOR 0x0013 IVT EXTERNAL 4 VECTOR 0x0014 IVT TIMER 5 VECTOR 0x0015 IVT INPUT CAPTURE 5 VECTOR 0x0016 IVT OUTPUT COMPARE 5 VECTOR 0x0017 IVT SPI 1 VECTOR 0x0018 IVT UART 1 VECTOR 0x0019 IVT I2C 1 VECTOR 0x0014 IVT CHANGE NOTICE VECTOR 0x001B IVT ADC VECTOR OxO01C IVT PMP VECTOR Ox001D IVT COMPARATOR 1 VECTOR OxOO1E IVT COMPARATOR 2 VECTOR OxOD1F IVT SPI 2 VECTOR 0x0020 IVT UART 2 VECTOR 0x0021 IVT I2C 2 VECTOR 0x0022 IVT FAIL SAFE MONITOR VECTOR 0x0023 IVT RTCC VECTOR fixnini24 WT PMA N VECTOR only used By checking the Only Used box you can display only the used breakpoints MikroElektronika 104 mikroBasic PRO for PIC32 Regular Expressions Introduction Regular Expressions are a widely used method of specifying patterns of text to search for Special metacharacters allow you to specify for instance that a particular string you are looking for occurs at the beginning or end of a line or contains n recurrences of a certain character Simple matches Any single character matches itself unless it is a metacharacter with a special meaning described below A series o
191. ES bit Soft I2C Sol Direction as i TRISFS3 DIE Soft I2C Sda Direction as i TRISF2 bit End Software I2C connections Soft I2C Init Soft I2C Start Rems Nothing Software I C must be configured before using this function See Soft I2C Init routine Issue START signal Soft I2C Start MikroElektronika 388 mikroBasic PRO for PIC32 Soft I2C Read Prototype sub function Soft I2C Read dim ack as word as 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 Returns One byte from the Slave Requires Soft IC must be configured before using this function See Soft_I2C_Init routine Also START signal needs to be issued in order to use this function See Soft I2C Start routine dim take as byte Read data and send the not acknowledge signal take Soft I2C Read 0 Soft I2C Write Prototype sub function Soft I2C Write dim data as byte as 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 C bus Requires Soft IC must be configured before using this function See Soft I2C Init routine Also START signal needs to be issued in order to use this function See Soft I2C Start routine dim data error as byte error Soft I2C Write data error Soft I2C W
192. 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 ENC24J600 module such as Pattern Match Magic Packet and Hash Table can not be enabled by this routine Additionaly all filters except CRC enabled with this routine will work in OR mode which means that packet will be received if any of the enabled filters accepts it This routine will change receive filter configuration on the fly It will not in any way mess with enabling disabling receive transmit logic or any other part of the ENC24J600 module The ENC247600 module should be properly cofigured by the means of SPI Ethernet 24j600 Init routine M3 MikroElektronika mikoBasic PRO for PIC32 SPI Ethernet 24j600 Disable Prototype sub procedure SPI Ethernet 24j600 Disable dim disFlt as word 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 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 i
193. Ethernet UserUDP 425 SPI Ethernet setUserHandlers 426 SPI Ethernet getlpAddress 426 Ethernet getGwlpAddress 426 SPI Ethernet getDnslpAddress 427 SPI Ethernet getlpMask 427 SPI Ethernet confNetwork 428 SPI Ethernet arpResolve 429 SPI Ethernet sendUDP 429 SPI Ethernet dnsResolve 430 MikroElektronika T mikoBasic PRO for PIC32 SPI Ethernet initDHCP 431 SPI Ethernet doDHCPLeaseTime 431 SPI Ethernet renewDHCP 432 Library Example 432 HW Connection 439 SPI Ethernet ENC24J600 Library 440 Library Dependency Tree 440 External dependencies of SPI Ethernet ENC24J600 Library 441 Library Routines 442 SPI Ethernet 24j600 Init 443 SPI Ethernet 24j600 Enable 445 SPI Ethernet 24j600 Disable 446 SPI Ethernet 24j600 doPacket 447 SPI Ethernet 24j600 putByte 447 SPI Ethernet 24j600 putBytes 448 SPI Ethernet 24j600 putConstBytes 448 SPI Ethernet 24j600 putString 449 SPI Ethernet 24j600 putConstString 449 SPI Ethernet 24j600 getByte 449 SPI Ethernet 24j600 getBytes 450 SPI Ethernet 24j600 UserTCP 450 SPI Ethernet 24j600 UserUDP 451 SPI Ethernet 24j600 setUserHandlers 452 SPI Ethernet 24j600 getlpAddress 452 SPI Ethernet 24j600 getGwlpAddress 453 SPI Ethernet 24j600 getDnslpAddress 453 SPI Ethernet 24j600 getlpMask 454 SPI Ethernet 24j600 confNetwork 454 SPI Ethernet 24j600 arpResolve 455 SPI Ethernet 24j600 sendUDP 455 SPI Ethernet 24j600 dnsResolve 456 SPI Ethernet 24j600 initDHCP 457 SPI Ethernet 24j600 doDHCPLeaseTime 458 SPI Ethernet 24j600
194. F card 211 MikroElektronika mikoBasic PRO for PIC32 e Test Start UART1 Write Line Test Start Create New File IFDEF COMPLETE EXAMPLE Create Multiple Files Open File Rewrite Open File Append Open File Read Delete File Test File Exist Create Swap File ENDIF UART1 Write Line Test End else UART1 Write Line err txt once Y longer depending on clock speed end if end HW Connection Note Cf Fat Init tries to initialize a card more than If card is not present vcc3 PIC32MX460F512L initialization may last OSCALATOR B RDO va Compact Flash Lm P m Card E EL LL LB C RET rmn mE Es ae REG 2 RES r RES D RE3 2 RE2 TT x RE REO e Bm m 10K 4 vcc Pin diagram of CF memory card MikroElektronika 218 mikroBasic PRO for PIC32 Epson S1D13700 Graphic Lcd Library The mikroBasic PRO for PIC32 provides a library for working with Glcds based on Epson S1D13700 controller The S1D13700 Glcd is capable of displaying both text and graphics on an LCD panel The S1D13700 Glcd allows layered text and graphics scrolling of the display in any direction and partitioning of the display into multiple screens It includes 32K bytes of embed
195. FO VERTICAL Vertical orientation TFT module needs to be initialized See the TFT Init routine ESTER TFT Set Font TFT defaultFont CL BLACK FO HORIZONTAL 931 MikroElektronika mikoBasic PRO for PIC32 TFT Write Char Prototype sub procedure TFT Write Char dim ch x y as 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 TFrweite Chara 2229 Sd TFT Write Text Prototype sub procedure TFT Write Text dim byref text as string dim x y as word 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 EO TFT Write Text TFT LIBRARY DEMO WELCOME MikroElektronika 538 mikroBasic PRO for PIC32 TFT Fill Screen Prototype sub procedure TFT Fill Screen dim color as 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 Tet rinp screen mac CS MikroElektronika 939 mikoBasic PRO for PIC32 TFT Dot Prototype sub procedure TFT Dot dim x y as integer dim color as word Description Draws a dot on the TFT at coor
196. 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 ple SPI Ethernet H l String MikroElektronika 438 mikroBasic PRO for PIC32 External dependencies of SPI Ethernet ENC24J600 Library The following variables must be defined in all projects using SPI Ethernet Description ENC24J600 Library dim SPI Ethernet 24j600 CS as F dim SPI Ethernet 24j600 CS as sbit sbit sfr external PNC24J600 chip Select pit at RCI bit dim SPI Ethernet 243600 CS Direction of the ENC24J600 chip dim SPI Ethernet 243600 CS Direction Direction as sbit sfr external select pin as sbit at TRISC1 bit The following routines must be defined in all project using SPI Ethernet ENC24J600 Description Library sub function SPI Ethernet 245600 UserTCP dim byref remoteHost as byte 4 dim remotePort as word dim localPort as word dim regLength as word dimbyref flags as TEthj 600PktFlags as word Refer to the library example at TCP request handler the bottom of this page for code implementation sub function SPI Ethernet 245600 UserUDP dim byref remoteHost as byte 4 dim remotePort as word Refer to the library example at dim destPort as word UDP request handler the bottom of this page for code dim reqLength as word implementation dimbyref flags as TEthJ600PktFlags as word 439 MikroElektronika
197. GB and are used in digital cameras digital camcorders handheld computers media players mobile phones GPS receivers video games and PDAs Secure Digital High Capacity Card SDHC Secure Digital High Capacity SD 2 0 is an extension of the SD standard which increases card s storage capacity up to 32 GB by using sector addressing instead of byte addressing in the previous SD standard SDHC cards share the same physical and electrical form factor as older SD 1 x cards allowing SDHC devices to support both newer SDHC cards and older SD cards The current standard limits the maximum capacity of an SDHC card to 32 GB Important Routines for file handling can be used only with FAT16 file system Library functions create and read files from the root directory only Library functions populate both FAT1 and FAT2 tables when 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
198. Glcd Set Font G8Font Gled 5x7 5 7 32 Change font someText 5x7 Font SPI Glcd Write Text someText 5 4 2 Write string Delay2s SPI Glcd Set Font GFont Gled System5x7 5 7 32 Change font someText 5x7 Font v2 SPI Glcd Write Text someText 50 6 2 Write string Delay2s wend end an MikroElektronika mikoBasic PRO for PIC32 HW Connection Left side Right side wr X axis x 63 x 0 PIC32MX460F512L 5 VCC3 ovcca SPI Glcd HW connection MikroElektronika 472 mikroBasic PRO for PIC32 SPI Lcd Library The mikroBasic PRO for PIC32 provides a library for communication with Lcd with HD44780 compliant controllers in 4 bit mode via SPI interface For creating a custom set of Lcd characters use Lcd Custom Character Tool Important When using this library with PIC32 family MCUs be aware of their voltage incompatibility with certain number of 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 Lcd Library For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by using the SPI Set Active routine See the SPI Library functions This Library is designed to work with the mikroElektronik
199. Glcd module needs to be initialized See SPI T6963C Config routine enable text displaying SPI T6963C text 1 MikroElektronika 500 mikroBasic PRO for PIC32 SPI T6963C cursor Prototype sub procedure SPI T6963C cursor dim n as word Description Set cursor on off Parameters n on off parameter Valid values 0 set cursor off and 1 set cursor on Nothing Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine set cursor on SPI T6963C cursort 1 SPI T6963C cursor blink Prototype sub procedure SPI T6963C cursor blink dim n as word Description Enable disable cursor blinking Parameters n cursor blinking enable disable parameter Valid values 0 disable cursor blinking and 1 enable cursor blinking Nothing Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine enable cursor blinking SPI T6963C cursor biink 1 Library Example The following drawing demo tests advanced routines of the SPI T6963C Glcd library Hardware configurations in this example are made for the LV 32MX v6 board and PIC32MX460F512L Copy Code To Clipboard program SPI T6963C 240x128 include Lib SPIT6963C Const dim Port Expander module connections SPExpanderRST as sbit at LATD8 bit for writing to output pin always use latch SPExpanderCS as sbit at LATD9 bit for writing to output pin always use latch SPExpanderRST Direction
200. HARACTER HEIGHT then MikroElektronika 506 mikroBasic PRO for PIC32 cposy 0 end if end if SPI T6963C set cursor cposx cposy Delay ms 100 wend end HW Connection ovccs cca Adjustment SPI T6963C Glcd HW connection 907 MikroElektronika mikoBasic PRO for PIC32 T6963C Graphic Lcd Library The mikroBasic PRO for PIC32 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 For creating a custom set of Glcd images use Glcd Bitmap Editor Tool Important When using this library with PIC32 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
201. HID Read as byte Receives message from host and stores it in the Read Buffer Parameters None 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 while HID Read HID_Write Prototype sub function HID Write dim writebuff as byte dim len as byte as byte Description 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 ni If the data transmitting has failed the function returns 0 Otherwise it returns number of transmitted bytes USB HID needs to be enabled before using this function See HID Enable penne while HID Write writebuff 64 Notes Function call needs to be repeated as long as data is not successfuly sent MikroElektronika 512 mikroBasic PRO for PIC32 HID Disable ems Nothing USB HID needs to be enabled before using this function See HID Enable Example HID Disable C USB Interrupt Proc This routine is used for servicing various USB bus events Should be called inside USB interrupt routine sub procedure USBlInterrupt iv IVT ADDR USBlIINTERRUPT USB Interrupt Proc end sub Do not use this function with USB Polling Proc only one should be used
202. HITE mms Ren DTUEITEEEEEU Ee rectangle 20 20 219 107 T6963C WHITE mas MR RR RR T6963C rectangle round edges Prototype sub procedure T6963C rectangle round edges dim x0 y0 xl yl radius as integer dim pcolor as 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 y1 y coordinate of the lower right rectangle corner round radius radius of the rounded edge PEU color parameter Valid values 16963C 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 91 MikroElektronika mikoBasic PRO for PIC32 T6963C rectangle round edges fill Prototype sub procedure T6963C rectangle round edges fill dim x0 y0 xl yl radius as integer dim pcolor as byte Draws a filled rounded edge rectangle on Glcd Parameters x0 x coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner round radius radius of the rounded edge ee color parameter Valid values T6963C_ BLACK and T6963C WHITE Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C
203. I CONFIG FLAGS as byte CANSPISetOperationMode CANSPI MODE CONFIG OxFF set CONFIGURATION mode CANSPI1 module mast 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 CANSPI CONFIG FLAGS 22 MikroElektronika mikoBasic PRO for PIC32 CANSPISetMask Prototype sub procedure CANSPISetMask dim CANSPI MASK as byte dim val as longint dim CANSPI CONFIG FLAGS as byte Description Configures mask for advanced filtering of messages The parameter value is bit adjusted to the appropriate mask registers Parameters CANSPI MASK CAN module mask number Valid values CANSPT MASK constants See CANSPI MASK constants val mask register value This value is bit adjusted to appropriate buffer mask registers CANSPI CONFIG FLAGS selects type of message to filter Valid values CANSPI CONFIG ALL VALID MSG CANSPI CONFIG MATCH MSG TYPE amp CANSPI CONFIG STD MSG CANSPI CONFIG MATCH MSG TYPE amp CANSPI CONFIG XTD MSG See CANSPI_CONFIG_FLAGS constants Requires The CANSPI module must be in Config mode otherwise the function will be ignored See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has
204. I MASTER SPI 8 BIT 16 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE LOW SPI IDLE 2 ACTIVE SPI Ethernet Init myMacAddr myIpAddr SPI Ethernet FULLDUPLEX x init ethernet module SPI Ethernet setUserHandlers 8SPI Ethernet UserTCP SPI Ethernet UserUDP set user handlers dhcp will not be used here so use preconfigured addresses SPI Ethernet confNetwork ipMask gwIpAddr dnsIpAddr while TRUE do forever SPI Ethernet doPacket process incoming Ethernet packets amp x Bah 3 wend end add your stuff here if needed SPI Ethernet doPacket must be called as often as possible otherwise packets could be lost HW Connection VCC3 3 VCC3 3 VCC3 3 VCC3 3 OSCILLATOR muuuuumuu uuu tium ovcC3 ovcc3 A31 mikoBasic PRO for PIC32 SPI Ethernet ENC24J600 Library The ENC24J3600 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
205. I T6963C rectangle round edges dim x0 as integer dim y0 as integer dim x1 as integer dim yl as integer dim radius as integer dim pcolor as 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 y1 y coordinate of the lower right rectangle corner round radius radius of the rounded edge pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C rectangle round edges 20 20 219 107 12 SPI T6963C WHITE SPI T6963C rectangle round edges fill Prototype sub procedure SPI T6963C rectangle round edges fill dim x0 as integer dim yO as integer dim x1 as integer dim yl as integer dim radius as integer dim pcolor as byte Draws a filled rounded edge rectangle on Glcd Parameters x0 x coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner round radius radius of the rounded edge pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C rectangle round edges fill 20 20 219 107 1
206. IDLE Loop until MMC is initialized mc Init Reinitialize the SPI module at higher speed change primary prescaler SPI1 Init Advanced SPI MASTI SPI 8 BIT SPI PRESCALE SEC 1 SPI PRESCALE PRI 4 SPI SS DISABLI SPI DATA SAMPLE MIDDLE SPI CLE IDL HIGH SPI ACTIVE 2 IDLI MikroElektronika 338 mikroBasic PRO for PIC32 Mmc Read Sector Prototype sub function Mmc Read Sector dim sector as longword dim byref dbuff as byte 512 as word The function reads one sector 512 bytes from MMC card Parameters sector MMC SD card sector to be read dbuf f buffer of minimum 512 bytes in length for data storage if reading was successful if an error occurred MMC SD card must be initialized See Mmoc Init read sector 510 of the MMC SD card dim error as word sectorNo as longword dataBuffer as byte 512 sectorNo 510 rror Mmc Read Sector sectorNo dataBuffer Mmc Write Sector Prototype sub function Mmc Write Sector dim sector as longword dim byref data as byte 512 as word The function writes 512 bytes of data to one MMC card sector Parameters sector MMC SD card sector to be written to dbuf f 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
207. II Chart EEPROM Editor Graphic Lcd Bitmap Editor HID Terminal Interrupt Assistant Lcd Custom Character Seven Segment Editor UDP Terminal USART Terminal Active Comments New Active Comment Renaming Active Comment Deleting Active Comment Export Project Jump To Interrupt Regular Expressions Introduction Simple matches Escape sequences Character classes Metacharacters Metacharacters Line separators Metacharacters Predefined classes Metacharacters Word boundaries Metacharacters Iterators Metacharacters Alternatives 110 MikroElektronika mikroBasic PRO for PIC32 Metacharacters Subexpressions 110 Metacharacters Backreferences 110 Keyboard Shortcuts 111 CHAPTER 3 113 mikroBasic PRO for PIC32 Command Line Options 113 CHAPTER 4 115 mikrolCD In Circuit Debugger 115 Introduction 115 mikrolCD Debugger Options 117 Debugger Options 117 mikrolCD Debugger Example 118 mikrolCD Debugger Windows 122 Debug Windows 122 Breakpoints Window 122 Watch Values Window 122 RAM Window 124 Stopwatch Window 124 EEPROM Watch Window 125 Code Watch Window 126 CHAPTER 5 127 Software Simulator Overview 127 Software Simulator 128 Software Simulator Debug Windows 129 Debug Windows 129 Breakpoints Window 129 Watch Values Window 129 RAM Window 131 Stopwatch Window 131 EEPROM Watch Window 132 Code Watch Window 133 Software Simulator Debugger Options 134 Debugger Options 134 CHAPTER 6 135 mikroBasic PRO for PIC32 Spec
208. ILTER OFF Initialize SPI1 module SPI2 Init CANSPIInitialize 1 3 3 3 1 Can Init Flags initialize external CANSPI module CANSPISetOperationMode CANSPI MODE CONFIG OxFF set CONFIGURATION mode CANSPISetMask CANSPI MASK B1 1 CANSPI CONFIG XTD MSG set all maskli 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 node ID CANSPISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode while TRUE endless loop Msg Rcvd CANSPIRead Rx ID RxTx Data Rx Data Len Can Rcv Flags receive message if Rx ID ID 1st and Msg Rcvd then if message received check id 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 if wend end 291 MikroElektronika mikoBasic PRO for PIC32 HW Connection za e x o la Se PIC32MX460F512L Shielded I twisted pair 7 Example of interfacing CAN transceiver MCP2510 with MCU via SPI interface e 2zr0 2520 ponora x mabn oVCC3 2885z amp uuu ovcca OSCKRLATOR p lt VCC3 298 mikroBasic PRO for PIC32 Compact Flash Library The Compact Flash Library provides routines for accessing data on Compact Flash card abbr CF further in
209. INESS 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 ASSOCIATESHASBEENADVISED 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 GOVERNED BY THE TERMS OF THAT AGREEMENT HIGH RISK ACTIVITIES Software is not fault tolerant and is not designed manufactured or intended for use or resale as on line control equipment in hazardous environments requiring fail safe performance such as in the operation of nuclear facilities aircraft navigation or communication systems air traffic control direct life support machines or weapons systems in which the failure of Software could lead directly to death personal injury or severe physical or environmental damage High Risk Activities mikroElektronika Associates and its suppliers specifically disclaim any expressed or implied warranty of fitness for High Risk Activities GENERAL PROVISIONS This statement may only be modified in writing signed by you and an authorised officer of m
210. L 1000 8 miliseconds Send from file 00 5 5 8 5 25 ay mikoBasic PRO for PIC32 Active Comments The idea of Active Comments is to make comments alive and give old fashioned comments new meaning and look From now on you can assign mouse event on your comments and tell your comments what to do on each one For example on left mouse click open some web address in your browser on mouse over show some picture and on mouse double click open some file Let suppose we are writing a example for a GSM GPSR module which is connected to EasyPIC6 and we would like to provide a photo of our hardware jumpers cables etc within the example Also it would be also nice to put some documentation about chip we are using and a GSM module extra board Now we can have all those things defined in one single comment using Active Comment Editor New Active Comment When you start Active Comment Editor for the first time from the View menu from editor s pop up menu or by pressing Ctrl Alt P you will get an empty editor Active Comments Editor Select Active Comment Active Comment Actions New Rename Delete Properties Add Image to Project AdG File To Project By clicking the New button you are prompted to enter a name for the comment MikroElektronika 94 mikroBasic PRO for PIC32 Active Comments Editor Enter comment name activeComment
211. LACK T6963C Rectangle Round Edges Fill 30 30 209 97 12 T6963C WHITE T6963C Rectangle Round Edges Fill 40 40 199 87 12 T6963C BLACK T6963C Rectangle Round Edges Fill 50 50 189 77 12 T6963C WHITE ENDIF Y 3 Draw a cross Y IFDEF LINE DEMO T6963C line 0 0 239 127 T6963C WHIT T6963C I1ine 0 127 239 0 T6963C WHIT ENDIF E Fl Y x Draw circles Y IFDEF LINE DEMO T6963C circle 120 64 10 T6963C WHITI T6963C circle 120 64 30 T6963C WHITI T6963C circle 120 64 50 T6963C WHITI T6963C circle 120 64 70 T6963C WHITI E Ed Ed Hd d T6963C circle 120 64 90 T6963C WHITI T6963C circle 120 64 110 T6963C WHIT T6963C circle 120 64 130 T6963C WHIT ENDIF d E mo d 521 MikroElektronika mikoBasic PRO for PIC32 Y 3 Draw filled circles Y IFDEF FILL DEMO T6963C circle fill 120 T6963C circle fil1 120 T6963C circle fil1 120 T6963C circle fil1 120 T6963C circle fill 120 T6963C circle fill 120 T6963C circle fil1 120 T6963C circle fil1 120 T6963C circle fill 120 T6963C circle fil1 120 T6963C circle fil1 120 T6963C circle fil1 120 ENDIF Delay ms 1000 image while TRUE if T6963C image mikrol T6963C displayGrPanel 1 Delay ms 1000 IFDEF PARTIAL IMAGE DEMO T6963C grFill 0 T6963C PartiallImage 0
212. LACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine pM SPI T6963C circle fill 120 64 110 SPI T6963C WHITE me Ne MikroElektronika 494 mikroBasic PRO for PIC32 SPI T6963C image Prototype sub procedure SPI T6963C image dim pic as const byte Description Displays bitmap on Glcd Parameters pic image to be displayed Bitmap array can be located in both code and RAM memory due to the mikroBasic PRO for PIC32 pointer to const and pointer to RAM equivalency Nothing Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Image dimension must match the display dimension Use the integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd SPI T6963C Partiallmage Prototype sub procedure SPI T6963C Partiallmage dim x left y top width height picture width picture height as word const image as byte Description Displays a partial area of the image on a desired location Parameters x left x coordinate of the desired location upper left coordinate y top y coordinate of the desired location upper left coordinate width desired image width height desired image height picture width width of the original image picture height height of the original image image image to be displayed Bitmap array can be locate
213. MCU The bit associated with RB that you ve commanded to MODIFY is changed and then the microcontroller WRITES all 8 bits RB7 RBO back to the PORTB register During the first reading of the PORT register you will be reading the actual state of the physical pin The problem arises when an output pin is loaded in such a way that its logic state is affected by the load Instances of such loads are LEDs without current limiting resistors or loads with high capacitance or inductance For example if a capacitor is attached between pin and ground it will take a short while to charge when the pin is set to 1 On the other hand if the capacitor is discharged it acts like a short circuit forcing the pin to 0 state and therefore a read of the PORT register will return 0 even though we wrote a 1 to it Lets analyze the following example PORTB BO 1 PORTB B1 1 Assume that the PORTB is initially set to zero and that all pins are set to output Let s say we connect a discharged capacitor to RBO pin The first line PORTB BO 1 will be decoded like in this way READ PORTB is read STORE Data is stored inside a temporary internal register in the MCU Store read value gt 0000000 s 1 Read from pins boou c Discharged REGISTER T capacitor ETEC pep pe Discharged capacitor 00000000 00000000 C I MikroElektronika 172 mikroBasic PRO for PIC32 Actual voltage levels on MCU pi
214. MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page g set the CANSPI module into configuration mode wait inside CANSPISetOperationMode until this mode is set CANSPISetOperationMode CANSPI MODE CONFIG OxFF MikroElektronika 244 mikroBasic PRO for PIC32 CANSPIGetOperationMode constants or device datasheet for operation mode codes Requires The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page check whether the CANSPI module is in Normal mode and if it is do something if CANSPIGetOperationMode _CANSPI MODE NORMAL then end if CANSPIInit Prototype sub procedure CANSPIInit dim SJW BRP PHSE EG2 PROPSEG CANSPI _ CONFIG FLAGS as char Description Initializes the CANSPI module Stand Alone CAN controller in the CANSPI module is set to Disable CAN capture Continue CAN operation in Idle mode Do not abort pending transmissions Fcan clock 4 Tcy Fosc Baud rate is set according to given parameters CAN mode Normal Filter and mask registers IDs are set to zero Filter and mask message frame type is set according to CANSPI_ CONFIG FLAGS value SAM SEG2PHTS WAKFIL and DBEN bits are set according to C
215. P Ctrl S Ctrl Shift S Ctrl V Ctrl X Ctrl Y Ctrl Z Ctrl Shift Z Ctrl Shift number Ctrl Shift l Ctrl Shift U Jump To Interrupt Indent Selection 4 gt Ww Shift TAB Alt Select Ctrl Alt Select Alt Left Arrow Alt Right Arrow Ctrl Alt L Ctrl Alt U Ctrl Alt T 109 MikroElektronika mikoBasic PRO for PIC32 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 MikroElektronika 110 mikroBasic PRO for PIC32 CHAPTER 3 mikroBasic PRO for PIC32 Command Line Options Usage mBPIC32 exe lt opts gt lt opts gt infile lt opts gt lt opts gt Infile can be of mbas emcl and pld type The following parameters are valid P devicename MCU for which compilation will be done FO lt oscillator gt Set oscillator in MHz SP directory Add directory to the search path list filename Output files generated to file path specified by filename B directory Save compiled binary files amp mc1 to directory O Miscellaneous output options DBG Generate debug info SF Short message format Y Dynamic link for string literals RA Rebuild all sources in project L Check and rebuild new libraries DL Build all files as libraries LHF Generate Long hex format F Project file name H filename Full EEPROM HEX file name wi
216. RO for PIC32 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 CANSPIInit 1l 1 3 3 1l init 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 as byte 03 _CANSPI_TX PRIORITY 0 as byte SFC XXXXXX00 _CANSPI_TX PRIORITY 1 as byte FD XXXXXX01 CANSPI TX PRIORITY 2 as byte FE XXXXXX10 CANSPI TX PRIORITY 3 as byte SFF XXXXXX11 CANSPI TX FRAME BIT as byte 08 CANSPI TX STD FRAME as byte SFF XXXXX1XX CANSPI TX XTD FRAME as byte SF7 XXXXXOXX CANSPI TX RTR BIT as byte 40 CANSPI TX NO RTR FRAME as byte SFF v XIXXXXXX CANSPI TX RTR FRAME as byte SBF 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 CANSPI TX PRIORITY 0 and CANSPI TX XTD FRAME and CANSPI TX NO RTR FRAM PJ 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 partic
217. 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 dim RS485 rxtx pin as sbit at RF2 bit dim RS485 rxtx pin direction as 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 Notes None MikroElektronika 380 mikroBasic PRO for PIC32 RS485Slave Receive Prototype sub procedure RS485Slave Receive dim byref data as byte 20 Description Receives messages from Master If Slave address and Message address field don t match then the message will be discarded Messages are multi byte so this routine must be called for each byte received Parameters data buffer 6 byte buffer for storing received data in the following manner data buffer 0 2 message content data buffer 3 number of message bytes received 1 3 data buffer 4 is setto 255 when message is received data buffer 5 is setto 255 if error has occurred The routine automatically adjusts data 4 and data 5 upon every received message These flags need to be cleared by software Nothing Requires MCU must be initialized as a Slave for RS 485 communication See RS485Slave Init dim msg as byte 8 RS485Slave Read msg RS485Slav
218. SET Prototype sub procedure CPO SET dim const register as TCPOREG dim Value as longword Function sets the value of the coprocessor register or part of the register based upon the register argument Parameters register Register or register part must be a constant from the enumerated built in constants list which can be found at the bottom of this page value Register Value CPO SET CPO CONFIG 0x1A2C0000 Enablelnterrupts eum Noting EnableInterrupts Disablelnterrupts ems Noting Example pisare LL etes oe O Oooo CPO CONFIG3 CPO DEBUG CPO TRACECONTROL CPO TRACECONTROL2 CPO USERTRACEDATA CPO TRACEBPC CPO DEBUG2 CPO DEPC CPO0 ERROREPC CPO DESAVE MikroElektronika 160 mikroBasic PRO for PIC32 GEUREA M CPO CAUSE DC CPO0 CAUSE CE CPO CAUSE TI CPO0 CAUSE BD CPO PRID REVISION CPO PRID PATCHREV CPO PRID MINORREV CPO PRID MAJORREV CPO PRID PROCESSORID CPO PRID COMPANYID CPO CAUSE IP6 CPO CAUSE IP7 CPO CAUSE WP CPO CAUSE IV CPO CAUSE PCI CPO0 EBASE CPUNUM CPO0 EBASE EBASE CPO0 CONFIG KO CPO0 CONFIG MT CPO CONFIG AR CPO0 CONFIG UDI CPO0 CONFIG KU CPO0 CONFIG1 M CPO0 CONFIG1 FP CPO CONFIG1 EP CPO CONFIG1 CA CPO0 CONFIG1 WR CP0 CONFIG1 PC CPO0 CONFIG1 MD CPO CONFIG1 C2 CPO CONFIG1 DA CPO0 CONFIG1 DL CPO0 CONFIG1 DS CPO0 CONFIG1 IA CPO CONFIG1 IL CPO DEBUG DIB CPO0 DEBUG DINT CPO0 DEBUG DIBIMPR CPO_DEBUG_R CPO DEBUG SST CPO DEBUG EXI CPO DEBUG DBUSEP CPO DEBUG CACH
219. Set PORTB value to zero performs I2C initialization EPROM 24C02 RdSingle i 315 MikroElektronika mikoBasic PRO for PIC32 Keypad Library mikroBasic PRO for PIC32 provides a library for working with 4x4 keypad The library routines can also be used with 4x1 4x2 or 4x3 keypad For connections explanation see schematic at the bottom of this page External dependencies of Keypad Library The following variable must be defined in all projects Par y Description using Keypad Library dim keypadPort as word sfr external Keypad Port dim keypadPort as word at PORTB dim keypadPort Direction as word sfr external Keypad Port dim keypadPort Direction as word at TRISB Library Routines Keypad Init Keypad Key Press Keypad Key Click Keypad Init Reums non LL Requires Global variable keypadPort Keypad port must be defined before using this function Keypad module connections dim keypadPort as word at PORTB dim keypadPort Direction as word at TRISB End Keypad module connections Keypad Init Notes The Keypad library uses lower byte bits lt 7 0 gt of keypadPort MikroElektronika 316 mikroBasic PRO for PIC32 Keypad Key Press Reads the key from keypad when key gets pressed The code of a pressed key 1 16 If no key is pressed returns 0 Port needs to be initialized for working with the Keypad library see Keypad Init dim kp as word k
220. Spi Lcd8 Cmd LCD CLEAR Clear display Spi Lcd8 Cmd LCD CURSOR OFF Turn cursor off Spi Lcd8 Out 1 6 mikroE t Print text to LCD Ist row 6th column Spi Lcd8 Chr CP Append it Spi Lcd8 Out 2 1 text Print text to LCD 2nd row 1st column Spi Lcd8 Out 3 1 mikroE For LCD with more than two rows Spi Lcd8 Out 4 15 mikroE For LCD with more than two rows Delay ms 2000 Moving text for counter 0 to 3 Move text to the right 4 times Spi Lcd8 Cmd LCD SHIFT RIGHT Move Delay next counter 483 MikroElektronika mikoBasic PRO for PIC32 for counter 0 to 6 Move text to the right 7 times Spi Lcd8 Cmd LCD SHIFT RIGHT Move Delay next counter wend end OSCILLATOR lt 9 Dopnnnnnnnpn 2 o VCC3 Q g o o w 5K ovoc3 SPI Lcd8 HW connection MikroElektronika 484 mikroBasic PRO for PIC32 SPI T6963C Graphic Lcd Library The mikroBasic PRO for PIC32 provides a library for working with Glcds based on TOSHIBA T6963C controller via SPI interface The Toshiba T6963C is a very popular Lcd controller for the use in small graphics modules It is capable of controlling displays with a resolution up to 240x128 Because of its low power and small outline it is most suitable for mobile applications such as PDAs MP3 players or mobile measurement equipment Although this controller is small it has a capability
221. TA SAMPLE MIDDLE SPI CLK IDLE LOW 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 prc 1 is IRD bit 0 is CD bit 4 is RST chip enable reverse on 8x8 font internaly set in library Initialize SPI Toshiba 240x128 SPI T6963C Config 240 128 8 0 2 1 0 4 Delay ms 1000 Enable both graphics and text display at the same time SPI PRESCALE SEC 1 SPI PRESCALE PRI 4 SPI IDLE 2 ACTIVE MikroElektronika 902 mikroBasic PRO for PIC32 SPI T6963C graphics 1 SPI T6963C text 1 i Text messages SPI T6963C write text txt 0 0 SPI T6963C ROM MODE XOR SPI T6963C write text txtl 0 15 SPI T6963C ROM MODE XOR Ve Cursor Vs SPI T6963C cursor height 8 8 pixel height SPI T6963C set cursor 0 0 move cursor to top left SPI T6963C cursor 0 cursor off Ve Draw solid boxes Tw SPI T6963C box 0 0 239 8 SPI T6963C WHITE SPI T6963C box 0 119 239 127 SPI T6963C WHITE Y Draw rectangles Y IFDEF LINE DEMO SPI T6963C rectangle SPI T6963C rectangle SPI T6963C rectangle SPI T6963C rectangle ENDIF 0 0 239 127 SPI T6963C WHITE 20 20 219 107 SPI T6963C WHITI 40 40 199 87 SPI T6963C WHITI 60 60 179 67 SPI T6963C WHITI F E F a Y Draw ro
222. To enable servicing through interrupt USB_ INTERRUPT constant should be set it is set by default in descriptor file 913 MikroElektronika mikoBasic PRO for PIC32 USB Polling Proc Description This routine is used for servicing various USB bus events It should be periodically preferably every 100 microseconds Requires Nothing while TRUE USB Polling Proc kk HID Read if kk lt gt 0 then for cnt 0 to 63 writebuff cnt readbuff cnt next cnt HID Write writebuff 64 end if wend Do not use this functions with USB_Interrupt_Proc To enable servicing by polling USB_ INTERRUPT constant should be set to 0 it is located in descriptor file Gen_Enable Prototype sub procedure Gen Enable dim readbuff as byte dim writebuff as byte Description Initialize the USB module of the MCU Parameters readbuff Read Buffer writebuff Write Buffer MikroElektronika 574 mikroBasic PRO for PIC32 Gen Read Prototype sub function Gen Read dim readbuff as byte dim length as byte dim ep as byte as 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 Se
223. ToRGB dim color as word dim rgb red rgb green rgb blue as byte Description Converts true color into 5 6 5 RGB format Parameters color true color to be converted rgb red red component of the input color rgb green green component of the input color rgb blue blue component of the input color TFT module needs to be initialized See the TFT Init routine Example TFT Colorl6bitToRGB start color Gred start green start blue_ start MikroElektronika 548 mikroBasic PRO for PIC32 HW Connection TFT 320x240 display MI0283QT2 TFT HW connection 949 mikoBasic PRO for PIC32 Touch Panel Library The mikroBasic PRO for PIC32 provides a library for working with Touch Panel Library Dependency Tree Touch Panel ADC External dependencies of Touch Panel Library The following variables must be defined in all Description projects using Touch Panel Library dim DriveA as sbit sfr external dim DriveA as sbit at LATC13 bit dim DriveB as sbit sfr external dim DriveB as sbit at LATC14 bit dim DriveA Direction as sbit sfr Direction of the DriveA pin dim DriveA Direction as sbit at external TRISC13 bit dim DriveB Direction sbit sfr Direction of the DriveB pin dim DriveB Direction as sbit at external TRISC14 bit Library Routines TP_Init TP_Set_ADC_Threshold TP_Press_Detect TP_Get_Coordinates TP_Calibrate_Bottom_Left TP_Calibr
224. U uses virtual addresses to address the peripherals which means that to access the PIC32MX s peripherals we and the CPU must be operating within the virtual boundaries of KSEG1 The PIC32MX s CPU also uses virtual addressing to fetch and execute program memory instructions If you look closely you ll see that the physical address region between the INTERNAL RAM at physical address 0x00000000 and the INTERNAL BOOT FLASH beginning at physical address 0x1FC00000 is matched up with the virtual memory schemes of KSEGO and KSEG1 The PIC32MX CPU maps the virtual areas of KSEGO and KSEG1 against the same physical memory area beginning at physical address 0x00000000 Because both the KSEGO and KSEG1 virtual segments point to the same physical memory area the PIC32MX CPU can execute instructions from either the KSEGO or KSEG1 virtual memory segment depending on the cacheable status of the application KSEGO and USEG KSEG are cacheable while KSEG1 is not cacheable Related topics Accessing individual bits SFRs Memory type specifiers MikroElektronika 170 mikroBasic PRO for PIC32 Memory Type Specifiers The mikroBasic PRO for PIC32 supports usage of all memory areas Each variable may be explicitly assigned to a specific memory space by including a memory type specifier in the declaration or implicitly assigned The following memory type specifiers can be used code data rx reserved for compiler purposes only SE
225. Uri www mikroe com n Image Easy GS5M GPRS jpg File None OnLeftClick Alt Openurl OnRightClick None OnDblClick 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 I V acractiveConment 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 ac activeComment MikroElektronika mikoBasic PRO for PIC32 There is another way to add an active comment to an active project You can do it simply by typing a comment in old fashion way except with ac prefix So it would look like this ff ac activeComment4 Add Comment To Project Notice that when you stop typing Add Comment To Project button will show By clicking on it you will open Active Comment Editor and comment name will be already set so you need only to adjust attributes and settings After saving you can always edit your active comment by Active Comment Editor and switch between comments directly from editor If you remove a file from the Project Manager or add an Active Comment File which contains information about the file which is
226. a s Serial Lcd Adapter Board pinout see schematic at the bottom of this page for details Library Dependency Tree r Port Expander SPI Lcd 1 Lcd Constants External dependencies of SPI Lcd Library The implementation of SPI Lcd Library routines is based on Port Expander Library routines External dependencies are the same as Port Expander Library external dependencies Library Routines SPI Lcd Config SPI Lcd Out SPI Lcd Out Cp SPI Lcd Chr SPI Lcd Chr Cp SPI Lcd Cmd 473 MikroElektronika mikoBasic PRO for PIC32 SPI Lcd Config Rems Noting 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 dim SPExpanderRST as sbit at LATFO bit SPExpanderCS as sbit at LATF1 bit SPExpanderRST Direction as sbit at TRISFO bit SPExpanderCS Direction as sbit at TRISF1 bit End Port Expander module connections If Port Expander Library uses SPI1 module SPIl Init v Initialize SPI module used with PortExpander SPI Lcd Config 0 initialize lcd over spi interface SPI Lcd Out Prototype sub procedure SPI Lcd Out dim row column as byte dim byref tex
227. aan up io wa Sa a m ELE am roe 4 o OY r tons m y m v ecc co lt A oc om lt a me en Ld Seve Pedes th gt b r poms nas DID i ana a E mo w a ze o gt IX PR E og P _ dn deni P m t bem E T fem Pei 2 t a os om 4 pol mikroBasic PRO for PIC32 IDE MikroElektronika 28 mikroBasic PRO for PIC32 Introduction to mikroBasic PRO for PIC32 The PIC32 is a 32 bit family of general purpose microcontrollers This is the Microchip s first inherent 32 bit data microcontroller family It builds upon the MIPS M4K 32 bit core offering high performance hardware multiply divide unit programmable user and kernel memory partition through an unified 4GB virtual memory space with powerful peripherals to address a wide range of applications Having a wide range of application being prized for its efficiency PIC32 MCUs are a natural choice for developing embedded systems mikroBasic PRO for PIC32 provides a successful match featuring highly advanced IDE ANSI compliant compiler broad set of hardware libraries comprehensive documentation and plenty of ready to run examples Features mikroBasic PRO for PIC32 allows you to quickly develop and deploy complex applications Write your source code using the built in Code Editor Code and Parameter Assistants Code Folding Syntax Highlighting Auto Correct Code
228. act Flash i Compact Flash FAT16 c Type 259 MikroElektronika mikoBasic PRO for PIC32 External dependencies of Compact Flash Library Compact Flash Data Port dim CF Data Port as byte at PORTD Ready signal line dim CF RDY as sbit at RB7 bit The following variables must be defined in all projects using Compact Flash Library dim CF Data Port as byte sfr external dim CF RDY as sbit sfr external dim CF WE as external Description bit sf z A sees 9 7 Write Enable signal line dim CF WE as sbit at LATB6 bit dim CF OE i 1 sain a Soa pis Output Enable signal line dim CF OE as sbit at LATB5 bit external zd A Chip Detect signal line dim CF CD1 as sbit at RB4 bit Chip Enable signal line dim CF CEl1 as sbit at LATB3 bit PM UOI UM ONDES NE Address pin 2 dim CF A2 as sbit at LATB2 bit external ME dim CF CDl1 as sbit sfr external dim CF CEl as sbit sfr external dim CF Al external dim CF A0 as external dim CF RDY direction as sbit sfr external Direction of the Ready pin dim CF RDY direction TRISB7 bit Se HD ER Address pin 1 dim CF Al as sbit at LATB1 bit an OBEN Address pin 0 dim CF A0 as sbit at LATBO bit as sbit at dim CF WE direction as i dim CF WE direction as sbit at TRISB6 A oT Direction of the Write Enable pin sbit sfr external bat dim CF OE direction sbit sfr external dim CF CD1 direction as sbit sfr external
229. ad 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 Sound sub procedure Tonel Sound Play 659 250 Frequency end sub 659Hz duration 250ms sub procedure Tone2 Sound Play 698 250 Frequency 698Hz duration 250ms end sub sub procedure Tone3 Sound Play 784 250 Frequency 784Hz duration 250ms end sub sub procedure Melody Plays the melody Yellow house Tonel Tone2 Tone3 Tone3 Tonel Tone2 Tone3 Tone3 Tonel Tone2 Tone3 Tonel Tone2 Tone3 Tone3 Tonel Tone2 Tone3 Tone3 Tone3 Tone2 Tone2 Tonel end sub sub procedure ToneA Tones used in Melody2 function Sound Play 880 50 end sub MikroElektronika 40 mikroBasic PRO for PIC32 sub procedure ToneC Sound Play 1046 50 end sub Fl sub procedure ToneE Sound Play 1318 50 end sub sub procedure Melody2 dim counter as byte for counter 9 to 1 step 1 ToneA ToneC lr oneE next counter end sub main CHECON 0x32 ADIPCFG OxFFFF TRISB OxF8 Sound Init PORTD 3 Sound Play 880 1000 if But while TRUE Tonel while RB7 bit 0 nop wend end if if Button PORTB 6 1 1 Tone2 while RB6 bit lt gt 0 nop wend end
230. 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 I File N J Events OnLeftClick Alt Mor OnRightClick OnDblClick OnMouseOver For every Active Comment a XML file will be created containing all valid information regarding the Active Comment attributes events etc and it is automatically added to Project manager after saving it Project Manager c Radni mikroC PRO for ds X pe S 83 i8 Ly tet e P Easy_GSM_GPRS mbp32 B Sources amp Easy_GSM_GPRS mbas j Header Files Binaries Project Level Defines S 7j Image Files Easy GSM GPRS jpg EEPROM Files Active Comments Files L 2 activeComment xml Output Files 3 Other Files MikroElektronika 96 mikroBasic PRO for PIC32 You can see the contents of the created XML file by expanding Active Comment Editor Active Comments Editor Enter comment name lt activeComment gt activeComment lt Attributes gt Url nnr mikroe comc Url lt Image gt lt Image gt lt File gt lt File gt Properties lt Attributes gt Active Comment Actions New Rename Attributes lt Events gt wn mikroe com lt OnLeftClick gt lt OnLeftClick gt Image j lt 0nRightClick gt lt 0nRightClick gt File lt OnDb1Click gt lt OnDb1Click gt Ld Events lt OnMouseOver gt lt
231. aen as byte p gt Description Initializes Port Expander using SPI communication Parameters rst Port Port Expander s reset port rst Pin Port Expander s reset pin haen Port Expander s hardware address Requires SPExpanderCs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before using this function SPI module needs to be initialized See SPIx Init and SPIx Init Advanced routines Port Expander module connections dim SPExpanderRST as sbit at LATFO bit SPExpanderCS as sbit at LATF1 bit SPExpanderRST Direction as sbit at TRISFO bit SPExpanderCS Direction as Sbit at TRISF1 bit End Port Expander module connections If Port Expander Library uses SPI1 module SPIL Inrt initialize SPI module Expander Init Advanced PORTB 0 0 initialize Port Expander 399 MikroElektronika mikoBasic PRO for PIC32 Expander Read Byte byte The function reads byte from Port Expander ModuleAddress Port Expander hardware address see schematic at the bottom of this page Prototype sub function Expander Read Byte dim ModuleAddress RegAddress as byte as RegAddress Port Expander s internal register address Byte read Port Expander must be initialized See Expander Init Read a byte from Port Expander s register dim read data as byte Expander R
232. alized 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 Cp 10 2 1 Notes For x axis and page layout explanation see schematic at the bottom of this page Glcd Write Text Prototype sub procedure SPI Glcd Write Text dim byref text as char 40 dim x pos page num color as 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 O 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 text Hello world on the position 10 inside the page 2 SPI Gled Write Text Hello world 10 2 1 Notes For x axis and page layout explanation see schematic at the bottom of this page MikroElektronika 468 mikroBasic PRO for PIC32 SPI Glcd Image Prototype sub procedure SPI Glcd Image
233. all variables in the Watch Values Window by clicking We Add All button To remove a variable from the Watch Values Window just select the variable that you want to remove and then click the 96 Remove button or press the Delete key It is possible to remove all variables from the Watch Values Window by clicking Remove All button You can also expand collapse complex variables i e struct type variables strings etc by clicking the appropriate button or beside variable name Watch Yalues PE En Bx Select variable from list WREGL PC 0x00028E 9655 99 ms Double clicking a variable or clicking the X 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 S 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 128 mikroBasic PRO for PIC32 RAM Window The RAM Window is available from the drop down menu View Debug Windows RAM The RAM Window displays the map of MCU s RAM with recently c
234. am memory space can also be declared within constant declaration block using keyword const program const ptr constant array will be stored in program memory const b array as byte 5 1 2 3 4 5 const ptr as byte ptr is pointer to program memory space main 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 205 MikroElektronika mikoBasic PRO for PIC32 This leads to equality of the following declarations dim ptrl as const byte ptrl1 pointer in data space pointing to a byte in code space const ptrl as byte ptri 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 mikroBasic PRO for PIC32 The example shows how to define and use a function pointer Example Example demonstrates the usage of function pointers It is shown how to declare a procedural type a pointer to function and finally how to call a function via pointer program Example typedef TMyFunctionType sub function dim paraml
235. ame represents a procedure s name and can be any valid identifier Within parentheses parameter list is a formal parameter list similar to variable declaration In mikroBasic PRO for PIC32 parameters are always passed to procedure by value to pass argument by address add the keyword byref ahead of identifier Local declarationsareoptional 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 198 mikroBasic PRO for PIC32 Example Here s an example procedure which transforms its input time parameters preparing them for output on Lcd sub procedure time prep dim byref sec min hr as byte sec sec and SF0 gt gt 4 10 sec and SOF min min and SFO gt gt 4 10 min and SOF hr hr and SFO gt gt 4 10 hr and SOF end sub A function can return a complex type Follow the example bellow to learn how to declare and use a function which returns a complex type Examp
236. an Init Flags 0 3 Can Send Flags 0 clear flags Can Rcv Flags 0 3 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 Initialize SPI2 module SPI2 Init CANSPIInitialize 1 3 3 3 1 Can Init Flags initialize external CANSPI module CANSPISetOperationMode CANSPI MOD CANSPISetMask CANSPI MASK B1 1 F E CONFIG OxFF CANSPI CONFIG XTD MSG set CONFIGURATION mode set all maski bits to ones 299 MikroElektronika mikoBasic PRO for PIC32 CANSPISetMask CANSPI MASK B2 1 CANSPI CONFIG XTD MSG set all mask2 bits to ones CANSPISetFilter CANSPI FILTER B2 F4 ID 2nd CANSPI CONFIG XTD MSG set id of filter B2 F4 to 2nd node ID CANSPISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode Set initial data to be sent RxTx Data 0 9 CANSPIWrite ID 1st RxTx Data 1 Can Send Flags send initial message while TRUE endless loop Msg Rcvd CANSPIRead Rx ID RxTx Data Rx Data Len Can Rcv Flags receive message if Rx ID ID 2nd and Msg Rcvd then if message received check id PORTB RxTx Data 0 id correct output data at PORTD Inc RxTx Data 0 increment received data Delay ms
237. an be used but it doesn t affect data For example b 2 MikroElektronika 216 mikroBasic PRO for PIC32 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 greater than greater than or equal less than or equa Relational Operators in Expressions The equal sign can also be an assignment operator depending on context Precedence of arithmetic and relational operators was designated in such a way to allow complex expressions without parentheses to have expected meaning if aa 5 gt bb 1 0 ce then same as if aa 5 gt bb 1 0 cc then dd My Function end if 211 MikroElektronika mikoBasic PRO for PIC32 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 associates from right to left Bitwise Operators Overview bitwise AND compares pairs of bits and returns 1 if both bits are 1 otherwise it returns 0 bitwise inclusive OR compares pairs of bits and generates a 1 result if either or both bits are 1 otherwise it returns O bitwise exclusive OR XOR compares pairs of bits and generates a 1 result if the bits are complementary othe
238. anager Project Settings MikroElektronika 44 mikroBasic PRO for PIC32 Build Build Menu Options Build Menu allows the user to easily manage building and compiling process M Build Ctrl F9 Rebuild All Sources Alt F9 Build All Projects Shift F9 Stop Build All Ctri F12 Build Program Ctrl Fi1 Bua O Besep on A Build ct Fs Build active project Rebuild All Sources Ak r Rebuild all sources in active project De Build all Projects shift F9 Build all projects Stop Build All Ctr F12 Stop building all projects 2h Build Program Ctr F11_ Build and program active project Related topics Keyboard shortcuts Project Toolbar Creating New Project Project Manager Project Settings 45 MikroElektronika mikoBasic PRO for PIC32 Run Run Menu Options Run Menu is used to debug and test compiled code on a software or harware level Start Debugger F9 5h Stop Debugger Ctrl F2 Run Pause Debugger F6 Step Into F7 Step Over F8 Step Out Ctri F8 Run To Cursor F4 4 Jump To Interrupt F2 Toggle Breakpoint F5 Clear Breakpoints Shift Ctrl F5 Disassembly mode Alt D Ra a v 8 5 Related topics Keyboard shortcuts Debug Toolbar MikroElektronika 46 mikroBasic PRO for PIC32 Tools Tools Menu Options Tools Menu contains a number of applications desig
239. 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 f MMC SD card was detected successfully formated and initialized 1 if FAT16 format was unseccessful 255 if MMC SD card was not detected The appropriate hardware SPI module must be previously initialized 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 MikroElektronika 342 mikroBasic PRO for PIC32 Mmc Fat Assign Protot
240. 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 ENC244600 It works with any PIC32 with integrated SPI and more than 4 Kb ROM memory 38 to 40 MHz clock is recommended to get from 8 to 10 Mhz SPI clock otherwise PIC32 should be clocked by ENC2443600 clock output due to its silicon bug in SPI hardware If you try lower PIC32 clock speed there might be board hang or miss some requests SPI Ethernet ENC24J600 library supports IPv4 protocol ARP requests ICMP echo requests UDP requests TCP requests no stack no packet reconstruction ARP client with cache DNS client UDP client DHCP client packet fragmentation is NOT supported Important Global library variable SPI Ethernet 243600 userTimerSec is used to keep track of time for all client implementations ARP DNS UDP and DHCP It is user responsibility to increment this variable each second in it s code if any of the clients is used For advanced users there is EcnEnc243600Private 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 ENC24J600 Library The appropriate hardware SPI module must be initialized before using any of the SPI Ethernet ENC24J600 library routines Refer to SPI Library
241. ant array MONTHS will be placed starting from the address 0x800 const MONTHS as byte 12 31 28 31 30 31 30 31 31 30 31 30 31 org 0x800 If you want to place simple type constant into Flash memory instead of following declaration sub procedure proc dim par as word org 0x200 Procedure will start at the address 0x200 end sub 113 MikroElektronika mikoBasic PRO for PIC32 org directive can be used with main routine too For example program Led Blinking main 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 main orgall 0x200 All the routines constants in main program will be above the address 0x200 end Built in Routines The mikroBasic PRO for PIC32 compiler provides a set of useful built in utility functions Built in functions do not have any special requirements You can use them in any part of your project The Delay us and Delay ms routines are implemented as inline i e code is generated in the place of a call so the call doesn t count against the nested call limit The Vdelay ms Vdelay advanced ms Delay Cyc Delay Cyc Long Get Fosc kHz and Get Fosc Per Cyc are actual Basic routines Their sources can be found in the Lib Delays mbas file located in the Uses folder of the compiler Lo Hi Higher Highest LoWord HiWord Inc Dec Chr Ord
242. ar product of two vectors using the while statement S20 i 0 while i n s s talil b i k ap Xd wend Probably the easiest way to create an endless loop is to use the statement while TRUE Y wend 221 MikroElektronika mikoBasic PRO for PIC32 Do Statement The do statement executes until the condition becomes true The syntax of the do statement is do statements loop until expression statements are executed repeatedly until expression evaluates true expression is evaluated after each iteration so the loop will execute statements at least once Here is an example of calculating scalar product of two vectors using the do statement S20 i 0 do S s a i b i iss itl loop until i n Jump Statements The jump statement when executed transfers control unconditionally There are five such statements in mikroBasic PRO for PIC32 break continue exit goto gosub 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 do For example Led Ouc l L1 No card inserted Wait for CF card to be plugged refresh every second while true if Cf Detect 1 then break MikroElektronika 228 mikroBasic PRO for PIC32 end if Delay ms 1000 wend Now we can work with CF c
243. arameters n cursor blinking enable disable parameter Valid values 0 disable cursor blinking and 1 enable cursor a Pinna Toshiba Glcd module needs to be initialized See the T6963C init routine enable cursor blinking T6963C cursor blink l Notes None LI Library Example The following drawing demo tests advanced routines of the T6963C Glcd library Hardware configurations in this example are made for the LV 32MX v6 board and PIC32MX460F512L Copy Code To Clipboard program T6963C 240x128 include Lib T6963C Consts T6963C module connections dim T6963C dataPort as byte at PORTD DATA port dim T6963C cntlPort as byte at PORTE DATA port dim T6963C ctrlwr as sbit at LATE2 bit WR write signal dim T6963C ctrlrd as sbit at LATE bit RD read signal dim T6963C ctrlcd as sbit at LATEO bit CD command data signal dim T6963C ctrlrst as sbit at LATE4 bit RST reset signal dim T6963C ctrlwr Direction as sbit at TRISE2 bit WR write signal direction dim T6963C ctrlrd Direction as sbit at TRISE1 bit RD read signal direction dim T6963C ctrlcd Direction as sbit at TRISEO bit CD command data signal direction dim T6963C ctrlrst Direction as sbit at TRISE4 bit AST reset signal direction Signals not used by library they are set in main function dim T6963C ctrlce as sbit at LATE3 bit CE signal dim T6963C ctrlfs as sbit at LATE6 bit t FS signal dim T6963C
244. arameters 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 Basic a unction name is automatically created local variable that can be used for returning a value of a function mikroBasic PRO for PIC32 also allows you to use the automatically created local variable result to assign the return value of a function if you find function name to be too ponderous If the return value of a function is not defined the compiler will report an error 197 MikroElektronika mikoBasic PRO for PIC32 Function calls are considered to be primary expressions and can be used in situations where expression is expected A function call can also be a self contained statement and in that case the return value is discarded Example Here s a simple function which calculates x based on input parameters x andn n gt 0 sub function power dim x n as byte as longint dim i as byte result 1 if n gt 0 then for i 1 to n result result x next i end if end sub Now we could call it to calculate say 3 tmp power 3 12 Procedures Procedure is declared like this sub procedure procedure name parameter list local declarations procedure body end sub procedure n
245. ard Lcd Out 1 1 Card detected m Continue Statement You can use the cont inue 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 do loop moves program counter to the line with loop condition bottom of the loop continue jumps here continue jumps here do for X sei while condition TE R E continue continue continue id continue jumps here next i wend loop until condition 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 sub procedure Procl dim error as byte i we re doing something here if error TRUE then exit end if some code which won t be executed if error is true end sub Note If breaking out of a function return value will be the value of the local variable result at the moment of exit Return Statement The return statement causes execution to leave the current subroutine and resume at the point in the code immediately after where the subroutine was called It s mainly intended to be used with gosub statement Return statement suffers from the same sort of readability problems as the GOTO s
246. ardware address see schematic at the bottom of this page Byte read Port Expander must be initialized See Expander Init Port Expander s PortB should be configured as input See Expander Set DirectionPortB and Expander Set DirectionPortAB routines Read a byte from Port Expander s PORTB dim read data as byte Expander Set DirectionPortB 0 S FF set expander s portb to be input Expander Read PortB 0 Read PortAB sub function Expander Read PortAB dim ModuleAddress as byte as word Description The function reads word from Port Expander s ports PortA readings are in the higher byte of the result PortB readings are in the lower byte of the result ModuleAddress Port Expander hardware address see schematic at the bottom of this page Rtums woare Requires Port Expander must be initialized See Expander Init Port Expander s PortA and PortB should be configured as inputs See Expander Set DirectionPortA Expander Set DirectionPortB and Expander Set DirectionPortAB routines Read a byte from Port Expander s PORTA and PORTB dim read data as word Expander Set DirectionPortAB 0 FFFF set expander s porta and portb to be input read data s Expander Read PortAB 0 361 MikroElektronika mikoBasic PRO for PIC32 Expander Write PortA Prototype sub procedure Expander Write PortA dim ModuleAddress Data as byte Description The function writes byte to Port Expander
247. as detected and successfully initialized 1 if FAT16 boot sector was not found 255 if MMC SD card was not detected Requires Global variables Mmc Chip Select Chip Select line Mmc Chip Select Direction Direction of the Chip Select pin must be defined before using this function The appropriate hardware SPI module must be previously initialized See the SPIx Init SPIx Init Advanced routines MMC module connections dim Mmc Chip Select as sbit sfr at LATFO bit dim Mmc Chip Select Direction as sbit sfr at TRISFO bit MMC module connections Initialize the SPI module SPI1 Init Advanced SPI MASTER SPI 8 BIT SPI PRESCALE SEC 1 SPI PRESCALE PRI 64 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 IDLE Initialize MMC SD card and MMC FAT16 library globals mc 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 341 MikroElektronika mikoBasic PRO for PIC32 Mmc Fat QuickFormat Prototype sub function Mmc Fat QuickFormat dim byref mmc fat label as string 11 as word Formats to FAT16
248. as 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 Init Mmc Fat QuickFormat Mmc Fat Assign Mmc Fat Reset Mmc Fat Read Mmc Fat Rewrite Mmc Fat Append Mmc Fat Delete Mmc Fat Write Mmc Fat Set File Date Mmc Fat Get File Date Mmc Fat Get File Date Modified Mmc Fat Get File Size Mmc Fat Get Swap File 337 MikroElektronika mikoBasic PRO for PIC32 Mmc Init Prototype sub function Mmc Init as word 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 dim Mmc Chip Select as sbit at LATFO bit for writing to output pin always use latch PIC18 family dim Mme Chip Select Direction as sbit at TRISFO bit MMC module connections dim error as byte 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
249. asic PRO for PIC32 LongIntToStrWithZeros 590 ByteToHex 590 ShortToHex 591 WordToHex 591 IntToHex 592 LongWordToHex 592 LongIntToHex 593 StrToInt 593 StrToWord 594 Bcd2Dec 594 Dec2Bcd 595 Bcd2Dec16 595 Dec2Bcd16 595 Setjmp Library 596 Library Routines 596 Setjmp 596 Longjmp 596 Library Example 597 String Library 598 Library Functions 598 memchr 598 memcmp 599 memcpy 599 memmove 600 memset 600 strcat 600 strcat2 601 strchr 601 strcmp 601 strcpy 602 strlen 602 strncat 602 strncpy 602 strspn 603 strncmp 603 strstr 603 strcspn 604 strpbrk 604 strrchr 604 Itrim 604 rtrim 605 strappendpre 605 strappendsuf 605 length 605 Time Library 606 Library Routines 606 MikroElektronika 24 mikroBasic PRO for PIC32 Time dateToEpoch 606 Time epochToDate 607 Time dateDiff 607 Library Example 608 Trigon Library 609 Library Functions 609 acos 610 asin 610 atan 610 atan2 610 ceil 610 cos 610 cosh 611 eval_poly 611 exp 611 fabs 611 floor 611 frexp 611 Idexp 612 log 612 log10 612 modf 612 pow 612 sin 612 sinh 613 sqrt 613 tan 613 tanh 613 Trigonometry Library 614 Library Routines 614 sinE3 614 cosE3 614 CHAPTER 10 615 Tutorials 615 Managing Project 615 Projects 615 New Project 616 New Project Wizard Steps 616 Customizing Projects 620 Managing Project Group 620 Add Remove Files from Project 620 Project Level Defines 621 Source Files 622 Managing Source Files 622 Creati
250. at Init tries to initialize a card more than once k If card is not present initialization may last longer depending on clock speed end if end HW Connection SPI MISO Pin diagram of MMC memory card MikroElektronika 354 mikroBasic PRO for PIC32 OneWire Library The OneWire library provides routines for communication via the Dallas OneWire protocol e g with DS18x20 digital thermometer OneWire is a Master Slave protocol and all communication cabling required is a single wire OneWire enabled devices should have open collector drivers with single pull up resistor on the shared data line Slave devices on the OneWire bus can even get their power supply from data line For detailed schematic see device datasheet Some basic characteristics of this protocol are single master system low cost low transfer rates up to 16 kbps fairly long distances up to 300 meters small data transfer packages Each OneWire device also has a unique 64 bit registration number 8 bit device type 48 bit serial number and 8 bit CRC so multiple slaves can co exist on the same bus Important Oscillator frequency Fosc needs to be at least 4MHz in order to use the routines with Dallas digital thermometers This library implements time based activities so interrupts need to be disabled when using OneWire library Library Routines Ow Reset Ow Read Ow Write Ow Reset isis sub function Ow Reset d
251. ate Valid values 0 logical zero and 1 logical one 255 if the pin was in the active state for given period 0 otherwise program Button Test dim oldstate as bit oldstate 0 ADPCFG OxFFFF initialize AN pins as digital TRISD OxFFFF initialize portd as input TRISB 0x0000 initialize portb as output TRUE if Button PORTD Q 1 1 then detect logical one on RBO pin oldstate 1 end if if oldstate and Button PORTD 0 1 0 then LATB not LATB invert value of PORTB oldstate 0 end if wend endless loop MikroElektronika 918 mikroBasic PRO for PIC32 C Type Library The mikroBasic PRO for PIC32 provides a set of library functions for testing and mapping characters Library Functions isalnum isalpha iscntrl isdigit isgraph islower ispunct isspace isupper isxdigit toupper tolower isalnum eee sub function isalnum dim character as byte as byte Function returns OxFF if the character is alphanumeric A Z a z 0 9 otherwise returns zero isalnum o returns OxFF res isalnum Nr returns 0 Prototype sub function isalpha dim character as byte as word Function returns OxFF if the character is alphabetic A Z a z otherwise returns zero isalpha A returns OxFF res isalpha 1 returns 0 iscntrl Prototype sub function iscntrl dim character as byte as word Function returns OxFF if the character is a control
252. ate_Upper_Right TP_Get_Calibration_Consts TP_Set_Calibration_Consts MikroElektronika 550 mikroBasic PRO for PIC32 TP Init dim readX ChNo as byte dim readY ChNo as byte Initialize touch panel display Default touch panel ADC threshold value is set to 3900 Parameters Prototype sub procedure TP Init dim display width as word dim display height as word display width set display width display height set display height readX ChNo read X coordinate from desired ADC channel readY ChNo read Y coordinate from desired ADC channel Before calling this function initialize ADC module ADC1 Init Initalize ADC module TP Init 128 64 Initialize touch panel dimensions 128x64 TP Set ADC Threshold Rems Nang S T TP Init has to be called before using this routine Example TP Set ADC Threshold 3900 Set touch panel ADC threshold rows Ree 991 MikroElektronika mikoBasic PRO for PIC32 TP Press Detect Prototype sub function TP Press Detect as byte Detects if the touch panel has been pressed 1 if touch panel is pressed 0 otherwise Requires Global variables DriveA DriveA DriveB DriveB DriveA Direction Direction of DriveA pin DriveB Direction Direction of DriveB pin must be defined before using this function Touch Panel module connections dim DriveA as sbit at LATC13 bit DriveB as sbit at LATC14 bit DriveA Direction as sbit at TRISC13 bit
253. ave working license key for it but it doesn t work with new compiler you have to repeat registration procedure from the new compiler and you will get a new license mikoBasic PRO for PIC32 have bought license for the older version do have to pay license for the new version of the compiler No once you pay for the license key you get a lifetime license When we release a new major release of the compiler you might need to repeat registration procedure from your new compiler and you will get new license free of charge Do your compilers work on Windows Vista Windows 7 Yes What does this function procedure routine do Please see your compiler s Help where all of the functions are explained in detail try to compile one of the provided examples and nothing happens what is the problem You need to open project not file When you want to open an example go to Project Open Project then browse through projects and choose project file Now you will be able to compile and program with success Can get your library sources need to provide all sources with my project It is our company s policy not to share our source code Can use code developed 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
254. ay type the operator will return pointer to it s first basic element except when the left side of the statement in which x is used is an array pointer In this case the operator will return pointer to array not to it s first basic element program example dim w as word ptr b as byte ptr arr as byte 10 arr as byte 10 main ptr b arr operator will return byte w Qarr operator will return byte ptr arr arr operator will return byte 10 end If F is a routine a function or procedure F returns a pointer to F Related topics Pointer Arithmetic 207 MikroElektronika mikoBasic PRO for PIC32 Pointer Arithmetic Pointer arithmetic in the mikroBasic PRO for PIC32 is limited to assigning one pointer to another comparing two pointers comparing pointer to zero adding subtracting pointer and an integer value subtracting two pointers Assignment and Comparison The simple assignment operator can be used to assign value of one pointer to another if they are of the same type Assigning the integer constant 0 to a pointer assigns a null pointer value to it Two pointers pointing to the same array may be compared by using relational operators lt gt lt lt gt and gt Results of these operations are the same as if they were used on subscript values of array elements in question dim ptrl as byte ptr2 as byte a as byte 10 array a containing 10
255. b procedure CircleArea sub function r square dim r as float as float external Declaration of the r square routine defined in Main Module followed with a external modifier sub procedure pi r square dim rr as float external Declaration of the pi r square routine defined in Second Module followed with a external modifier implements MikroElektronika 194 mikroBasic PRO for PIC32 sub procedure CircleArea Definition of the CircleArea routine dim res as real res r square 5 Calculate r r pi r square res y Calculate pi r r end sub end Variables and PIC32 Every declared variable consumes part of RAM memory Data type of variable determines not only the allowed range of values but also the space a variable occupies in RAM memory Bear in mind that operations using different types of variables take different time to be completed mikroBasic PRO for PIC32 recycles local variable memory space local variables declared in different functions and procedures share the same memory space if possible There is no need to declare SFRs explicitly as mikroBasic PRO for PIC32 automatically declares relevant registers as global variables of word For example WO TMR1 etc 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 declara
256. bit at LATC3 bit dim RS as sbit at LATB15 bit dim TFT RST as sbit at LATCl bit dim TFT DataPort Direction as byte at TRISE dim TFT WR Direction as sbit at TRISD13 bit dim TFT RD Direction as sbit at TRISD12 bit dim TFT CS Direction as sbit at TRISC3 bit dim TFT RS Direction as sbit at TRISB15 bit dim TFT RST Direction as sbit at TRISC1 bit End of TFT display connections Initialize 240x320 TFT display TFT Init 240 320 MikroElektronika 534 mikroBasic PRO for PIC32 TFT Set Index Prototype sub procedure TFT Set Index dim index as 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 sub procedure TFT Write Command dim cmd as 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 sub procedure TFT Write Data dim data as 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 535 MikroElektronika mikoBasic PRO for PIC32
257. 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 Draw a rounded edge rectangle between dots 5 5 and 40 40 with the radius of 12 SPI Glcd Rectangle Round Edges 5 5 SPI Glcd Rectangle Round Edges Fill Prototype sub procedure SPI Glcd Rectangle Round Edges Fill dim x upper left as byte dim y upper left as byte dim x bottom right as byte dim y bottom right as byte dim radius as byte dim color as 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 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 t
258. braries in a common form which will work with all MCUs If this box is not checked then library will be built for selected MCU Bear in mind that compiler will report an error if a library built for specific MCU is used for another one 5 Compiled file Lib Example emcl should appear in mikroBasic PRO for PIC32 Uses folder 6 Open the definition file for the MCU that you want to use This file is placed in the compiler s Defs folder DriveName Program Files Mikroelektronika mikroBasic PRO for PIC32 Defs and it is named MCU NAME mlk for example P32MX460F512L m1k 7 Add the the following segment of code to lt LIBRARIES gt node of the definition file definition file is in XML format lt LIB gt lt ALIAS gt Example Library lt ALIAS gt FILE Lib Example lt FILE gt lt TYPE gt REGULAR lt TYPE gt lt LIB gt 8 Add Library to mlk file for each MCU that you want to use with your library 9 Click Refresh button in Library Manager 10 Example Library should appear in the Library manager window Multiple Library Versions Library Alias represents unique name that is linked to corresponding Library emc1 file For example UART library for PIC32MX460F512L is different from UART library for PIC32MX675F512L MCU Therefore two different UART Library versions were made see mlk files for these two MCUs Note that these two libraries have the same Library Alias UART in both m1k files This approach enables y
259. button Clear All E and all libraries will be cleared from the project Only the selected libraries will be linked Library Manager 2 fa fa Fe mikroE ADC C BitReverseComplex Oo Button O can CO CAN sPI C Conversions C Type C EEPROM O FFT C FirRadix FLASH O Ged CO Gled_Fonts E rc CO rirRadix C Keypad4x4 Lcd Lcd Constants C Manchester Im Matrices Mmc Mmc FAT16 C one wire C Port Expander ps2 a PwM lon BDesepon S Refresh Library by scanning files in Uses folder Useful when new libraries are added by copying files to Uses folder EJ ETTITT NN 61 MikroElektronika EI E E E E E E E ED E2 ED E E B E E E E E E E E E E mikoBasic PRO for PIC32 Managing libraries using Package Manager The Package Manager is a tool which enables users to easily install their own libraries in the mikroIDE Libraries are distributed in the form of a package which is an archive composed of one or more files containing libraries For more information on Package Manager visit our website Upon package installation a new node with the package name will be created in the Library Manager For example E Library Manager a del ferio C sound amp ser C sPI Ethernet C sPI lcd E sPr Lcd C ser Leda amp C ser T sesc C sprintf C sprinti C Sprint amp v Tesesc amp E Time C TouchPanel Trigonometry L rwr
260. by the library The user accesses to the UDP request by using some of the SPI Ethernet 24j600 get routines The user puts data in the transmit buffer by using some of the SPI Ethernet 24j600 put routines The function must return the length in bytes of the UDP reply or 0 if nothing to transmit If you don t need to reply to the UDP requests just define this function with a return 0 as single statement Parameters remoteHost client s IP address remotePort client s port localPort port to which the request is sent regLength UDP request data field length flags Structure consisted of two bit fields Copy Code To Clipboard structure TEthj600PktFlags dim canCloseTCP as boolean flag which closes socket not relevant to UDP dim isBroadcast as boolean flag which denotes that the IP package has been received via subnet broadcast address end structure 0 there should not be a reply to the request Length of UDP reply data field otherwise Ethernet module has to be initialized See SPI Ethernet 24600 Init This function is internally called by the library and should not be called by the user s code The function source code is provided with appropriate example projects The code should be adjusted by the user to achieve desired reply 449 MikroElektronika mikoBasic PRO for PIC32 SPI Ethernet 24j600 setUserHandlers Prototype sub procedure SPI Ethernet 245600 setUserHandlers dim TCPHandl
261. 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 mikroBasic PRO for PIC32 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 only limitation of the free version is that it cannot generate hex output over 2K of program words Although it might sound restrictive this margin allows you to develop practical working applications with no thinking of demo limit If you intend to develop really complex projects in the mikroBasic PRO for PIC32 then you should consider the possibility of purchasing the license key Who Gets the License Key Buyers of the mikroBasic PRO for PIC32 are entitled to the license key After you have completed the payment procedure you have an option of registering your mikroBasic PRO for PIC32 In this way you can generate hex output without any limitations How to Get License Key After you have completed the payment procedure start the program Select Help How to Register from the drop down menu or click the How To Register Icon i You can choose between two register
262. cd Parameters image image to be displayed Bitmap array can be located in both code and RAM memory due to the mikroBasic PRO for PIC32 pointer to const and pointer to RAM equivalency Nothing Requires Glcd needs to be initialized see Glcd Init routine Draw image my image on Glcd Glcd Image my image Use the mikroBasic PRO for PIC32 integrated Glcd Bitmap Editor Tools Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd Glcd Partiallmage Prototype sub procedure Glcd Partiallmage dim x left y top width height picture width picture height as word const image as byte Description Displays a partial area of the image on a desired location Parameters x left x coordinate of the desired location upper left coordinate y top y coordinate of the desired location upper left coordinate width desired image width height desired image height picture width width of the original image picture height height of the original image image image to be displayed Bitmap array can be located in both code and RAM memory due to the mikroBasic PRO for PIC pointer to const and pointer to RAM equivalency Nothing Requires Glcd needs to be initialized see Glcd Init routine Draws a 10x15 part of the image starting from the upper left corner on the coordinate 10 12 Original image size is 16x32 Glcd Partiallmage 10 12 10 15 16 32 image Use the m
263. ck Ck ck kk kk ck ck ck kk ck kk kk ck kk kk ck kk ke kk Sk ko ck ko ke kx ko k ko k ko ko implements constants declarations const variables declarations dim procedures declarations sub procedure sub procedure name dim byref const ParamName as type dim byref const ParamName2 ParamName3 as type ilevel 0x123 overload forward local declarations end sub 189 MikroElektronika mikoBasic PRO for PIC32 functions declarations sub function sub function name dim byref const ParamName as type dim byref const ParamName2 ParamName3 as Jtype as type ilevel 0x123 overload forward local declarations end sub end Note Sub functions and sub 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 Place of declaration Identifier is declared in the declaration section of the Scope extends from the point where it is declared to the end of the cur main module out of any function or procedure rent file including all routines enclosed within that scope These identi fiers have a file scope and are referred to as globals Identifier is declared in the fu
264. ck and limited memory PIC32 Specific Basic Language Extensions mikroBasic PRO for PIC32 has additional set of keywords that do not belong to the standard Basic language keywords code data IX sfr at MikroElektronika 134 mikroBasic PRO for PIC32 sbit bit iv Related topics Keywords PIC32 Specific Predefined Globals and Constants To facilitate PIC32 programming the mikroBasic PRO for PIC32 implements a number of predefined globals and constants All PIC32 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 mikroBasic PRO for PIC32 will include an appropriate mbas file from defs folder containing declarations of available SFRs and constants such as PORTB ADPCFG etc All identifiers are in upper case identical to nomenclature in the Microchip datasheets For a complete set of predefined globals and constants look for Defs in the mikroBasic PRO for PIC32 installation folder or probe the Code Assistant for specific letters CtrltSpace in the Code Editor Predefined project level defines mikroBasic PRO for PIC32 provides predefined project level defines that you can use in your project First one is equal to the name of selected device for the project For example IFDEF P32MX460F512L ENDIF Second one is equal to the family name IFDEF PIC32 ENDIF
265. cnt MAXALLOWED then cnt 0 PORT 1 0 MY DELAY end if Note Symbols do not support macro expansion in a way the C preprocessor does 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 value while procedure does not Functions A function is declared like this sub function function name parameter list as return type local declarations function body end sub 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 1ist is a formal parameter list very similar to variable declaration In mikroBasic PRO for PIC parameters are always passed to a function by the value To pass an argument by address add the keyword byre ahead of identifier Local declarations are optional declarations of variables and or constants local for the given function Function body is a sequence of statements to be executed upon calling the function Calling a function Afunction is called by its name with actual arguments placed in the same sequence as their matching formal parameters The compiler is able to coerce mismatching arguments to the proper type according to implicit conversion rules Upon a function call all formal p
266. code The code memory type may be used for allocating constants in program memory puts txt in program memory const txt Enter parameter code data This memory specifier is used when storing variable to the Data RAM puts data buffer in data ram dim data buffer as char data rx This memory specifier allows variable to be stored in the working registers space WREGO WREG195 puts y in the working registers space dim y as char rx 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 dim y as char sfr puts y in SFR space Note If none of the memory specifiers are used when declaring a variable data specifier will be set as default by the compiler Related topics PIC32 Memory Organization Accessing individual bits SFRs Constants Functions 171 MikroElektronika mikoBasic PRO for PIC32 Read Modify Write Problem The Microchip microcontrollers use a sequence known as Read Modify Write RMW when changing an output state 1 or 0 on a pin This can cause unexpected behavior under certain circumstances When your program changes the state on a specific pin for example RBO in PORTB the microcontroller first READs all 8 bits of the PORTB register which represents the states of all 8 pins in PORTB RB7 RBO The microcontroller then stores this data in the
267. collision was detected on the I C bus Requires MCU with at least one lC module Used I C module must be initialized before using this function See I2Cx Init routine Also START signal needs to be issued in order to use this function See I2Cx Start dim data as byte error as word I2Cl Write data I2C1 Write 0xA3 PC library routines require you to specify the module you want to use To select the desired C module simply change the letter x in the routine prototype for a number from 1 to 5 Number of IC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 313 MikroElektronika mikoBasic PRO for PIC32 I2Cx Stop Reums Noting Requires MCU with at least one I C module Used I C module must be initialized before using this function See I2Cx Init routine Issue STOP signal I2C1 Stop FC library routines require you to specify the module you want to use To select the desired C module simply change the letter x in the routine prototype for a number from 1 to 5 Number of IC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Library Example This code demonstrates working with the I C library Program sends data to EEPROM data is written at the address 2 After that program reads data from the same EEPROM address and displays it on PORTB for visual check Copy C
268. ct pointed to by eptr 609 MikroElektronika mikoBasic PRO for PIC32 Idexp Prototype sub function ldexp dim value as float dim newexp as integer as float Description Function returns the result of multiplying the floating point number num by 2 raised to the power n i e retums x 22 es ldexp 2 PIOIODe sub function log dim x as float as float Function returns the natural ESSENT of x i e Logg x Example res log 10 res 2 302585E log10 Prototype sub function logl0 dim x as float as float Function returns the base 10 logarithm of x i e 16910 x Example res logl0 100 res 2 000000 modf Prototype sub function modf dim val as float dim byref iptr as float as float Returns argument val split to the fractional part function return val and integer part in number iptr Example res modf 6 25 iptr 0 25 iptr 6 00 pow Prototype sub function pow dim x as float dim y as float as float Description Function returns the value of x raised to the power y i e xY If x is negative the function will automatically cast y into unsigned long Example res pow 10 5 b 9 999984e 4 sin Prototype sub function sin dim arg as float as float Function returns the sine of f in radians The return value is from 1 to 1 u Example res sin PI 2 res 1 000000 MikroElektronika 610 mikroBasic PRO for PIC32 sinh Prototype sub funct
269. cted 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 mikroBasic PRO for PIC32 to suit your needs best Spell checker underlines identifiers which are unknown to the project In this way it helps the programmer to spot potential problems early much before the project is compiled Spell checker can be disabled by choosing the option in the Preferences dialog F12 49 MikroElektronika mikoBasic PRO for PIC32 Code Editor The Code Editor is advanced text editor fashioned to satisfy needs of professionals General code editing is the same as working with any standard text editor including familiar Copy Paste and Undo actions common for Windows environment Available Code Editor options are Editor Settings Editor Colors Auto Correct Auto Complete and Style Editor Settings Main Editor Settings Features are Auto Save Highlighter Spelling Comment Style Code Folding Code Assistant Parameter Assistant Bookmarks and Go to Line Options Editor Settings Editor Settings Project Ries 1t V Restore Last Opened Project Restore All Opened Files 5 Editor Colors ig If Opened File Is Externally Modified
270. cts 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 ka from the Project Manager window The project group may be reopened by clicking the Open Project Group Icon e All relevant data about the project group is stored in the project group file extension mbdsgroup Add Remove Files from Project The project can contain the following file types mbas source files emc1 binary files p1d project level defines files image files ihex EEPROM files hex asm and 1st files see output files These files can not be added or removed from project other files Project Manager 1 1 rs 4 Sources T6963C 240x128 mbas einstein bmp mbas mikroe bmp mbas a Um Binaries T 963C 240x128 md Project level defines Image Files mikroE 240x128 bmp EEPROM Files T6963C 240x128 ihex Active Comments Files 4 Output Files T6963C 240x128 hex T6963C 240x128 asm einstein bmp asm mikroe bmp asm T6963C 240x128 lst B E Other Files B DataSheet_70138b pdfF MikroElektronika 618 mikroBasic PRO for PIC32 The list of relevant files is stored in the project file extension mbp32 To add a file to the project click the Add File to Project Icon E press Insert button on your keyboard Each added source file must be self contained i e it must have all necessary definiti
271. d MikroElektronika 242 mikroBasic PRO for PIC32 CANSPI Library The SPI module is available with a number of the PIC32 MCUs The mikroBasic PRO for PIC32 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 CAN supports two message formats Standard format with 11 identifier bits and Extended format with 29 identifier bits Important Consult the CAN standard about CAN bus termination resistance An effective CANSPI communication speed depends on SPI and certainly is slower than real CAN The library uses the SPI module for communication User must initialize appropriate SPI module before using the 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 CANSPI module refers to mikroElektronika s CANSPI Add on board connected to SPI module of MCU Library Dependency Tree CANSPI 9 sri External dependencies of CANSPI Library The following variables must be defined in all projects using CANSPI
272. d by the Getmem sub procedure ActualSize specifies the size in bytes of the dynamic variable to dispose of and should be the same as the one used to Getmem Nothing Requires Nothing FreeMem ptr 20 sizeof PBuffer ptr will point to a memory block where PBuffer is allocated None MM_LargestFreeMemBlock Prototype sub function MM LargestFreeMemBlock as word This sub function is used to determine largest available free memory block for the Heap Returns after defragmentation of the freelist the size in bytes of the largest free block of contiguous memory on the heap MM TotalFreeMemSize Retums Retums te size Gn byes ofthe tal fee memory ontheheap Nm OS dim total as word total MM TotalFreeMemSize 339 MikroElektronika mikoBasic PRO for PIC32 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 PDAs mikroBasic PRO for PIC32 provides a library for accessing data on Multi Media Card via SPI communication This library also supports SD Secure Digital and high capacity SDHC Secure Digital High Capacity memory cards Secure Digital Card Secure Digital SD is a Flash memory card standard based on the older Multi Media Card MMC format SD cards are currently available in sizes of up to and including 2
273. d 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 ENC24J600 module such as Pattern Match Magic Packet and Hash Table can not be enabled by this routine Additionaly all filters except CRC enabled with this routine will work in OR mode which means that packet will be received if any of the enabled filters accepts it This routine will change receive filter configuration on the fly It will not in any way mess with enabling disabling receive transmit logic or any other part of the ENC24J600 module The ENC247600 module should be properly cofigured by the means of SPI Ethernet 24j600 Init routine multicast traffic will be enabled MULTICAST x oxuo noted mei 5 0x20 CRC check flag When set packets with invalid CRC field SPI Ethernet 24j600 CRC will be discarded a Es efo mum SPC 7 loxao MAC Unicast traffic receive filter flag When set MAC SPI Ethernet 24 600 unicast traffic will be enabled UNICAST Requires Ethernet module has to be initialized See SPI Ethernet 24j600 Init SPI Ethernet 24 600 Enable SPI Ethernet 243600 CRCor SPI Ethernet 24 600 UNICAST enable CRC checking and Unicast traffic Parameters enF1t network traffic receive filter flags
274. d in both code and RAM memory due to the mikroBasic PRO for PIC pointer to const and pointer to RAM equivalency Nothing Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Draws a 10x15 part of the image starting from the upper left corner on the coordinate 10 12 Original image size is 16x32 SPI T6963C Partiallmage 10 12 10 15 16 32 image Image dimension must match the display dimension Use the integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd 495 MikroElektronika mikoBasic PRO for PIC32 SPI T6963C sprite Prototype sub procedure SPI T6963C sprite dim px py as byte dim const pic as byte dim sx sy as byte Fills graphic rectangle area px py to px sx py sy with custom size picture Parameters x x coordinate of the upper left picture corner Valid values multiples of the font width py y coordinate of the upper left picture corner pic picture to be displayed sx picture width Valid values multiples of the font width sy picture height Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPE T6963C sprite 76 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 SPI T6963C set cursor Prototyp
275. de 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 PIC32 specifics mikroBasic PRO for PIC32 specifics Memory type specifiers MikroElektronika 162 mikroBasic PRO for PIC32 Single Static Assignment Optimization Introduction In compiler design static single assignment form often abbreviated as SSA form or SSA is an intermediate representation IR in which every variable is assigned exactly once An SSA based compiler modifies the program representation so that every time a variable is assigned in the original program a new version of the variable is created A new version of the variable is distinguished renamed by subscripting the variable name with its version number or an index so that every definition of each variable in a program becomes unique At a joining point
276. ded SRAM display memory which is used to store text character codes and bit mapped graphics The S1D13700 Glcd handles display controller functions including Transferring data from the controlling microprocessor to the buffer memory Reading memory data converting data to display pixels Generating timing signals for the LCD panel The S1D13700 Glcd is designed with an internal character generator which supports 160 5x7 pixel characters in internal mask ROM CGROM and 64 8x8 pixel characters incharacter generator RAM CGRAM When the CGROM is not used up to 256 8x16 pixel characters are supported in CGRAM External dependencies of the Epson S1D13700 Graphic Lcd Library The following variables must be defined in all projects using S1D13700 Graphic Description Lcd library i 7 ane er TUUS eee System data bus dim S1D13700 DATA at PORTD external z dim 51D13700 WR as sbit sfr dim S1D13700 WR as sbit at LATC2 Write signal external bit dim 1D13700 RD as Ssbit sfr dim S1D13700 RD as sbit at LATCI1 Read signal external bat dim S 1D13700 AO as Ssbit sfr 2 dim S1D13700 AO as sbit at LATCO System Address pin external bat dim 51D13700 RES as sbit sfr A dim 51D13700 RES as sbit at LATC4 Reset signal external pat r g dim 51D13700 CS as sbit at LATC4 Chip select n bit Direction of the system data bus dim S1D13700 DATA Direction sbit at pins TRISD A dim 1D13700 WR Direction as sb
277. dencies of Touch Panel TFT Library 557 Library Routines 557 TP TFT Init 558 TP TFT Set ADC Threshold 558 TP TFT Press Detect 559 TP TFT Get Coordinates 560 TP TFT Calibrate Min 560 TP TFT Calibrate Max 560 TP TFT Get Calibration Consts 561 TP TFT Set Calibration Consts 561 HW Connection 562 UART Library 563 Library Routines 563 UARTXx Init 564 UARTx Init Advanced 565 UARTx Data Ready 566 UARTx Tx Idle 566 UARTx Read 567 UARTx Read Text 568 UARTx Write 569 UARTx Write Text 569 UART Set Active 570 Library Example 571 HW Connection 572 USB Library 5 3 MikroElektronika 22 mikroBasic PRO for PIC32 USB HID Class 573 Descriptor File 573 Library Routines 573 HID_Enable 574 HID_Read 574 HID_Write 574 HID_ Disable 575 USB_Interrupt_Proc 575 USB Polling Proc 576 Gen Enable 576 Gen Read 577 Gen_Write 577 Library Example 578 HW Connection 578 Miscellaneous Libraries 579 Button Library 579 Library Routines 579 Button 580 C Type Library 581 Library Functions 581 isalnum 581 isalpha 581 iscntrl 581 isdigit 581 isgraph 582 islower 582 ispunct 582 isspace 582 isupper 582 isxdigit 583 toupper 583 tolower 583 Conversions Library 584 Library Dependency Tree 584 Library Routines 584 ByteToStr 585 ShortToStr 585 WordToStr 585 WordToStrWithZeros 586 IntToStr 586 LongintToStr 587 LongWordToStr 587 FloatToStr 588 WordToStrWithZeros 588 IntToStrWithZeros 589 LongWordToStrWithZeros 589 MikroElektronika 23 mikoB
278. dency Tree Lcd Lcd Constants External dependencies of Lcd Library The following variables must be denned Enni CN NE D7 as sbit sfr external dim LCD D7 as sbit at B3 bart LCD RS Direction as sbit sfr 3 i n A P Register Select direction pin dim LCD RS Direction as sbit at TR cue dim LCD EN Direction as sbit sfr l F i x Enable direction pin dim LCD EN Direction as sbit at 1 external Lo dim LCD D4 Direction as sbit sfr i s y r Data 4 direction pin dim Direction as sbit at TR external Lu dim LCD D5 Direction as sbit sfr n j i Data 5 direction pin Direction as sbit at 1 external _ dim LCD D6 Direction as sbit sfr n i n T Data 6 direction pin Direction as sbit at TR external dim LCD D7 Direction as sbit sfr F A A i o Data 7 direction pin dim Direction as sbit at TRISB3 bit external ii iet Library Routines Lcd Init Lcd Out Lcd Out Cp Lcd Chr Lcd Chr Cp Lcd Cmd MikroElektronika 320 mikroBasic PRO for PIC32 Lcd Init Requires Global variables Le LC LC LC LC LC LC LC LC LC sme LC Register Select data instruction signal pin Enable signal pin Data bit 4 Data bit 5 Data bit 6 Data bit 7 RS Direction Direction of the Register Select pin EN Direction Direction of the Enable signal pin D4 Direction Direction of the Data 4 pin D5 Direction
279. dependencies of Manchester Code Library The following variables must be defined in all projects using Manchester Code Description Library dim MANRXPIN as sbit sfr external dim MANRXPIN as sbit at RFO bit dim MANTXPIN as sbit sfr external dim MANTXPIN as sbit at LATF1 bit dim MANRXPIN Direction as sbit sfr dim MANRXPIN Direction as sbit at Direction of the Receive pin external TRISFO bit dim MANTXPIN Direction as sbit sfr external dim MANTXPIN Direction as sbit at Direction of the Transmit pin TRISFl bit MikroElektronika 326 mikroBasic PRO for PIC32 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 sub function Man Receive Init as word Description The function configures Receiver pin After that the function performs synchronization procedure in order to retrieve baud rate out of the incoming signal 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 dim MANRXPIN as sbit at RFO bit dim MANRXPIN Direction as sbit at TRISFO bit Man
280. der Set DirectionPortB Expander Set DirectionPortAB Expander Set PullUpsPortA Expander Set PullUpsPortB Expander Set PullUpsPortAB 39 MikroElektronika mikoBasic PRO for PIC32 Expander Init Prototype sub procedure Expander Init dim ModuleAddress as byte Description Initializes Port Expander using SPI communication Port Expander module settings hardware addressing enabled automatic address pointer incrementing disabled byte mode BANK O0 register adressing slew rate enabled ModuleAddress Port Expander hardware address see schematic at the bottom of this page Requires Global variables SPExpanderCs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before using this function SPI module needs to be initialized See SPIx Init and SPIx Init Advanced routines Port Expander module connections dim SPExpanderRST as sbit at LATFO bit SPExpanderCS as sbit at LATF1 bit SPExpanderRST Direction as sbit at TRISFO bit SPExpanderCS Direction as sbit at TRISF1 bit End Port Expander module connections SPIl Inxt initialize SPI module Expander Init initialize Port Expander MikroElektronika 398 mikroBasic PRO for PIC32 Expander Init Advanced Prototype sub procedure Expander Init Advanced dim byref rstPort rstPin h
281. destination string Destination string should be at least 7 characters in length dim input as integer txt as string 6 input 4220 IntToStr inp t txt V Ext xe T 42207 MikroElektronika 584 mikroBasic PRO for PIC32 LongintToStr Prototype sub procedure LongintToStr dim input as longint dim byref output as string 11 Description Converts input longint number to a string The output string is right justified and the remaining positions on the left if any are filled with blanks Parameters input signed long integer number to be converted output destination string Nothing Requires Destination string should be at least 12 characters in length dim input as longint txt as string l1l input 12345678 InbToStr input txt t ERE is WV 123945678 LongWordToStr Prototype sub procedure LongWordToStr dim input as longword dim byref output as string 10 Description onverts input double word number to a string The output string is right justified and the remaining positions on the left if any are filled with blanks Parameters input unsigned long integer number to be converted output destination string Nothing Requires Destination string should be at least 11 characters in length dim input as longint txt as string 10 input 12345678 IntToStr input txt EXE xs 22345678 585 MikroElektronika mikoBasic PRO for PIC32 FloatToStr Prototype sub proc
282. dim byref const image as 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 mikroBasic PRO for PIC32 pointer to const and pointer to RAM equivalency Glcd needs to be initialized for SPI communication see SPI Glcd Init routine ame ee eem me OOO OOOO O Use the mikroBasic PRO for PIC32 integrated Glcd Bitmap Editor Tools gt Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd SPI Glcd Partiallmage Prototype sub procedure SPI T6963C Partiallmage dim x left y top width height picture width picture height as word const image as 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 mikroBasic PRO for PIC pointer to const and pointer to RAM equivalency Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draws a 10x15 part of the image starting from the upper left corner on the coordinate 10 12 Original image size is 16x32 SPI Gled Partiallmage l10
283. dinates x y Parameters x dot position on x axis y dot position on y axis color color parameter Valid values TFT module needs to be initialized See the TFT Init routine ERE TFT Dot 50 50 CL BLACK MikroElektronika 540 mikroBasic PRO for PIC32 TFT Set Pen Prototype sub procedure TFT Set Pen dim pen color as word dim pen width as byte Description Sets color and thickness parameter for drawing line circle and rectangle elements Parameters pen color Sets color E C C pen width sets thickness TFT module needs to be initialized See the TFT Init routine Example TFT Set Pen CL BLACK 10 L OLIVE Olive color 541 MikroElektronika mikoBasic PRO for PIC32 TFT Set Brush Prototype sub procedure TFT Set Brush dim brush enabled as byte dim brush color as word dim gradient enabled gradient orientation as byte dim gradient color from gradient color to as 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 MikroElektronika 542 mikroBasic PRO for PIC32 Description gradient enabled enable gradient Enable gradient lo Disable gradient gradient orientation sets gradient orientation Left to right gradient orientation Top to bottom g
284. dress of the FLASH memory word rdata data to be written Nothing Requires Nothing None Flash Erase Page Prototype sub procedure FLASH Write Init dim flash address as longint dim data address as word Description Erases one page 8 rows 1024 32 bit word 4096 bytes from the program Flash memory Parameters address starting address of the FLASH memory block Nothing Requires Nothing 295 MikroElektronika mikoBasic PRO for PIC32 Graphic Lcd Library mikroBasic PRO for PIC32 provides a library for operating Graphic Lcd 128x64 with commonly used Samsung KS108 KS107 controller For creating a custom set of Glcd images use Glcd Bitmap Editor Tool Library Dependency Tree Gicd J Glcd Fonts MikroElektronika 296 mikroBasic PRO for PIC32 External dependencies of Graphic Lcd Library The following variables must be defined in all projects using Graphic Lcd Description Library dim GLCD DO Direction as sbit n dim GLCD D0 Direction as sbit at ias Direction of the Data 0 pin x IT sfr external TRISBO bit dim GLCD D1 Direction as sbit g x dim GLCD D1 Direction as sbit at e Direction of the Data 1 pin n sfr external TRISB1 bit dim GLCD D2 Direction as sbit dim GLCD D2 Direction as sbit Direction of the Data 2 pin dios sfr external at TRISF2 bit dim GLCD D3 Direction as i p tion as sbit a sic cbusnad Direction of the Data 3 pin dim
285. e 1 black and 2 inverts each dot Requires Glcd needs to be initialized see Glcd Init routine Use Glcd Set Fontto specify the font for display if no font is specified then default Font Gicd System5x7 font supplied with the library will be used Write character C on the position 10 inside the page 2 Gled Write Chari 10 2 1 For x axis and page layout explanation see schematic at the bottom of this page Glcd Write Text Prototype sub procedure Glcd Write Text dim byref text as string dim x pos page num color as 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 see Glcd Init routine Use Glcd Set Fontto specify the font for display if no font is specified then default Font Gicd System5x7 font supplied with the library will be used Write text Hello world on the position 10 inside the page 2 Glcd Write Text Hello world 10 2 1 For x axis and page layout explanation see schematic at the bottom of this page MikroElektronika 308 mikroBasic PRO for PIC32 Glcd Image Prototype sub procedure Glcd Image dim byref constimage as byte Description Displays bitmap on Gl
286. e as 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 cn found in s if no matching character was found the function returns OxFFFF txt mikroElektronika wp res strchr txt E routine will locate the character E in the txt string and return the position of the character Prototype sub function strcmp dim byref sl s2 as string as integer Description The function lexicographically compares the contents of the strings s1 and s2 and returns a value indicating their relationship Value Meaning 0 si less than 82 sl equal to s2 gt 0 sl greater than s2 The value returned by the function is determined by the difference between the values of the first pair of words that differ in the strings being compared txt mikroElektronika txt sub mikr res strcomp txt txt sub v compares strings txt and txt sub and returns returns a difference between the first differing characters in this case 69 599 MikroElektronika mikoBasic PRO for PIC32 strcpy Prototype sub procedure strcpy dim byref s1 s2 as string The function copies the value of the string s2 to the string s1 and appends a null character to the end of s1 txt mikroElektronika Ext sub mikr strcp
287. e loopl loop2 as byte i size as longint Buffer as byte 512 UART write text and new line carriage return line feed sub procedure UART1 Write Line dim byref uart text as string UART1 Write Text uart text UART1 Write 13 UART1 Write 10 end sub xin EE Creates new file and writes some data to it sub procedure M Create New File filename 7 A Cf Fat Set File Date 2005 6 21 10 35 0 Set file date amp time info Cf Fat Assign filename OxAO0 Will not find file and then create file Cf Fat Rewrite To clear file and start with new data for loopl 1 to 99 We want 5 files on the MMC card UART1 Write MikroElektronika 214 mikroBasic PRO for PIC32 file contents 0 loopl div 10 48 file contents 1 loopl mod 10 48 Cf Fat Write file contents LINE LEN 1 write data to the assigned file next loopl end sub E Creates many new files and writes data to them sub procedure M Create Multiple Files for loop2 B to z UART1 Write loop2 this line can slow down the performance filename 7 loop2 set filename Cf Fat Set File Date 2005 6 21 10 35 0 Set file date amp time info Cf Fat Assign filename OxAO0 find existing file or create a new one Cf Fat Rewrite To clear file and start with new data for loopl 1 to 44 file contents 0 loopl div 10 48 file contents 1 loopl mod 10 48 Cf Fat Write file contents LINE LEN 1 write data
288. e routine code is generated in the place of the call so the call doesn t count against the nested call limit Parameters time in ms delaytime in milliseconds Valid values constant values range of applicable constants depends on the oscillator frequency eum MM SSS Example Delay ms 1000 One second pause Notes For generating delays wih varabe as input parameter use We Vaelay_ms route Vdelay_ms Prototype sub procedure Vdelay ms dim time in ms as 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 pause 1000 viela pi ms pause one second pause 152 MikroElektronika mikoBasic PRO for PIC32 VDelay Advanced ms Prototype sub procedure VDelay advanced ms dim time ms Current Fosc kHz as word Description Creates a software delay in duration of time in ms milliseconds a variable for a given oscillator frequency Generated delay is not as precise as the delay created by Delay ms Note that Vdelay_ ms is library function rather than a built in routine it is presented in this topic for the sake of convenience Parameters time ms delay time in milliseconds Current Fosc kHz desiredoscillator frequency pause 1000 fosc 10000 VDelay advanced ms pause fosc Generates approximately one second pause for a osci
289. e HID Enable while Gen Read readbuff 64 1 wend i e aooo Gen Write Prototype sub function Gen Write dim writebuff as byte dim as length as byte dim ep as byte as 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 while Gen Write writebuff 64 1 wend lt lt 019 MikroElektronika mikoBasic PRO for PIC32 Library Example This example establishes connection with the HID terminal that is active on the PC Upon connection establishment the HID Device Name will appear in the respective window After that software will wait for data and it will return received data back Examples uses USBdsc mbas descriptor file which is in the same folder and can be created by the HID Terminal Copy Code To Clipboard program HID Write Polling dim cnt kk as char dim readbuff as char 64 dim writebuff as char 64 main CHECON 0x32 ADIPCFG OxFFFF HID Enable readbuff writebuff while TRUE USB Polling Proc Call this routine periodically kk HID Read if kk 0 then for cnt 0 to 63 writebuff cnt readbuff cnt next cnt HID Write writebuff 64 end if wend end HW Co
290. e Send Prototype sub procedure RS485Slave Send dim byref data as byte 20 dim datalen as byte Description 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 O 3 Nothing Requires MCU must be initialized as a Slave for RS 485 communication See RS485Slave Init It is the user s responsibility to ensure by protocol that only one device sends data via 485 bus at a time dim msg as byte 8 send 2 bytes of data to the Master RS485Slave Send msg 2 381 MikroElektronika mikoBasic PRO for PIC32 Library Example The example demonstrates RS 485 communication Master sends message to Slave with address 160 and waits for a response After the response is received the first byte of received data is incremented and sent back to the Slave The received data is displayed on PORTB while error on receiving OxAA and number of consecutive unsuccessful retries are displayed on PORTD Hardware configurations in this example are made for the LV 32MX v6 board and PIC32MX460F512L Copy Code To Clipboard program RS485 Master Example dim dat as byte 10 buffer for receving sending messages i j as byte cnt as longint dim rs485 rxtx pin as sbit at RF2 bit set transcieve pin rs485 rxtx pin direction as sbit at TRISF2 bit set transcieve pin direction Interrupt routine sub procedure in
291. e To Clipboard program RTC Read dim seconds minutes hours Software I2C connections dim Soft I2C Scl Soft I2C Sda Soft I2C Scl Direction as Soft I2C Sda Direction as End Software I2C connections sbit sbit sbit sbit as as LCD module connections dim LCD RS as sbit at LATB2 bit dim LCD EN as sbit at LATB3 bit dim LCD D4 as sbit at LATB4 bit dim LCD D5 as sbit at LATB5 bit dim LCD D6 as sbit at LATB6 bit dim LCD D7 as sbit at LATB7 bit dim LCD RS Direction as sbit dim LCD EN Direction as sbit dim LCD D4 Direction as sbit dim LCD D5 Direction as sbit dim LCD D6 Direction as sbit dim LCD D7 Direction as sbit End LCD module connections sub procedure Read Time Soft I2C Start t Soft_I2C_Write 0xA0 t Soft I2C Write 2 i Soft I2C Start N Soft I2C Write 0xA1 seconds Soft I2C Read 1 1 minutes Soft I2C Read 1 3 hours Soft I2C Read 1 i day Soft I2C Read 1 i month _ Soft I2C Read 0 Soft I2C Stop end sub cccuccceE cce Formats date sub procedure Transform Time day month year as byte Global date time variables at RF3 bit at RF4 bit at TRISF3 bit at TRISF4 bit at TRISB2 bit at TRISB3 bit at TRISB4 bit at TRISB5 bit at TRISB6 bit at TRISB7 bit time and date information from RTC PCF8583 Issue start signal Address PCF8583 see PCF8583 datasheet Start from address 2 Issue repeated start signal Address PCF8583 for reading R W
292. e a valid identifier A declaration starting with the typedef 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 t ypedef 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 mikroBasic PRO for PIC32 For example Let s declare a synonym for word typedef Distance as word Now synonym Distance can be used as type identifier dim i as Distance declare variable i of word In the typedef declaration as in any other declaration several types can be declared at once For example typedef Pti Array 10 as byte Here Pt i is a synonym for type pointer to int and Array is a synonym for type array of 10 byte elements Type Qualifiers The type qualifiers const and volatile are optional in declarations and do not actually affect the type of declared object Qualifier const The qualifier const implies that a declared object will not change its value during runtime In declarations with the const qualifier all objects need to be initialized The mikroBasic PRO for PIC32 treats objects declared with the const qualifier the same as literals or preprocessor constants If the user tries to change an object declared with the const qualifier compiler will report an error For example
293. e for the Manchester receiver it shows how to use the Manchester Library for receiving data Copy Code To Clipboard LCD module connections dim LCD RS as sbit at LATB2 bit CD EN as sbit at LATB3 bit LCD D4 as sbit at LATB4 bit LCD D5 as sbit at LATB5 bit LCD D6 as sbit at LATB6 bit LCD D7 as sbit at LATB7 bit dim LCD RS Direction as sbit at TRISB2 bit CD EN Direction as sbit at TRISB3 bit LCD D4 Direction as sbit at TRISB4 bit LCD D5 Direction as sbit at TRISB5 bit LCD D6 Direction as sbit at TRISB6 bit LCD D7 Direction as sbit at TRISB7 bit End LCD module connections Manchester module connections dim MANRXPIN as sbit at RFO bit MANRXPIN Direction as sbit at MANTXPIN as sbit at LATF1 bit MANTXPIN Direction as sbit at TRISF1 b End Manchester module connections RISF0 b dim error flag ErrorCount counter temp a main ErrorCount counter 0 0 CHECON ADIPCFG Lcd Init Lcd Cmd 0x32 OxFFFF CD CLEAR 0 Man Receive Ini while TRUE Lcd Cmd LCD FIRST ROW while TRUE temp if temp break end if if error flag lt gt 0 break end if wend an Receiv 0x0B error flag then then it it S byte Configure AN pins as digital I O Initialize LCD Clear LCD display Initialize Receiver Endless loop Move cursor to the 1st row Wait for the start byte Attempt byte receive Start byte see Transmi
294. e for use in a program during the runtime of that program Dynamically allocated memory exists until it is released This is in contrast to static memory allocation which has a fixed duration It is said that an object so allocated has a dynamic lifetime The heap memory size can be configured in the Edit Project window Also user can override heap memory size in the code by setting the HEAP _ SIZE constant Library Routines Heap Init GetMem FreeMem MM LargestFreeMemBlock MM TotalFreeMemSize Heap Init Returns Nothing o const HEAP SIZE 3000 declare Heap siz Heap Init set Heap size GetMem een sub procedure GetMem dim byref P as longword dim WantedSize as word Fetches memory from the memory heap Parameters WantedSize pointer to the fetched memory WantedSize size in bytes of the dynamic variable to allocate Returns a pointer to the fetched memory of WantedSize bytes in P if success Otherwise 0 no free blocks of memory are large enough GetMem ptr 20 sizeof PBuffer ptr will point to a memory block where PBuffer is allocated Notes None OOOO MikroElektronika 334 mikroBasic PRO for PIC32 FreeMem Prototype sub procedure FreeMem dim byref P as longword dim ActualSize as word Description FreeMem destroys the variable referenced by P and returns its memory to the heap Parameters P variable of any pointer type previously assigne
295. e has to be initialized See SPI Ethernet 24j600 Init dim buffer as byte lt gt Ethernet 245600 getByte read a byte from ENC24J600 buffer M MikroElektronika mikoBasic PRO for PIC32 SPI Ethernet 24j600 getBytes Prototype sub procedure SPI Ethernet 243600 getBytes dim ptr as byte dim addr as word dim n as word Description This is MAC module routine It fetches equested number of bytes from xNC243600 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 ENC245600 RAM addr ENC247600 RAM start address Valid values 0 8192 n number of bytes to be read Ethernet module has to be initialized See SPI Ethernet 24j600 Init dim buffer as byte 16 SPI Ethernet 24600 getBytes buffer 0x100 16 read 16 bytes starting from address 0x100 SPI Ethernet 24j600 UserTCP Prototype sub function SPI Ethernet 24j600 UserTCP dim byref remoteHost as byte 4 dim remotePort as word dim localPort as word dim reqLength as word dim byref flags as TEthJ600PktFlags as 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
296. e letter x in the routine prototype for a number from 1 to 3 Number of SPI modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library SPIx Write Requires Routine requires at least one SPI module Used SPI module must be initialized before using this function See the SPIx Init and SPIx Init Advanced routines write a byte to the SPI bus dim buffer as byte SPI1 Write buffer SPI library routines require you to specify the module you want to use To select the desired SPI module simply change the letter x in the routine prototype for a number from 1 to 3 Number of SPI modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 409 MikroElektronika mikoBasic PRO for PIC32 SPI Set Active Prototype sub procedure SPI Set Active dim read ptr as TSpi Rd Ptr dim write ptr as TSpi Wr Ptr 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 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 SPI Set Active SPI1 Read SPI1 Write Sets the SPI1 module active Number of SPI modules per MCU differs from chip to chip Please re
297. e of every project See Program Organization for more information Label should be followed by end of line CR otherwise compiler will report an error Here is an example of an infinite loop that calls the procedure Beep repeatedly loop Beep goto loop Symbols mikroBasic PRO for PIC32 symbols allow you to create simple macros without parameters You can replace any line of code with a single identifier alias Symbols when properly used can increase code legibility and reusability Symbols need to be declared at the very beginning of the module right after the module name and optional inciude clauses Check Program Organization for more details Scope of a symbol is always limited to the file in which it has been declared Symbol is declared as symbol alias code Here alias must be a valid identifier which you will use throughout the code This identifier has a file scope The code can be any line of code literals assignments function calls etc Using a symbol in the program consumes no RAM the compiler will simply replace each instance of a symbol with the appropriate line of code from the declaration Here is an example symbol MAXALLOWED 216 Symbol as alias for numeric value symbol PORT PORTC v Symbol as alias for SFR symbol MYDELAY Delay ms 1000 Symbol as alias for procedure call dim cnt as byte Some variable MikroElektronika 196 mikroBasic PRO for PIC32 M main if
298. e single and multidimensional array subscripts dim alphabet as byte 30 alphabet 2 c For more information refer to Arrays MikroElektronika 186 mikroBasic PRO for PIC32 Parentheses Parentheses are used to group expressions isolate conditional expressions and indicate function calls and function parameters d ec a b Override normal precedence if da z then Useful with conditional statements fune Function call no arguments sub function func2 dim n as word Function declaration w 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 dim i j k as word The comma also separates elements in initialization lists of constant arrays const MONTHS as byte 12 31 28 31 30 31 30 31 31 30 31 30 31 Colon Colon is used to indicate a labeled statement Start nop goto start For more information refer to Labels Dot Dot indicates access to a structure member For example person surname Smith For more information refer to Structures Dot is a necessary part of floating point literals Also dot can be used for accessing individual bits of registers in mikroBasic PRO for PIC32 187 MikroElektronika mikoBasic PRO for PIC32 Program Organizatio
299. e sub procedure SPI T6963c set cursor dim x y as byte y Cursor position column number Reus Ni yS Example SPI T6963c set cursor cposx cposy Notes Nang O OOOO SPI T6963C clearBit Prototype sub procedure SPI T6963C clearBit dim b as byte Clears control port bit s b bit mask The function will clear bit on control port if bit x in bit mask is set to 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine clear bits 0 and 1 on control port SPI T6963C clearBit 0x0003 MikroElektronika 496 mikroBasic PRO for PIC32 SPI T6963C setBit Prototype sub procedure SPI T6963C setBit dim b as byte Description Sets control port bit s Parameters b bit mask The function will set bit x on control port if bit x in bit mask is set to 1 Nothing Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine set bits 0 and 1 on control port SPI T6963C setBit 0x0003 None SPI T6963C negBit sub procedure SPI T6963C negBit dim b as byte Negates control port bit s b bit mask The function will negate bit x on control port if bit x in bit mask is set to 1 Nothing Toshiba Glcd module needs to be initialized See SPI T6963C Config routine peus negate bits 0 and 1 on control port SPI T6963C negBit 0x0003 Notes None SPI T6963C displayGrPanel Prototype sub procedure SPI T6963C displayGrPanel dim n as
300. e 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 nins 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 dim year as word month day hours mins as byte Mmc Fat Get File Date Modified year month day hours mins Mmc Fat Get File Size Returns This function retums size ofactive fie Ga bye 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 dim my file size as longword my file size Mmc Fat Get File Size MikroElektronika 348 mikroBasic PRO for PIC32 Mmc Fat Get Swap File Prototype i Parameters MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init sub function Mmc Fat Get Swap File dim sectors cnt as longword dim byref fllename as string 11 dim file attr as byte as longword This function is used to create a swap fi
301. eaching the cursor position Ctrl F8 Toggle Preakpoint Toggle breakpoints option sets new breakpoints or removes those F5 a already set at the current cursor position aad Related topics Run Menu Debug Toolbar MikroElektronika 132 mikroBasic PRO for PIC32 CHAPTER 6 mikroBasic PRO for PIC32 Specifics The following topics cover the specifics of mikroBasic PRO for PIC32 compiler Basic Standard Issues Predefined Globals and Constants Accessing Individual Bits Interrupts Linker Directives Built in Routines Code Optimization 133 MikroElektronika mikoBasic PRO for PIC32 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 a See also Linker Directives Basic Standard Issues Divergence from the Basic Standard Function recursion is not supported because of no easily usable sta
302. ead Byte 0 1 Expander Write Byte Prototype sub procedure Expander Write Byte dim ModuleAddress RegAddress Data as byte Routine writes a byte to Port Expander Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page RegAddress Port Expander s internal register address bata data to be written Retums Byte read Port Expander must be initialized See Expander Init Write a byte to the Port Expander s register Expander Write Byte 0 1 FF Expander Read PortA Prototype sub function Expander Read PortA dim ModuleAddress as byte as 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 dim read data as byte Expander Set DirectionPortA 0 S FF set expander s porta to be input Expander Read PortA 0 MikroElektronika 360 mikroBasic PRO for PIC32 Expander Prototype Description Parameters Requires Expander Prototype Read PortB sub function Expander Read PortB dim ModuleAddress as byte as byte The function reads byte from Port Expander s PortB ModuleAddress Port Expander h
303. ecial Function Keys Table special is a flag for special function keys F1 Enter Esc etc If key pressed is one of these special Will be set to 1 otherwise O pressed is set to 1 if the key is pressed and O if it is released 1 if reading of a key from the keyboard was successful 0 if no key was pressed PS 2 keyboard needs to be initialized See Ps2 Config routine dim value special pressed as word Press Enter to continue do if Ps2 Key Read value special pressed then if value 13 and special 1 then break end if end if loop until 0 1 369 MikroElektronika mikoBasic PRO for PIC32 Special Function Keys 7 F8 F9 F10 F11 F12 Enter Page Up Page Down Backspace Insert Delete Windows Ctrl Shift Alt Print Screen Pause Caps Lock Home Scroll Lock Num Lock Left Arrow Right Arrow Up Arrow Down Arrow Escape Tab Value returned 10 11 12 13 14 15 16 17 19 1 28 1 32 33 34 je joo C a 2 3 C ee C ee io eo jo eS 9 2 33 jaa pu MikroElektronika 310 mikroBasic PRO for PIC32 Library Example This simple example reads values of the pressed keys on the PS 2 keyboard and sends them via UART Copy Code To Clipboard program PS2 Example dim keydata special down as byte dim PS2 Data as sbit at RDO bit PS2 Clock as sbit at RD1 bit PS2 Data Direction as sbit at TRISDO bit PS2 Clock Direction as sbit at TRIS
304. ection thus selecting the text Editor Colors Options Editor Settings Editor Colors Auto Correct Auto Complete fq e Style Dutput Editor Colors Current Scheme Office 2003 Blue I New Scheme Scheme Setup Element Assembler Binary Character Comment Float Hexadecimal Identifier Illegal Char Number Octal Preprocessor Reserved Word Space String Symbol Web link Text Attributes Bold E Underline Foreground Black ivi Italic Background NEN Black T Strikeout i Active Line Color T Custom Gutter Colors Gradient From V Show Active Line Gradient To E Sky Blue C white Font m oe Delete DEFINE PWM_ SEQUENCE ON mikoBasic PRO for PIC32 Editor Colors option allows user to set change and save text and color settings organized in schemes Schemes represent custom graphical appearance that can be applied to GUI Graphical User Interface to satisfy tastes of different users Auto Correct Auto Correct option facilitates the user in such a fashion that it automatically corrects common typing or spelling errors as it types Options Auto Correct Editor Settings V Enable Auto Correct aF add Original Replacement t 6 Remove Editor Colors e Auto Correct Auto Complete v5 Advanced V Correct Case to Match Declaration
305. edure FloatToStr dim fnum as float dim byref str as string 20 as 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 dim ffl ff2 ff3 as float txt as string 20 ffl 374 2 If2 123 456789 ff3 0 000001234 PloatToStr ffl txt r Ext xg 972 2 EIocatToStr fft2 tst Y G66 ms 223 8567 FPloatToStr ffi txt Y txt zs l 234e 6 Notes Given floating point number will be truncated to 7 most significant digits before conversion WordToStrWithZeros Prototype sub procedure WordToStrWithZeros dim input as word dim byref output as string 5 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 zeros Parameters input unsigned integer to be converted output destination a S Returns Non s o dim t as word txt as stringi5 437 WordToStrWithZeros t txt txt 16 004374 MikroElektronika 586 mikroBasic PRO for PIC32 IntToStrWithZeros Prototype sub E 9 IntToStrWithZeros dim input as integer dim byref output as string 6 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 in
306. ee the SPIx Init and SPIx Init Advanced routines mE ehternet NIC pinout dim SPI Ethernet RST as sbit at LATFO bit dim SPI Ethernet CS as sbit at LATF1 bit dim SPI Ethernet RST Direction as sbit at TRISFO bit dim SPI Ethernet CS Direction as sbit at TRISF1 bit end mE ehternet NIC pinout const SPI Ethernet HALFDUPLEX 0 const SPI Ethernet FULLDUPLEX 1 myMacAddr as byte 6 my MAC address mylpAddr as byte 4 my IP addr myMacAddr 0 0x00 myMacAddr 1 0x14 myMacAddr 2 0xA5 0x76 0x19 Ox3F myMacAddr 3 myMacAddr 4 myMacAddr 5 mylIpAddr 0 192 mylIpAddr 1 168 mylpAddr 2 20 myIpAddr 3 60 SPIl Init SPI Ethernet Init myMacAddr myIpAddr SPI Ethernet FULLDUPLEX MikroElektronika 416 mikroBasic PRO for PIC32 SPI Ethernet Enable Prototype sub procedure SPI Ethernet Enable dim enFlt as byte Description This is MAC module routine This routine enables appropriate network traffic on the ENC28J60 module by the means of it s receive filters unicast multicast broadcast crc Specific type of network traffic will be 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 Patte
307. ees JUL Contrast Adjustment ovccs VCCS Lcd HW connection by default initialization using SPI Lcd Init MikroElektronika 418 mikroBasic PRO for PIC32 SPI Lcd8 8 bit interface Library The mikroBasic PRO for PIC32 provides a library for communication with Lcd with HD44780 compliant controllers in 8 bit mode via SPI interface For creating a custom set of Lcd characters use Lcd Custom Character Tool Important When using this library with PIC32 family MCUs be aware of their voltage incompatibility with certain number of Lcd modules So additional external power supply for these modules may be required The library uses the SPI module for communication The user must initialize the appropriate SPI module before using the SPI Lca8 Library For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by using the SPI Set Active routine See the SPI Library functions This Library is designed to work with the mikroElektronika s Serial Lcd Glcd Adapter Board pinout see schematic at the bottom of this page for details Library Dependency Tree m Port Expander SPI Lcd8 E 9i 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
308. elements of type byte main ptrl a 4 ptr2 a 2 if ptrl ptr2 then i won t be executed as 4 is not equal to 2 if ptrl gt ptr2 then will be executed as 4 is greater than 2 if ptrl ptr2 then if the value pointed to by ptrl is equal to the value pointed to by ptr2 if ptrl gt ptr2 then if the value pointed to by ptrl is greater to the value pointed to by ptr2 end Note Comparing pointers pointing to different objects arrays can be performed at programmer s own responsibility a precise overview of data s physical storage is required MikroElektronika 208 mikroBasic PRO for PIC32 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 dim a as byte 10 array a containing 10 elements of type byte ptr as byte pointer to byte main ptr Qa 0 v ptr is pointer to byte pointing to a 0 ptr ptr 3 ptr 3 is a pointer
309. elete 347 Mmc Fat Write 348 Mmc Fat Set File Date 348 Mmc Fat Get File Date 349 Mmc Fat Get File Date Modified 350 Mmc Fat Get File Size 350 Mmc Fat Get Swap File 351 Library Example 352 HW Connection 356 OneWire Library 357 Library Routines 357 Ow Reset 357 Ow Read 358 Ow Write 358 Port Expander Library 359 Library Dependency Tree 359 External dependencies of Port Expander Library 359 Library Routines 359 Expander Init 360 Expander Init Advanced 361 Expander Read Byte 362 Expander Write Byte 362 Expander Read PortA 362 Expander Read PortB 363 Expander Read PortAB 363 Expander Write PortA 364 Expander Write PortB 364 Expander Write PortAB 365 Expander Set DirectionPortA 365 Expander Set DirectionPortB 366 Expander Set DirectionPortAB 366 Expander Set PullUpsPortA 366 Expander Set PullUpsPortB 367 Expander Set PullUpsPortAB 367 Library Example 368 HW Connection 369 PS 2 Library 370 External dependencies of PS 2 Library 370 15 MikroElektronika mikoBasic PRO for PIC32 Library Routines 370 Ps2 Config 371 Ps2 Key Read 371 Special Function Keys 372 Library Example 373 HW Connection 374 PWM Library 374 Library Routines 374 PWM Init 375 PWM Init Advanced 375 PWM Set Duty 376 PWM Start 376 PWM Stop 376 Library Example 377 HW Connection 378 RS 485 Library 379 Library Dependency Tree 379 External dependencies of RS 485 Library 379 Library Routines 380 RS485Master_Init 380 RS485Master Receive 381 RS485Master Send 38
310. emove All Select variable from list text Search for variable by assembly name text 4 Peripherals Freeze Name Value Address text db 0x0800 PC 0x000280 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 main ADPCFG OxFFFF gt 24 text mikroElektronika Lcd Init Lcd Cmd LCD CLEAR E Lcd Cmd LCD CURSOR OFF Led Chr i i text i 1 TID iaca s next i end Watch Values Eh E Eh 90 oe of e E fu b Add Remove gt Properties tq AddAll kg Remove All Select variable from list text Search for variable by assembly name _text Peripherals Freeze Name Value Address text dE 0x0800 PC 0x00028A 0 10us 117 MikroElektronika mikoBasic PRO for PIC32 Step Into F7 Step Over F8 and Step Out Ctrl F8 are mikrolCD debugger functions that are used in stepping mode There is also a Real Time mode supported by the mikrolCD Functions that are used in the Real Time mode are Run Pause Debugger F6 and Run to cursor F4 Pressing F4 executes the code until the program reaches the cursor pos
311. en listing file in editor View statistics for current project 19 MikroElektronika mikoBasic PRO for PIC32 Layout Toolbar Styles toolbar allows you to easily customize workspace through a number of different IDE layouts ia i 1024x758 Debug layout Default Legacy Messages C BesWpion IT Delete the selected layout Save the current layout Set the selected layout Help Toolbar 9 2 Help Toolbar provides access to information on using and registering compilers Icon A How To Register Related topics Keyboard shortcuts Integrated Tools MikroElektronika 80 mikroBasic PRO for PIC32 Customizing IDE Layout Docking Windows You can increase the viewing and editing space for code depending on how you arrange the windows in the IDE Step 1 Click the window you want to dock to give it focus Project Manager om B Sources Bj Lcd mbas Binaries 73 Project level defines Image Files EEPROM Files 7 Active Comments Files B Output Files ES Lcd hex EZ Lcd asm Other Files Step 2 Drag the tool window from its current location A guide diamond appears The four arrows of the diamond point towards the four edges of the IDE D 81 MikroElektronika mikoBasic PRO for PIC32 Step 3 Move the pointer over the corresponding portion of the guide diamond An outline of the window appears in the designated area E an cu Step 4 T
312. entations except float are unsigned by default For signed representation click the check box next to the Signed label B Edit Value PORTB Representation S Dec O Hex O Bin O Float O Char C Signed OK Cancel An item s value can also be changed by double clicking item s value field and typing the new value directly 121 MikroElektronika mikoBasic PRO for PIC32 RAM Window The RAM Window is available from the drop down menu View Debug Windows RAM The RAM Window displays the map of MCU s RAM with recently changed items colored red The user can edit and change the values in the RAM window mikrolCD Specific RAM window content will be written to the MCU before the next instruction execution Lcd4bit mikroE ikroElektronike EasydsPIC4 Stopwatch Window The Software Simulator Stopwatch Window is available from the drop down menu View Debug Windows Stopwatch The Stopwatch Window displays a Current Count of cycles time since the last Software Simulator action Stopwatch measures the execution time number of cycles from the moment Software Simulator has started and can be reset at any time Delta represents the number of cycles between the lines where Software Simulator action has started and ended Watch Clock Cycles Time Current Count 2 103 943 273 105 205 Delta 80 881 413 4044 07 ms Stopwatch 2 103 943 273 105197 16 ms Reset To Zero
313. er as TSPI Ethernet 24j600 UserTCP dim UDPHandler as TSPI Ethernet 243600 UserUDP Description Sets pointers to User TCP and UDP handler function implementations which are automatically called by SPI Ethernet ENC24J600 library Parameters TCPHandler TCP request handler UDPHandler UDP Mu o I Ie handler Returns Nothing eee SPI Ethernet 24j600 UserTCP and SPI_Ethernet_24j600_UserUDP have to be previously defined SPI Ethernet 243600 setUserHandlers CSPI Ethernet 245 600 UserTCP Ethernet 243600 UserUDP 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 SPI Ethernet 24j600 getlpAddress LN Prototype sub function SPI Ethernet 243600 getIpAddress as word 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 di ipAddr as byte 4 user IP address buffer memcpy ipAddr SPI Ethernet 245 600 getIpAddress 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 MikroElektronika 450 mikroBasic PRO for PIC32 SPI Ethe
314. er defined data types and labels All these program elements will be referred to as objects throughout the help don t be confused with the meaning of object in object oriented programming Identifiers can contain letters from a to z and A to 7 the underscore character must be a letter or an underscore i e identifier cannot begin with a numeral Case Sensitivity mikroBasic PRO for PIC32 is not case sensitive so Sum sum and suM are equivalent identifiers 185 and digits from 0 to 9 First character MikroElektronika mikoBasic PRO for PIC32 Uniqueness and Scope Although identifier names are arbitrary within the rules stated errors result if the same name is used for more than one identifier within the same scope Simply duplicate names are illegal within the same scope For more information refer to Scope and Visibility Identifier Examples Here are some valid identifiers temperature V1 Pressure to ALE dat2string SUM3 vtext and here are some invalid identifiers temp NO cannot begin with a numeral shigher NO cannot contain special characters am NO cannot match reserved word j23 07 04 NO cannot contain special characters dot Punctuators The mikroBasic PRO for PIC32 punctuators also known as separators are Brackets Parentheses Comma Colon Dot Most of these punctuators also function as operators Brackets Brackets indicat
315. erator sizeof cannot be applied to a function 221 MikroElektronika mikoBasic PRO for PIC32 Expressions An expression is a sequence of operators operands and punctuators that returns a value The primary expressions include literals constants variables and function calls From them using operators more complex expressions can be created 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 mikroBasic PRO for PIC32 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 as byte as word as integer Gt a word level a c integer level b c integer level Left side exception In arithmetic expression left side is considered in the following manner If the left side size in bytes is greater than higher operand size then evaluation is done at one level above higher operand level to get correct ca
316. erl interrupts end The Software UART library implements time based activities so interrupts need to be disabled when using it MikroElektronika mikoBasic PRO for PIC32 Library Example This example demonstrates simple data exchange via software UART If MCU is connected to the PC you can test the example from the mikroBasic PRO for PIC32 USART communication terminal launch it from the drop down menu Tools gt USART Terminal or simply click the USART Terminal Icon Copy Code To Clipboard program Soft UART dim error as byte counter byte read as byte main CHECON 0x32 ADIPCFG OxFFFF TRISB 0x00 PORTB 0 error Soft UART Init PORTF if error gt 0 then PORTB error while TRUE nop wend end if Delay ms 100 for counter z to A step 1 Soft UART Write counter Delay ms 100 next counter while TRUE Y Y 25 8 Auxiliary variables Configure AN pins as Set PORTB as output digital I O error signalization No error 56000 Y 0 Initialize Soft UART at 56000 bps Signalize Init error Stop program Send bytes from z downto A Endless loop byte read Soft UART Read error Read byte then test error flag if error lt gt 0 then If error was detected PORTB error i signal it on PORTB else Soft UART Write byte read If error was not detected return byte read end if wend end MikroElektronika 400 m
317. ers 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 cee Gled Select Side Notes For side x axis and page T explanation see schematic at the bottom of this page Glcd Set X Parameters x pos position on x axis Valid values 0 63 Rtuns No Rampe erca sees OOO Notes Forside x axis and page layout explanation see schematic at the bottom ofthis page Glcd Set Page eum Noting Glcd needs to be initialized see Glcd Init routine Example era setae CS Notes For side x axis and page layout explanation see schematic at the bottom of this page MikroElektronika 300 mikroBasic PRO for PIC32 Glcd Read Data Requires Glcd needs to be initialized see Glcd Init routine Glcd side x axis position and page should be set first See functions Glcd Set Side Glcd Set X and Glcd Set Page dim data as byte Gled Read Data data Glcd Read Data This routine needs to be called twice After the first call data is placed in the buffer register After the second call data is passed from the buffer register to data lines Glcd Write Data Prototype sub procedure Glcd Write Data dim data as byte Noth
318. esired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library UARTx Write Text ums Wohn Requires Routine requires at least one UART module Used UART module must be initialized before using this routine See UARTx Init and UARTx Init Advanced routines UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Read text until the sequence OK is received and send back what s been received UART1 Init 4800 initialize UART module Delay ms 100 while TRUE if UART1 Data Ready 1 if data is received UART1 Read Text output OK 10 reads text until OK is found UART1 Write Text output sends back text end if wend 567 MikroElektronika mikoBasic PRO for PIC32 UART Set Active Prototype sub procedure UART Set Active dim read ptr as TUART Rd Ptr dim write ptr as TUART Wr Ptr dim ready ptr as TUART Rdy Ptr dim tx idle ptr as TUART TX Idle Ptr Description Sets active UART module which will be used by UARTx Data Ready UARTx Read and UARTx Write routi
319. ess opmode bits CANSPI CONFIG FLAGS Constants The CANSPI CONFIG FLAGS constants define flags related to the CANSPI module configuration The functions CANSPIInit CANSPISetBaudRate CANSPISetMask and CANSPISetFilter expect one of these or a bitwise combination as their argument Copy Code To Clipboard const CANSPI CONFIG DEFAULT as byte SFF FILIALI CANSPI CONFIG PHSEG2 PRG BIT as byte 01 CANSPI CONFIG PHSEG2 PRG ON as byte SFF XXXXXXX1 CANSPI CONFIG PHSEG2 PRG OFF as byte SFE XXXXXXX0 CANSPI CONFIG LINE FILTER BIT as byte 02 CANSPI CONFIG LINE FILTER ON as byte SFF XXXXXX1X CANSPI CONFIG LINE FILTER OFF as byte SFD XXXXXXOX CANSPI CONFIG SAMPLE BIT as byte 04 CANSPI CONFIG SAMPLE ONCE as byte SFF XXXXX1XX CANSPI CONFIG SAMPLE THRICE as byte SFB XXXXXOXX CANSPI CONFIG MSG TYPE BIT as byte 08 CANSPI CONFIG STD MSG as byte SFF XXXX1XXX CANSPI CONFIG XTD MSG as byte SF7 XXXXOXXX CANSPI CONFIG DBL BUFFER BIT as byte 10 CANSPI CONFIG DBL BUFFER ON as byte SFF XXX1XXXX CANSPI CONFIG DBL BUFFER OFF as byte SE XXX OXXXX CANSPI CONFIG MSG BITS as byte 60 CANSPI CONFIG ALL MSG as byte SFF X11XXXXX CANSPI CONFIG VALID XTD MSG as byte SDF X10XXXXX CANSPI CONFIG VALID STD MSG as byte SBF XO1XXXXX CANSPI CONFIG ALL VALID MSG as byte SOF XOOXXXXX MikroElektronika 292 mikroBasic P
320. ession must be enclosed in parentheses Explicit conversion can be performed only on the operand left of the assignment operator Special case is the 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 dim a as byte dim b as short b 1 a byte 5b r a is 255 not d 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 typedef TBytePtr as byte dim arr as word 10 ptr as TBytePtr dim a b cc as byte dim dd as word main a 241 b 128 cc ab equals 113 cc word a b equals 113 dd atb equals 369 ptr TBytePtr Qarr ptr byte Garr end 213 MikroElektronika mikoBasic PRO for PIC32 Typedef Specifier The specifier typedef introduces a synonym for a specified type The typedef declarations are used to construct shorter or more convenient names for types already defined by the language or declared by the user The specifier typede stands first in the declaration typedef synonym as type definition The typedef keyword assigns synonymto type definition The synonym needs to b
321. et 24j600 sendUDP Prototype sub function SPI Ethernet 245 600 sendUDP dim byref destIP as byte 4 dim sourcePort destPort as word dim pkt as byte dim pktLen as word as byte This is UDP module routine It sends an UDP packet on the network Parameters dest IP remote host IP address sourcePort local UDP source port number destPort destination UDP port number pkt packet to transmit pktLen length in bytes of packet to transmit 1 UDP packet was sent successfully 0 otherwise Ethernet module has to be initialized See SPI Ethernet 24j600 Init dim IpAddr as byte 4 remote IP address IpAddr 0 192 IpAddr 0 168 IpAddr 0 1 IpAddr 0 i Ethernet 243600 sendUDP IpAddr 10001 10001 Hello 5 send Hello message to the above IP address from UDP port 10001 to UDP port 10001 453 MikroElektronika mikoBasic PRO for PIC32 SPI Ethernet 24j600 dnsResolve l Prototype sub function SPI Ethernet 245600 dnsResolve dim byref host as string dim tmax as byte as 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
322. ets Port Expander s PortB direction Parameters ModulecAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written to the PortB direction register Each bit corresponds to the appropriate pin of the PortB register Set bit designates corresponding pin as input Cleared bit designates corresponding pin as output Nothing Requires Port Expander must be initialized See Expander Init Set Port Expander s PORTB to be input Expander Set DirectionPortB 0 S FF Expander Set DirectionPortAB Prototype sub procedure Expander Set DirectionPortAB dim ModuleAddress Direction as word Description The function sets Port Expander s PortA and PortB direction Parameters ModulecAddress Port Expander hardware address see schematic at the bottom of this page Direction data to be written to direction registers Data to be written to the PortA direction register are passed in Direction s higher byte Data to be written to the PortB direction register are passed in Direction s lower byte Each bit corresponds to the appropriate pin of the PortA PortB register Set bit designates corresponding pin as input Cleared bit designates corresponding pin as output Nothing Requires Port Expander must be initialized See Expander Init Set Port Expander s PORTA to be output and PORTB to be input Expander Set DirectionPortAB 0 00FF Expander Set PullUpsPortA Prototy
323. eturns EUM of passed string txt mikrol res length txt calculates and returns the length of the txt string 603 MikroElektronika mikoBasic PRO for PIC32 Time Library The Time Library contains functions and type definitions for time calculations in the UNIX time format which counts the number of seconds since the epoch 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 dim tsl as TimeStruct Epoch as longint what is the epoch of the date in ts poch Time dateToEpoch ts1 MikroElektronika 604 mikroBasic PRO for PIC32 Time epochToDate Prototype sub procedure Time epochToDate dim e as longint dim byref ts as TimeStruct ts time and date structure for storing conversion output fetus nonn OOOO y dim ts2 as TimeStruct epoch as longint what date is epoch 1234567890 epoch 1234567890 Time epochToDate epoch ts2 Time dateDiff Prototype sub function Time dateDiff dim byref tl t2 as TimeStruct
324. ever found on asy File creation flag If the file does not exist and this flag is 7 0x80 CM S 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 MIKRO007 TXT 0xAO0 Notes Long File Names LFN are not supported 261 MikroElektronika mikoBasic PRO for PIC32 Cf Fat Reset Prototype sub procedure Cf Fat Reset dim byref size as longword Opens currently assigned file for reading Parameters size buffer to store file size to After file has been open for reading its size is returned through this parameter Requires CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign dim size as longword Cf Fat Reset size Cf Fat Read Prototype sub procedure Cf Fat Read dim byref bdata as byte Description Reads a byte from 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 CF card and CF library must be initialized for file operations See C
325. external MOCHON NST Se pus Fl bit dim T6963C ctrlcd Direction as Direction of the Command im T696 trlcd Direction as sbit sfr external Data pin sbit at 1 FO bit dim T6963C ctrlrst Direction as Direction of the Reset pin dim T6963C ctrlrst Direction as sbit sfr external SPA piii sbit at TRISF4 bit 509 MikroElektronika mikoBasic PRO for PIC32 Library Routines T6963C init T6963C writeData T6963C writeCommand T6963C setPtr T6963C waitReady T6963C fill T6963C dot T6963C write char T6963C write text T6963C line T6963C rectangle T6963C rectangle round edges T6963C rectangle round edges fill T6963C box T6963C circle T6963C circle fill T6963C image T6963C Partiallmage T6963C sprite T6963C set cursor T6963C displayGrPanel T6963C displayTxtPanel T6963C_setGrPanel T6963C setTxtPanel T6963C panelFill T6963C grFill T6963C txtFill T6963C cursor height T6963C graphics T6963C text T6963C cursor T6963C cursor blink MikroElektronika 910 mikroBasic PRO for PIC32 T6963C init Prototype sub procedure 76963C init dim width height fntW as word dim byref data as word dim byref cntrl as word dim wr rd cd rst as 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
326. f A aim Sa CLOG se epe AE PS 2 Clock line dim PS2 Clock as sbit at RBI bit external E dim PS2 Data Direction as sbit A dim PS2 Data Direction as sbit at s r external Direction of the PS 2 Data pin TRISBO bit dim PS2 Clock Direction as sbit b dim PS2 Clock Direction as sbit at See artOHal Direction of the PS 2 Clock pin TRISBl bit Library Routines Ps2 Config Ps2 Key Read MikroElektronika 368 mikroBasic PRO for PIC32 Ps2 Config ums Naim OOOO SSS 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 dim PS2 Data as sbit at RBO bit dim PS2 Clock as sbit at RB1 bit dim PS2 Data Direction as sbit at TRISBO bit dim PS2 Clock Direction as sbit at TRISB1 Nous End of PS2 pinout definition Ps2 Config Init PS 2 Keyboard Ps2 Key Read Prototype sub function Ps2 Key Read dim byref value as byte dim byref special as byte dim byref pressed as byte as 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 Sp
327. f Fat Init File must be previously assigned See Cf Fat Assign File must be open for reading See Cf Fat Reset dim bdata as byte Cf Fat Read bdata MikroElektronika 268 mikroBasic PRO for PIC32 Cf Fat Rewrite Prototype sub procedure Cf Fat Rewrite Description Opens currently assigned file for writing If the file is not empty its content will be erased Nothing Requires CF card and CF library must be initialized for file operations See Cf Fat Init The file must be previously assigned See Cf Fat Assign open file for writing Gf Fat Rewrite Cf Fat Append Prototype sub procedure Cf Fat Append Opens currently assigned file for appending Upon this function execution file pointers will be positioned P after the last byte in the file so any subsequent file writing operation will start from there Nothing Requires CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign open file for appending Cf Fat Append Nts Nm CSS Cf Fat Delete Requires CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign delete current fil Cf Fat Delete None 269 MikroElektronika mikoBasic PRO for PIC32 Cf Fat Write Prototype sub procedure Cf Fat Write dim byref fdata as byte 512 dim data len as word
328. f characters matches that series of characters in the target string so the pattern short would match short in the target string You can cause characters that normally function as metacharacters or escape sequences to be interpreted by preceding them with a backslash For instance metacharacter matches beginning of string but matches character and matches V etc Examples unsigned matches string unsigned unsigned matches string unsigned Escape sequences Characters may be specified using an escape sequences n matches a newline c 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 Vx nnnn char with hex code nnnn one byte for plain text and two bytes for Unicode Nt tab HT TAB same as x09 n newline NL same as x0a Vr car return CR same as x0d form feed FF same as x0c a alarm bell BEL same as x07 ve escape ESC same as x1b Examples unsigned x20int matches unsigned int note space in the middle tunsigned matches unsigned predecessed by tab Character classes You can specify a character class by enclosing a list of characters in which will match any of the characters from the list If the
329. 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 mikroBasic PRO for PIC32 Explicit Path mikroBasic PRO for PIC32 uses internal algorithm to distribute objects within memory If you need to have a variable or routine at the specific predefined address use the linker directives absolute and org When using these directives be sure to use them in proper memory segments i e for functions it is the KSEGO and for variables it is the KSEG1 Linker directives are used with the virtual addresses Directive absolute Directive absolute specifies the starting address in RAM for a variable If the variable is multi byte higher bytes will be stored at the consecutive locations Directive absolute is appended to declaration of a variable Variable x will occupy 1 word 16 bits at address 0xA0000000 dim x as word absolute 0xA0000000 Variable y will occupy 2 words at addresses 0xA0000000 and 0xA0000002 dim y as longint absolute 0xA0000000 Be careful when using the absolute directive as you may overlap two variables by accident For example dim i as word absolute 0xA0000002 Variable i will occupy 1 word at address 0xA00000002 dim jj as longint absolute 0xA0000000 Variable will occupy 2 words at 0xA0000000 and 0xA0000002 thus changing i changes jj at the same time and vice versa Directive org
330. ffer 3 number of message bytes received 1 3 data buffer 4 is setto 255 when message is received data buffer 5 is setto 255 if error has occurred data buffer 6 address of the Slave which sent the message The routine automatically adjusts data 4 and data 5 upon every received message These flags need to be cleared by software Nothing MCU must be initialized as a Master for RS 485 communication See RS485Master Init RS485Master Send Prototype sub procedure RS485Master Send dim byref buffer as byte 20 dim datalen as byte dim address as 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 O 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 ata time dim msg as byte 8 send 3 bytes of data to slave with address 0x12 RS485Master Send msg 3 0x12 319 MikroElektronika mikoBasic PRO for PIC32 RS485Slave Init Rens Noting Requires Global variables R8485 rxtx pin this pin is connected to RE DE input of RS 485 transceiver see schematic at the bottom of this page RE DE signal controls RS 485 transceiver operation mode Valid values 1 for transmitting and 0 for receiving
331. ffer start address 0x19AE transmit buffer end address Ox1FFF RAM buffer read write pointers in auto increment mode receive filters set to default CRC MAC Unicast MAC Broadcast in OR mode flow control with TX and RX pause frames in full duplex mode frames are padded to 60 bytes CRC maximum packet size is set to 1518 Back to Back Inter Packet Gap 0x15 in full duplex mode 0x12 in half duplex mode Non Back to Back Inter Packet Gap 0x0012 in full duplex mode 0x0C12 in half duplex mode Collision window is set to 63 in half duplex mode to accomodate some ENC24 600 revisions silicon bugs CLKOUT output is disabled to reduce EMI generation half duplex loopback disabled LED configuration default LEDA link status LEDB link activity mac RAM buffer containing valid MAC address ip RAM buffer containing valid IP address configuration ethernet negotiation duplex and speed mode settings For this purpose predefined library constants see the list below can be combined using logical AND to form appropriate value Ethernet 24j TO NEGOTIATION ote It is advisable to use only the Auto negotiation setting If manual negotiation is used then duplex and Speed mode setting must be set also Duplex and speed mode may be set only when using manual negotiation AM MikroElektronika mikoBasic PRO for PIC32 Requires Global SPI_ SPI SPI
332. first character after the is the class matches any character not in the list 105 MikroElektronika mikoBasic PRO for PIC32 Examples count aeiou r finds strings countar counter etc but not countbr countcr etc count aeiou r finds strings countbr countcr etc but not countar counter etc Within a list the character is used to specify a range so that a z represents all characters between a and z inclusive If you want itself to be a member of a class put it at the start or end of the list or precede it with a backslash If you want you may place it at the start of list or precede it with a backslash Examples az matches a z and az matches a z and a z matches a z and a z matches all twenty six small characters from a to z n x0D matches any of 10 11 12 13 d t matches any digit or t 1 a matches any char from a Metacharacters Metacharacters are special characters which are the essence of regular expressions There are different types of metacharacters described below Metacharacters Line separators start of line end of line A start of text z end of text any character in line Examples PORTA matches string PORTA only if it s at the beginning of line PORTAS matches string PORTA only if it s at the end of line PORTAS matc
333. following code demonstrates usage of the Lcd Library routines Copy Code To Clipboard LCD module connections dim LCD RS as sbit at LATB2 bit dim LCD EN as sbit at LATB3 bit dim LCD D4 as sbit at LATB4 bit dim LCD D5 as sbit at LATB5 bit dim LCD D6 as sbit at LATB6 bit dim LCD D7 as sbit at LATB7 bit dim LCD RS Direction as sbit at TRISB2 bit dim LCD EN Direction as sbit at TRISB3 bit dim LCD D4 Direction as sbit at TRISB4 bit dim LCD D5 Direction as sbit at TRISB5 bit dim LCD Do Direction as sbit at TRISB6 bit dim LCD D7 Direction as sbit at TRISB7 bit End LCD module connections dim txtl as char 16 txt2 as char 12 txt3 as char 8 txt4 as char 7 i as byte Loop variable sub procedure Move Delay Function used for text moving Delay ms 500 You can change the moving speed here end sub main CHECON 0x32 ADIPCFG OxFFFF Configure AN pins as digital I O txtl mikroElektronika txt2 LV32MX v6 txt3 Led4bit txt4 example Lcd Init Initialize LCD Lcd Cmd LCD CLEAR Clear display Lcd Cmd LCD CURSOR OFF Cursor off LCD Out 1 6 txt3 Write text in first row LCD Out 2 6 txt4 Write text in second row Delay ms 2000 Lcd Cmd LCD CLEAR Clear display LCD Out 1 1 txtl Write text in first row Lcd Out 2 4 txt2 Write text in second row Delay ms 500 Moving text for i 0 to 3 Move text to the right 4 times MikroEle
334. for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in the negative mode i e white text on black background AND Mode The text and graphic data shown on display are combined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C write char A 22 23 T6963C ROM MODE AND 919 MikroElektronika mikoBasic PRO for PIC32 T6963C write text Prototype sub procedure T6963C write char dim byref str as byte 10 dim x y mode as 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 TG968C 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
335. function SPI Ethernet doDHCPLeaseTime as byte Description This is DHCP module routine It takes care of IP address lease time by decrementing the global lease time library counter When this time expires it s time to contact DHCP server and renew the lease 0 lease time has not expired yet 1 lease time has expired it s time to renew it Ethernet module has to be initialized See SPI Ethernet Init while true if SPI Ethernet doDHCPLeaseTime 0 then it s time to renew the IP address lease 429 MikroElektronika mikoBasic PRO for PIC32 SPI Ethernet renewDHCP Prototype sub function SPI Ethernet renewDHCP dim tmax as byte as 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 Init while true if SPI Ethernet doDHCPLeaseTime 0 then SPI Ethernet renewDHCP 5 it s time to renew the IP address lease with 5 secs for a reply 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 p
336. 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 txt mikroElektronika txt sub mikr res strstr txt sub txt 601 MikroElektronika mikoBasic PRO for PIC32 strcspn Prototype sub function strcspn dim byref sl s2 as string as word Description The function searches the string s1 for any of the characters in the string s2 The function returns the index of the first character located in s1 that matches any character in s2 If the first character in s1 matches a character in s2 a value of 0 is returned If there are no matching characters in s1 the length of the string is returned not including the terminating null character txt mikroElektronika txt sub mikr res strcspn txt sub txt Prototype sub function strpbrk dim byref sl s2 as string as word Description The function searches si for the first occurrence of any character from the string s2 The null terminator is not included in the search The function returns an index of the matching character in s1 If s1 contains no characters from s2 the function returns OxFFFF txt mikroElektronika wv txt sub mikr res strpbrk txt sub txt strrchr Prototype sub function strrchr dim byref s as string dim ch as byte as word Description The function searches the str
337. g MCU s EEPROM memory You can launch it from the drop down menu Tools EEPROM Editor When you run mikroElektronika programmer software from mikroBasic PRO for PIC32 IDE project name nex file will be loaded automatically while inex file must be loaded manually MikroElektronika EEPROM Editor 0000 0010 0020 0030 0040 0050 0060 0070 0080 0090 0B 0C 0D yYyyyyyyvyyvyyvyyy YyyyyyyyyyyYyYyY YYyVyyyYYVYYVYYYY yyyyyyvy yyyy yyyyyyvyyyyvyYYYY IVY ITV TIVITY YYyYyyyYyYYyYYYYY Yyyyyyvyyvyvyyvyyy YYVyyYyYyYYyYYYY YYVyVYVYVYVYYYYY MikroElektronika mikroBasic PRO for PIC32 Graphic Lcd Bitmap Editor The mikroBasic PRO for PIC32 includes the Graphic Lcd Bitmap Editor Output is the mikroBasic PRO for PIC32 compatible code You can launch it from the drop down menu Tools gt Glcd Bitmap Editor MikroElektronika GLCD Bitmap Editor Fie loaded banner bmp Picture preview Load BMP pn 240x128 pix bw Invert Picture GLCD See controller 240x128 T6963C gt 240x64 T 963C 128x128 T6963C 7 128x64 notimp yet 2 122x32 noting yet unsigned char const banner bmp 3840 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 128 0 0 0 0 0 0 O O O O O O O 0 0 0 0 0 O O O O0 O 1 128 O0 0 0 0 0 0 0 0O O 0 O 0 0 89 MikroElektronika m
338. h data port F RDY Ready signal line WE Write enable signal line E Output enable signal line D1 Chip detect signal line E1 Enable signal line 2 Address pin 2 1 Address pin 1 0 Address pin 0 DY direction Direction of the Ready pin E direction Direction of the Write enable pin E direction Direction of the Output enable pin CDI direction Direction of the Chip detect pin El direction Direction of the Chip enable pin F A2 direction Direction of the Address 2 pin CF Al direction Direction of the Address 1 pin CF A0 direction Direction of the Address 0 pin QOzu P POQOQO must be defined before using this function set compact flash pinout dim Cf Data Port as byte at PORTD dim CF RDY as sbit at RB7 bit dim CF WE as sbit at LATB6 bit for writing latch dim CF OE as sbit at LATB5 bit for writing latch dim CF CD1 as sbit at RB4 bit dim CF CE1 as sbit at LATB3 bit for writing latch E dim CF A2 as sbit at LATB2 bit for writing latch z dim CF Al as sbit at LATBI bit for writing latch z dim CF A0 as sbit at LATBO bit for writing latch dim CF RDY direction sbit at TRISB7 bit dim CF WE direction sbit at TRISB6 bit dim CF OE direction sbit at TRISB5 bit dim CF CD1 direction sbit at TRISB4 bit dim CF CE1 direction sbit at TRISB3 bit dim CF A2 direction sbit at TRISB2 bit dim CF A1 direction sbit at TRISBl bit dim CF AO direction sbit at TRISBO bit end of cf pinout In
339. hanged items colored red The user can edit and change the values in the RAM window mikrolCD Specific RAM window content will be written to the MCU before the next instruction execution Lcd4bit mikroE ikroElektronike EasydsPIC4 lt Stopwatch Window The Software Simulator Stopwatch Window is available from the drop down menu View Debug Windows Stopwatch The Stopwatch Window displays a Current Count of cycles time since the last Software Simulator action Stopwatch measures the execution time number of cycles from the moment Software Simulator has started and can be reset at any time Delta represents the number of cycles between the lines where Software Simulator action has started and ended Watch Clock Cycles Time Current Count 2 103 943 273 105 205 Delta 80 881 413 4044 07 ms Stopwatch _2 103 943 273 105197 16 ms Reset To Zero 129 MikroElektronika mikoBasic PRO for PIC32 Notes The user can change the clock in the Stopwatch Window which will recalculate values for the latest specified frequency Changing the clock in the Stopwatch Window does not affect actual project settings it only provides a simulation Stopwatch is available only when Software Simulator is selected as a debugger EEPROM Watch Window Note EEPROM Watch Window is available only when mikrolCD is selected as a debugger To show the EEPROM Watch Window select Debug Windows
340. he graphic area of display memory For more details see the T6963C datasheet Toshiba Glcd module needs to be initialized See SPI T6963C Config routine eui SPI T6963C write char A 22 23 SPI T6963C ROM MODE AND Wee None MikroElektronika 490 mikroBasic PRO for PIC32 SPI T6963C write text Prototype sub procedure SPI T6963C write text dim byref str as byte 10 dim x y mode as byte Writes text in the current text panel of Glcd at coordinates x y Parameters str text to be written x text position on x axis y text position on y axis mode mode parameter Valid values SPI T6963C ROM MODE OR SPI T6963C ROM MODE XOR SPI T6963C ROM MODE AND and SPI T6963C ROM MODE TEXT Mode parameter explanation OR Mode In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in negative mode i e white text on black background AND Mode The text and graphic data shown on the display are combined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet Nothing Requires To
341. he 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 ums Nothing Example ADCi_Init _ Initialize ADC nodule with default settings etes None SOS ADOx Init Advanced Prototype sub procedure ADC1 Init Advanced dim Reference as word This routine configures the internal ADC module to work with user defined settings Parameters Reference voltage reference used in ADC process Voltage reference Internal voltage reference ADC INTERNAL REF External voltage reference ADC EXTERNAL REF The MCU with built in ADC module ADC1 Init Advanced ADC INTERNAL REF set internal reference used med Not all MCUs support advanced configuration Please read the appropriate datasheet before utilizing this library MikroElektronika 240 mikroBasic PRO for PIC32 ADCx Get Sample dina ias sub function ADC1 Get Sample dim channel as word as word The function enables ADC module and reads the specified analog channel input channel represents the channel from which the analog value is to be acquired Returns 10 bit unsigned value from the specified channel Requires The MCU with built in ADC module Prior to using this routine ADC module needs to be initialized See ADCx_Init and
342. he radius of 12 SPI Glcd Rectangle Round Edges Fill 5 5 40 MikroElektronika 464 mikroBasic PRO for PIC32 SPI Glcd Box Prototype sub procedure SPI Glcd Box dim x upper left y upper left x bottom right y bottom right color as 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 0 white 1 black and 2 inverts each dot Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draw a box between dots 5 15 and 20 40 SPI Glcd Box 5 15 20 40 1 SPI Glcd Circle Prototype sub procedure SPI Glcd Circle dim x center y center radius as integer dim color as 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 for SPI communication see SPI Glcd Init routi
343. he same in asm as it is in the mikroBasic PRO for PIC32 are registers e g INTCON PORTB WREG GIE etc mikroBasic PRO for PIC32 comments are allowed in embedded assembly code Accessing variables Depending on the place of declaration accessing a variable can be done in several ways Accessing global variable 1 If declared under implementation section visible only in the file where it was declared source file _ name variable name 2 If declared in the interface section visible throughout the whole project variable name gt 3 If accessing registers declared through register rx or sfr specifiers visible throughout the whole project variable name 231 MikroElektronika mikoBasic PRO for PIC32 Accessing local variable lt routine name variable name gt Accessing routine parameter FARG routine name variable name gt Here is an example of using asm instructions program asm example dim myvar as word absolute 0x2678 dim myvarl as longword const msg Hello org 0x1234 sub procedure proc org 0x2346 asm nop end asm end sub main myvar 5 myvarl OxABCD1234 asm MOV myvar w0 move myvar to WO nop MOV 6 WO move literal 6 to WO MOV WO myvar move contents of WO to myvar OV lo_addr _myvar wl retrieve low address word of _myvar and move it to W1 0x2678 W1 OV hi_addr _myvar W1 retrieve high address word of myvar and move it to WL 0x0
344. hes string PORTA only if it s the only string in line PORT r matches strings like PORTA PORTB PORT1 and so on The metacharacter by default is only guaranteed to match beginning of the input string text and the metacharacter only at the end Embedded line separators will not be matched by or You may however wish to treat a string as a multi line buffer such that the will match after any line separator within the string and will match before any line separator Regular expressions works with line separators as recommended at http www unicode org unicode reports tr18 MikroElektronika 106 mikroBasic PRO for PIC32 Metacharacters Predefined classes Ww an alphanumeric character including NW a nonalphanumeric character Xd a numeric character XD a non numeric character Xs any space same as t n r f S anon space You may use w dand s within custom character classes Example routi de matches strings like routile routi6e and so on but not routine routime and so on Metacharacters Word boundaries A word boundary X5 is a spot between two characters that has an alphanumeric character Vw on one side and a nonalphanumeric character NW on the other side in either order counting the imaginary characters off the beginning and end of the string as matching a Ww b match a word boundary XB match a
345. hex records Use this file to program MCU Binary Extended mikro Compiled Library Binary distribution of application that can be included in other projects List File Overview of MCU memory allotment instruction 1st addresses registers routines and labels Assembler File Human readable assembly with symbolic names asm extracted from the List File Assembly View After compiling the program in the mikroBasic PRO for PIC32 you can click the View Assembly icon al aiia or select Project 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 Project Menu Project Toolbar Messages Window Project Manager Project Settings mikoBasic PRO for PIC32 Creating New Library mikroBasic PRO for PIC32 allows you to create your own libraries In order to create a library in mikroBasic PRO for PIC32 follow the steps bellow 1 Create a new source file see Managing Source Files 2 Save the file in one of the subfolders of the compiler s Uses folder DriveName Program Files Mikroelektronika mikroBasic PRO for PIC32 Uses 3 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 li
346. hh Smith your address e PRODUCTID 3F47 546774 7F6A73 SB4DF Name Johh Smith Address Invoice number BA Copy to clipboard Fill out the registration form select your distributor and click the Submit button This will start your e mail client with message ready for sending Review the information you have entered and add the comment if you deem it necessary Please do not modify the subject line Upon receiving and verifying your request we will send the license key to the e mail address you specified in the form After Receving the License Key The license key comes as a small autoextracting file just start it anywhere on your computer in order to activate your copy of compiler and remove the demo limit You do not need to restart your computer or install any additional components Also there is no need to run mikroBasic PRO for PIC32 at the time of activation MikroElektronika 34 mikroBasic PRO for PIC32 Important The license key is valid until you format your hard disk In case you need to format the hard disk you should request a new activation key Please keep the activation program in a safe place Every time you upgrade the compiler you should start this program again in order to reactivate the license 35 MikroElektronika mikroBasic PRO for PIC32 Environment mikroBasic PRO for PIC32 Main Menu Options Available Main Menu options are
347. hich can take longer time 2CO Number Email jsmithigexample com Re enter email jsmithiexample com Company Product ID Comment Distributor MikroElektronika progrant 744 Submit Related Links Products News Forums Distributors About Mikro amp lektronika Legal information and Privacy Policy Product Archive Contact Us 2010 Mikro iektronika Al rights reserved Al trade and or services marks mentioned are the property of their respective owners Copyright 19 MikroElektronika mikoBasic PRO for PIC32 Fill out the registration form select your distributor and click the Submit button If you choose I work offline registering method following window will be opened BB 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 Jo
348. httpMethod as string 5 GET web page splited into 2 parts Y Y Y 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 const indexPage as string 766 lt meta http equiv Chr 34 refresh Chr 34 content Chr 34 3 url http 192 168 20 60 Chr 34 gt lt HTML gt lt HEAD gt lt HEAD gt lt BODY gt lt h1 gt PIC32 ENC28J60 Mini Web Server lt h1 gt lt a href gt Reload lt a gt lt script src s gt lt script gt lt table gt lt tr gt lt td valign top gt lt table border 1 style chr 34 font Size 20px font family terminal t tchr 34 gt tr th colspan 2 gt ADC lt th gt lt tr gt tr td ANO td td script document write ANO lt script gt lt td gt lt tr gt tr td AN1 td td script document write AN1 lt script gt lt td gt lt tr gt table td td table border 1 style chr 34 font size 20px font family terminal chr 34 gt tr th colspan 2 gt PORTB lt th gt lt tr gt lt script gt var str i str tchr 34 chr 34 for i 2 1 lt 10 i strt t chr 34 lt tr gt lt td bgcolor pink gt BUTTON chr 34 4 it chr 34 lt td gt chr
349. ibrary 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 Reading file contents Deleting file s Creating the swap file see Help for details Copy Code To Clipboard program MMC FAT Test MMC module connections dim MMC chip select as sbit at LATG9 bit for writing to output pin always use latch dim MMC chip select direction as sbit at TRISG9 bit eof MMC module connections const LINE LEN 43 dim FAT TXT as string 20 file contents as string LINE LEN filename as string 14 File names character as byte loop loop2 as byte size as longint buffer as byte 512 MikroElektronika 390 mikroBasic PRO for PIC32 UART write text and new line carriage return line feed sub procedure UART Write Line dim byref uart text as string UART1 Write Text uart text UART1 Write 13 UART1 Write 10 end sub a ea Creates new file and writes some data to it sub procedure M Create New File filename 7 A Set filename for single file tests Mmc Fat Set File Date 2011 1 12 11 9 0 Set file date amp time info Mmc Fat Assign filename 0xA0 Will not find file and then create file Mmc Fat Rewrite
350. iew of the toolbars available in mikroBasic PRO for PIC32 Help File Toolbar Edit Toolbar Advanced Edit Toolbar Find Toolbar Project Toolbar Build Toolbar Debug Toolbar Styles Toolbar Tools Toolbar View Toolbar Layout Toolbar Help Toolbar MikroElektronika A mikroBasic PRO for PIC32 File Toolbar 5 File Toolbar is a standard toolbar with the following options Die Bemmpion LB Opens a new editor window Open source file for editing or image file for viewing nl Save changes for active window Save changes in all opened windows Edit Toolbar Edit Toolbar is a standard toolbar with the following options S Beeiplam E3 Undo last change E3 Redo last change Cut selected text to clipboard Copy selected text to clipboard Paste text from clipboard 15 MikroElektronika mikoBasic PRO for PIC32 Advanced Edit Toolbar Advanced Edit Toolbar comes with the following options Icon DIT C X HIT X E a Generate HTML code suitable for publishing current source code on the web Find Replace Toolbar D222 Find Replace Toolbar is a standard toolbar with the following options r Find text in current editor FUR Franextoseurenoe O O r1 Replace text Find text in files MikroElektronika 16 mikroBasic PRO for PIC32 Project Toolbar Project Toolbar comes with the following opti
351. if if Button PORTB 5 1 1 Tone3 while RB5 bit lt gt 0 nop wend end if if Button PORTB 4 1 1 Melody2 while RB4 bit lt gt 0 nop wend end if if Button PORTB 3 1 1 Melody on PORTB 7 1 1 then then then then then Plays Melody2 Configure AN pins as digital I O Configure RB7 RB3 as input endless loop If PORTB Wait for If PORTB Wait for If PORTB Wait for Tf PORTB Wait for If PORTB 7 is pressed button to be 6 is pressed button to be 5 is pressed button to be 4 is pressed button to be J is pressed play Tonel released play Tonel released play Tonel released play Tonel released play Tonel ai MikroElektronika mikoBasic PRO for PIC32 while RB3 bit lt gt 0 nop wend end if wend end HW Connection SPI SCK SPI MOSI SPI HW connection Wait for button to be released CN10 DAC CONNECTOR OSCILLATOR C 7 1 MikroElektronika 42 mikroBasic PRO for PIC32 SPI Ethernet Library The ENC28J60 is a stand alone Ethernet controller with an industry standard Serial Peripheral Interface SPI It is designed to serve as an Ethernet network interface for any controller equipped with SPI The ENC28460 meets all of the IEEE 802 3 specifications It incorporates a number of
352. ifics 135 GOTO Table 136 Basic Standard Issues 136 Divergence from the Basic Standard 136 Basic Language Extensions 136 Predefined Globals and Constants 137 Predefined project level defines 137 Accessing Individual Bits 138 sbit type 139 at keyword 140 MikroElektronika mikoBasic PRO for PIC32 bit type 140 Interrupts 141 Configuring Interrupts 141 Single Vector Mode 141 Multi Vector Mode 141 Interrupt Priorities 142 Interrupts and Register Sets 142 Register Set Selection in Single Vector Mode 142 Interrupts and Register Sets 142 Interrupt Coding Requirements 142 Interrupt Service Routine 142 Function Calls from Interrupt 143 Interrupt Example 144 Linker Directives 145 Directive absolute 145 Directive org 145 Directive orgall 146 Built in Routines 146 Lo 148 Hi 148 Higher 149 Highest 149 LoWord 150 HiWord 150 Inc 151 Dec 151 Chr 151 Ord 152 SetBit 152 ClearBit 152 TestBit 153 Delay us 153 Delay ms 154 Vdelay ms 154 VDelay Advanced ms 155 Delay Cyc 155 Delay Cyc Long 155 Clock kHz 156 Clock Mhz 156 Get Fosc kHz 156 Get Fosc Per Cyc 157 Reset 157 ClrWat 157 DisableContextSaving 158 SetFuncCall 158 SetOrg 159 MikroElektronika 6 mikroBasic PRO for PIC32 DoGetDateTime 159 DoGetVersion 159 KVAO TO KVA1 160 KVA1 TO KVAO 160 KVA TO PA 160 PA TO KVAO 161 PA TO KVA1 161 CPO GET 161 CPO SET 162 Enablelnterrupts 162 Disablelnterrupts 162 Code Optimization 164 Constant folding 164 Constan
353. ika 428 mikroBasic PRO for PIC32 SPI Ethernet initDHCP Prototype sub function SPI Ethernet initDHCP dim tmax as byte as 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 SPI Ethernet Init SPI Ethernet initDHCP 5 get network configuration from DHCP server wait 5 sec for the response The Ethernet services are not stopped while this routine waits for DNS reply The incoming packets will be processed normaly during this time When DHCP module is used global library variable SPI Ethernet userTimerSec is used to keep track of time It is user responsibility to increment this variable each second in it s code SPI Ethernet doDHCPLeaseTime Prototype sub
354. ikoBasic PRO for PIC32 HID Terminal The mikroBasic PRO for PIC32 includes the HID communication terminal for USB communication You can launch it from the drop down menu Tools HID Terminal R mikroElektronika USB HID Terminal fo amp es Terminal Descriptor HID Devices Info ABBAHOHE ABBAHOHE mikroE HID Librar Dell Premium USB Optical House mj Communication HID Read Write Test Send Append CR IV Send as Typing Append LF Send as Number ormat ASCII C HEX C DEC Clear HID Read Write Test Interrupt Assistant mikroBasic PRO for PIC32 includes the Interrupt Assistant that assist user in configuring interrupts Output is the code for the configured interrupt routine You can launch it from the drop down menu Tools Interrupt Assistant Interrupt Assistant x void interrupt w ilevel 4 is vw SOFT OK MikroElektronika mikroBasic PRO for PIC32 Lcd Custom Character mikroBasic PRO for PIC32 includes the Lcd Custom Character Output is mikroBasic PRO for PIC32 compatible code You can launch it from the drop down menu Tools Lcd Custom Character MikroElektronika LCD Custom Char Generator Save Load Fillall Clearall Invert p Preview i I const character as byte 8 0 4 4 31 4 4 0 0 sub procedure CustomChar dim pos row as byte dim pos char as byte dim i as byte Lcd Cmd 64 for i 0to 7 Lcd Ch
355. ikroBasic PRO for PIC32 Sound Library mikroBasic PRO for PIC32 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 of this page Library Routines Sound Init Sound Play Sound Init Prototype sub procedure Sound Init dim byref snd port snd pin as 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 sub procedure Sound Play dim freq in hz duration ms as 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 Play sound of 1KHz in duration of 100ms Sound Play 1000 100 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 401 MikroElektronika mikoBasic PRO for PIC32 Library Example The example is a simple demonstration of how to use the Sound Library for playing tones on a piezo speaker Copy Code To Clipboard program Sound sub procedure Tonel Sound Play 659 250 Frequency
356. ikroBasic PRO for PIC32 UARTx Init Advanced Prototype sub procedure UARTx Init Advanced dim baud rate freq Khz as dword dim high low parity stop bits as byte Configures and initializes the UART module with user defined settings Parameters baud rate requested baud rate freq Khz Peripheral Bus Clock frequency in kHz high low speed High low speed selection parameter Valid values parity Parity and data selection parameter Valid values stop bits stop bit selection parameter Valid values Predefined library const One stop bit UART ONE STOPBIT Two stop bits UART TWO STOPBITS Routine requires the UART module Refer to the device data sheet for baud rates allowed for specific Fosc UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Switching between the UART modules in the UART library is done by the UART Set Active function UART modules have to be previously initialized Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 563 MikroElektronika mikoBasic PRO for PIC32 UARTx Data Ready Prototype sub function UARTx Data Ready as word The function tests if data in receive buffer is ready for reading 1 if data is ready for reading 0 if there is no data in the receive regis
357. ikroBasic PRO for PIC32 integrated Glcd Bitmap Editor Tools gt Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd 309 MikroElektronika mikoBasic PRO for PIC32 PC Library The PC full master I C module is available with a number of the PIC32 MCU models The mikroBasic PRO for PIC32 provides a library which supports the master IC mode Important FC library routines require you to specify the module you want to use To select the desired IC module simply change the letter x in the routine prototype for a number from 1 to 3 Number of I C modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Library Routines 2Cx Init 2Cx Init Advanced 2Cx Start 2Cx Restart 2Cx Is Idle 2Cx Read I2Cx Write 2Cx Stop I2Cx Init Prototype sub procedure I2Cx Init dim scl as longint Description This function configures and initializes the desired IC module with default settings This function enables the I C module by setting the I2CEN bit The rest of the bits in I C control register remains unchanged Default initialization after reset of IPC module is Continue operation in IDLE mode T bit slave address Slew rate control enabled for High Speed mode 400 kHz General call address disabled SCL clock stretching disabled As per the I C standard SCL clock may be 100 kHz or 400 kHz
358. ikroElektronika 112 mikroBasic PRO for PIC32 Linker Directives mikroBasic PRO for PIC32 uses internal algorithm to distribute objects within memory If you need to have a variable or routine at the specific predefined address use the linker directives absolute and org When using these directives be sure to use them in proper memory segments i e for functions it is the KSEGO and for variables it is the KSEG1 Linker directives are used with the virtual addresses Directive absolute Directive absolute specifies the starting address in RAM for a variable If the variable is multi byte higher bytes will be stored at the consecutive locations Directive absolute is appended to declaration of a variable Variable x will occupy 1 word 16 bits at address 0x32 dim x as word absolute 0x32 Variable y will occupy 2 words at addresses 0x34 and 0x36 dim y as longint absolute 0x34 Be careful when using absolute directive as you may overlap two variables by accident For example dim i as word absolute 0x42 Variable i will occupy 1 word at address 0x42 dim jj as longint absolute 0x40 Variable will occupy 2 words at 0x40 and 0x42 thus changing i changes jj at the same time and vice versa 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 Const
359. ikroElektronika 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 831 Web www mikroe com E mail office mikroe com 31 MikroElektronika mikoBasic PRO for PIC32 Technical Support The latest software can be downloaded free of charge via Internet you might want to bookmark the page so you could check news patches and upgrades later on http www pic32compilers com In case you encounter any problem you are welcome to our support forums at www mikroe com forum Here you may also find helpful information hardware tips and practical code snippets Your comments and suggestions on future development of the mikroBasic PRO for PIC32 are always appreciated feel free to drop a note or two on our Wishlist In our Knowledge Base www mikroe com en kb you can find the answers to Frequently Asked Questions and solutions to known problems If you
360. im TFT DataPort as byte at LATE external im TFT D P Di i re i i aim Tn a a Direction of the TFT Data Port dim TFT DataPort Direction as byte at TRISE byte sfr external T di TFT WR b z i i zi Bee ES Write signal TFT WR as sbit at LAT external i TFT RD b f i din s gre ee Read signal FT RD as sbit at externa dim TFT CS as byte sfr r x Chip Select signal FT CS as sbit at externa nem Command Register Select signal fr im A as byte external I RS as sbit at LA im TFT RST gia RST as byte SER at signal dim TFT RST as sbit at LATC1 bit external UN im TE E im TFT WR Di ti Zu n n i am ee JS UAM Direction of the Write pin dim TFT WR Direction as sbit at TRISD13 bit sfr external diim im TFT RD Di ti b ete D Direction as Byte Directioniof the Read pin dim TFT WR Direction as sbit at TRISD12 bit sfr external ns E im TFT CS Directi as byte y9 DLreeelen y Direction of the Chip Select pin dim TFT_CS_Direction as sbit at TRISC3 bit sfr external AN A im TFT RS Di ti byt mum TeC son aS SYTS Direction ofthe Register Selectpin dim TFT_RS Direction as sbit at TRISB13 bit sfr external ET im TFT RST Di i byt o u dim TFT_RST_Direction as byte Direction of the Reset pin dim TFT RST Direction as sbit at TRISC1 bit sfr external a ms MikroElektronika 932 mik
361. im byref port as word dim pin as word as 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 Requires Devices compliant with the Dallas OneWire protocol Issue Reset signal on One Wire Bus connected to pin RF6 Ow Reset PORTF 6 Nos Nae SS 3909 MikroElektronika mikoBasic PRO for PIC32 Ow Read Prototype sub function Ow Read dim byref port as word dim pin as word as 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 dim read data as byte read data Ow Read PORTF 6 Ow Write Prototype sub procedure Ow Write dim byref port as word dim pin data as word 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 MikroElektronika 396 mikroBasic PRO for PIC32 Port Expander Library mikroBasic PRO for PIC32 provides a library for communication with the Microchip s Port Expander MCP23S17 via SPI interface Connect
362. im byref sl s2 as string as 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 txt mikroElektronika txt sub mikr res strspn txt txt sub routne returns 4 strncmp Prototype sub function strncmp dim byref sl s2 as string dim len as byte as integer Description The function lexicographically compares the first 1 en characters of the strings s1 and s2 and returns a value indicating their relationship Value Meaning 0 sl less than s2 sl equal to s2 gt 0 sl greater than s2 The value returned by the function is determined by the difference between the values of the first pair of words that differ in the strings being compared within first 1e words txt mikroElektronika txt sub mikr res strncomp txt sub txt 3 compares the first 3 characters from the string txt with the sting txt sub and returns a difference strstr Prototype sub function strstr dim byref sl s2 as string as word Description The function locates the first occurrence of the string s2 in the string s1 excluding the terminating null character The
363. im isBroadcast as boolean flag which denotes that the IP package has been received via subnet broadcast address end structure 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 422 mikroBasic PRO for PIC32 SPI Ethernet UserUDP Prototype sub function SPI Ethernet UserUDP dim remoteHost as byte dim remotePort as word dim destPort as word dim reqLength as word dim byref flags as TEthPktFlags as word Description This is UDP module routine It is internally called by the library The user accesses to the UDP request by using some of the SPI Ethernet get routines The user puts data in the transmit buffer by using some of the SPI Ethernet put routines The function must return the length in bytes of the UDP reply or 0 if nothing to transmit If you don t need to reply to the UDP requests just define this function with a return 0 as single statement Parameters remoteHost client s IP address remotePort client s port localPort port to which the request is sent reqLength UDP request data field length flags structure consisted of two
364. imulate operations of the Microchip PIC32 MCUs and assist the users in debugging code written for these devices Upon completion of writing your program choose Release build Type in the Project Settings window Project Settings Elgg Device Name P32MX460F512L Smeu Clock Choose Release type if you want to use software simulator Frequency 8 000000 MHz E Build Deb gger Build Type P Release O ICD Debug Debugger Software O mikroICD After you have successfuly compiled your project you can run the Software Simulator by selecting Run Start Debugger from the drop down menu or by clicking the Start Debugger Icon B from the Debugger 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 PIC32 device behavior i e it doesn t update timers interrupt flags etc Related topics Software Simulator Debug Windows Software Simulator Debugger Options MikroElektronika 126 mikroBasic PRO for PIC32 Software Simulator Debug Windows Debug Windows This section provides an overview of available Debug Windows in mikroBasic PRO for PIC32 Breakpoints Window Watch Values Window RAM Windo
365. in length dim t as short txt as string 4 24 ByteToStr t txt txt is 24 one blank here WordToStr Prototype sub procedure WordToStr dim input as word dim byref output as string 5 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 uis E destination string Destination string should be at least 6 characters in length dim t as word txt as stringi 5 437 WordToStr t txt txt is 437 two blanks here 583 MikroElektronika mikoBasic PRO for PIC32 WordToStrWithZeros Prototype sub E m WordToStrWithZeros dim input as word dim byref output as string 5 e Converts input word to a string The output string is right justified and the remaining positions on the e if any are filled with zeros Parameters dias signed integer number to be converted output destination string Destination string should be at least 7 characters in length dim t as word Ext as string 5 437 WordToStrWithZeros t txt txt zs 00437 IntToStr Prototype sub procedure IntToStr dim input as integer dim byref output string 6 alo Converts input integer number to a string The output string is right justified and the remaining positions ped the left if any are filled with blanks Parameters ae signed integer number to be converted output
366. 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 G1p13308 OVERERY XOR In this mode the text and graphics data are combined via the logical exclusive OR 913700 OURREAY 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 emis 1D13700 Write Text EPSON LIBRARY DEMO WELCOME 0 S1D13700 OVERLAY S1D13700 Dot S1D13700 OVERLAY OR Prototype sub procedure S1D13700 Dot dim x as word dim y as word dim color as ac inel 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 S1D13700 BLACK Black color 1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine Same S1D13700 Dot 50 50 S1D13700 WHITE 287 MikroElektronika mikoBasic PRO for PIC32 S1D13700 Line Prototype sub procedure S1D13700 Line dim x0 y0 xl yl as word dim pcolor as a dual Description Draws a l
367. ine 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 D RETURN HOME Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected MikroElektronika 482 mikroBasic PRO for PIC32 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 dim text as char 16 dim counter as byte Port Expander module connections dim SPExpanderRST as sbit at LATD8 bit dim SPExpanderCS as sbit at LATD9 bit dim SPExpanderRST Direction as sbit at TRISD8 bit dim SPExpanderCS Direction as sbit at TRISD9 bit End Port Expander module connections sub procedure Move Delay Function used for text moving Delay ms 500 You can change the moving speed here end sub main CHECON 0x32 ADIPCFG OxFFFF Configure AN pins as digital text mikroElektronika If Port Expander Library uses SPI2 module Initialize SPI module used with PortExpander SPI2 Init Advanced SPI MASTER SPI 8 BIT 4 SPI SS DISABLE SPI DATA SAMPL MIDDLE SPI CLK IDLE LOW SPI ACTIVE 2 IDLE Fl Spi Lcd8 Config 0 Initialize LCD over SPI interface
368. ine from x0 yO to x1 y1 Parameters x0 X coordinate of the line start y0 y coordinate of the line end x1 X coordinate of the line start y1 y coordinate of the line end pcolor color parameter Valid values S1D13700 BLACK Black color S1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine an S1D13700 Line 0 239 127 S1D13700 WHITE S1D13700 H Line Prototype sub procedure S1D13700 H Line dim x start x end y pos as word dim color as a a 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 S1D13700 BLACK Black color S1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine S1D13700 Line 0 0 239 127 91013700 WHITE MikroElektronika 288 mikroBasic PRO for PIC32 S1D13700 V Line Prototype sub procedure S1D13700 V Line dim y start y end x pos as word dim color as at ad Description Draws a horizontal line Parameters y start y coordinate of the line start y end y coordinate of the line end x pos line position on the x axis pcolor color parameter Valid values S1D13700 BLACK Black color 1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine eae S1D13700 Line
369. ing Description Writes one byte to the current location in Glcd memory and moves to the next location Parameters data data to be written Requires Glcd needs to be initialized see Glcd Init routine Glcd side x axis position and page should be set first See functions Glcd Set Side Glcd Set X and Glcd Set Page dim data as byte Glcd Write Data data 301 MikroElektronika mikoBasic PRO for PIC32 Gled Fill Prototype sub procedure Glcd Fill dim pattern as byte Description Fills Glcd memory with the byte pattern To clear the Glcd screen useGicd Fill 0 To fill the screen come use Gled Fill 0xFF ums me e 1 Example oram t crear semen Moes noe OOS Glcd Dot Prototype sub procedure Glcd Dot dim x pos y pos color as 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 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 Glcd Dot 0 0 2 Notes For x and y axis layout explanation see schematic at the bottom of this page Glcd Line Prototype sub procedure Glcd Line dim x start y start x end y end as integer dim color as byte Draws a line on Glcd Parameters x start x coordinate
370. ing methods work online or work offline based on your current internet connection and click Request license key now button MikroElektronika 32 mikroBasic PRO for PIC32 How to register Choose registration method f work online Choose this option if you are connected to i 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 btaining the license key it takes minutes to get it in your mailbox Recommended O I work offline Choose this option if you are not connected to Internet You will be quided to Fill in the registration Form which you can e mail when you get online This is a slower way of getting the license key and it is intended for offline computers Request license key now If you choose I work online registering method following page will be opened in your default browser mie if simple E 7 MikroElektronika i i EN Email officegmikroe com DEVELOPMENT TOOLS COMPILERS BOOKS Projects Download Publications Support elopment Home Software Activation In order to get activation key please fill in required fields Upon receiving and verifying your request we will send the license key to the e mail address you specified in the form Product Name John Smith Address If you do not specify 2CO Number or invoice number then the license key request must be processed Invoice manually w
371. ing 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 txt mikroElektronika res strrchr txt k returns the index of the k character of the txt string Prototype sub procedure ltrim dim byref astring as string The procedure trims the leading spaces of the string txt mikroE Ltrim bxt trims the leading 2 spaces of the txt string MikroElektronika 602 mikroBasic PRO for PIC32 rtrim EOD sub procedure rtrim dim byref astring as string The procedure trims the trailing spaces of the string txt mikroE rtrim txt trims the trailing 2 spaces of the txt string and adds terminating null character to the result strappendpre Erototne sub procedure strappendpre dim letter as char dim byref sl as string The Ss trims the trailing spaces of the string txt ikrol strappendpre m txt adds letter m at the beginning of the txt string strappendsuf Prototype sub procedure strappendsuf dim byref sl as string dim letter as char The procedure appends character at the end of the string txt mikro strappendsuf E adds letter E at the end of the txt string DDR sub function length dim byref s as string as word The function r
372. ing 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 mikroBasic PRO for PIC32 Tools USB HID Terminal The 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 971 MikroElektronika mikoBasic PRO for PIC32 HID Enable Prototype sub procedure HID Enable dim readbuff as byte dim writebuff as byte Enables USB HID communication Parameters readbuff Read Buffer writebuff Write Buffer These parameters are used for HID communication DONIS HID Enable readbuff writebuff Notes This function needs to be called before using other routines of USB HID Library HID Read Prototype sub function
373. input parameter multiplied by 1000 dim res as integer res sinE3 45 result is 707 Notes Return value range 1000 1000 cosE3 Prototype sub function cosE3 dim angle deg as word as integer Description The function calculates cosine multiplied by 1000 and rounded to the nearest integer result round cos angle deg 1000 angle deg input angle in degrees Retums The function returns the cosine of input parameter multiplied by 1000 dim res as integer res cosE3 196 result is 193 Notes Return value range 1000 1000 MikroElektronika 612 mikroBasic PRO for PIC32 CHAPTER 10 Tutorials Managing Project Projects The mikroBasic PRO for PIC32 organizes applications into projects consisting of a single project file extension mbp3 2 and one or more source files extension mbas mikroBasic PRO for PIC32 IDE allows you to manage multiple projects see Project Manager Source files can be compiled only if they are part of a project The project file contains the following information project name and optional description target device device flags config word device clock list of the project source files with paths binary files emcl image files other files Note that the project does not include files in the same way as preprocessor does see Add Remove Files from Project 613 MikroElektronika mikoBasic PRO
374. ion sinh dim x as float as float Description Function returns the hyperbolic sine of x defined mathematically as ex e X 2 If the value of x is too large if overflow occurs the function fails sinh PI 2 2 301296 sqrt aes sub function sqrt dim x as float as float Function returns the non eee square root of x Example res sqrt 10000 res 100 0000 tan Prototype sub function tan dim x as float as float Description Function returns the tangent of x in radians The return value spans the allowed range of floating point in the mikroBasic PRO for PIC32 s tan PL 4 res 0 999998 tanh Prototype sub function tanh dim x as float as float Function returns the hyperbolic tangent of x defined mathematically as sinh x cosh x Example res tanh PI 4 res 0 655793 611 MikroElektronika mikoBasic PRO for PIC32 Trigonometry Library The mikroBasic PRO for PIC32 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 sub function sinE3 dim angle deg as word as integer Description The function calculates sine multiplied by 1000 and rounded to the nearest integer result round sin angle deg 1000 angle deg input angle in degrees Retums The function returns the sine of
375. ionl then if expression2 then statementl else statement2 end if end if MikroElektronika 224 mikroBasic PRO for PIC32 In order to force the compiler to interpret our example the other way around we have to write it explicitly if expressionl then if expression2 then statementl end if else statement2 end if Select Case Statement Use the select case statement to pass control to a specific program branch based on a certain condition The select case statement consists of selector expression condition and list of possible values The syntax of the select case statement is select case selector case value 1 statements 1 case value n statements n case else default statements end select selector is an expression which should evaluate as integral value values can be literals constants or expressions and statements can be any statements The case e1se clause is optional First the selector expression condition is evaluated The select case statement then compares it against all available values If the match is found the statements following the match evaluate and the select case statement terminates In case there are multiple matches the first matching statement will be executed If none of the values matches the selector then default statements in the case else clause if there is one are executed Here is a simple example of the select case statement select case operator case res nl n2
376. ions of the PIC32 MCU and MCP23S17 is given on the schematic at the bottom of this page Important The library uses the SPI module for communication User must initialize the appropriate SPI module before using the Port Expander Library For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by using the SPI Set Active function See the SPI Library functions Library does not use Port Expander interrupts Library Dependency Tree Port Expander gt sP1 External dependencies of Port Expander Library The following variables must be defined in all projects using Port Expander Description Library dim SPExpanderRST as sbit sfr A dim SPExpanderRST as sbit at LATFO Reset line f external bit dim SPExpanderCS as sbit sfr i xp Chip Select line dim SPExpanderCS as sbit at LATF1 bit external dim SPExpanderRST Direction as Direction of the Reset pin dim SPExpanderRST Direction as _ sbit sbit sfr external pin at TRISFO bit dim SPExpanderCS Direction as 5 dim SPExpanderCS Directions as sbit sbit sfr external Direction onihe Chip Seleot pin at TRISF1 bit Library Routines Expander Init Expander Init Advanced Expander Read Byte Expander Write Byte Expander Read PortA Expander Read PortB Expander Read PortAB Expander Write PortA Expander Write PortB Expander Write PortAB Expander Set DirectionPortA Expan
377. it CF Cf Init MikroElektronika 262 mikroBasic PRO for PIC32 Cf Detect Prototype Checks for presence of CF card by reading the chip detect pin 1 if CF card was detected 0 otherwise The corresponding MCU ports must be appropriately initialized for CF card See C Init Wait until CF card is inserted while Cf Detect nop wend PIC32 family MCU and CF card voltage levels are different The user must ensure that MCU s pin connected to CD line can read CF card Logical One correctly Cf_Enable Prototype sub procedure Cf Enable Description Enables the device Routine needs to be called only if you have disabled the device by means of the Cf Disable routine These two routines in conjunction allow you to free occupy data line when working with multiple devices Nothing The corresponding MCU ports must be appropriately initialized for CF card See Cf Init enable compact flash Cf Enable None Cf Disable Prototype sub 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 P multiple devices Nothing The corresponding MCU ports must be appropriately initialized for CF card See Cf Init disable compact flash Cf Disable None 263 MikroElektronika mikoBasic PRO for
378. it at 7 Direction of the Write pin e Tee EET at A i D13700 RD Di i bit Direction of the Read pin mier S MeBPENDM NE eM dim 1D13700 CS as sbit sf external dim 51D13700 DATA Direction a byte sfr external dim 51D13700 WR Direction sbit sfr external sbit sfr external a sbit sfr external n a dim 51D13700 RES Direction Direction of the Reset pin dim S1D13700 RES Direction as sbit sbit sfr external pin at TRISCO bit dim 51D13700 CS Direction as Direction of the Chip select pin dim S1D13700 CS Direction as sbit at sbit sfr external i P pin TRISC4 bit 219 MikroElektronika s s dim 51D13700_RD Direction as s s dim S1D13700 AO Direction Direction of the System Address i D13700 AO Direction as sbit a pin TRISC2 bit mikoBasic PRO for PIC32 Library Routines 81D13700 Init 81D13700 Write Command 81D13700 Write Parameter 81D13700 Read Parameter 81D13700 Fill 81D13700 GrFill 81D13700 TxtFill 81D13700 Display GrLayer 81D13700 Display TxtLayer 1D13700 Set Cursor 81D13700 Display Cursor 81D13700 Write Char 81D13700 Write Text 81D13700 Dot 81D13700 Line 81D13700 H Line 81D13700 V Line 81D13700 Rectangle 81D13700 Box 81D13700 Rectangle Round Edges 81D13700 Rectangle Round Edges Fill 81D13700 Circle 81D13700 Circle Fill 81D13700 Image 81D13700 Partiallmage MikroElektronika 280 mikroBasic PRO for
379. it at TRISD6 bit SoftSpi SDI Direction as sbit at TRISD2 bit SoftSpi SDO Direction as sbit at TRISD3 bit End DAC module connections 395 MikroElektronika mikoBasic PRO for PIC32 dim value as word sub procedure InitMain TRISBO bit i TRISB1 bit all Chip Select 1 b Chip Select Direction 0 Soft Spi Init end sub DAC increments 0 4095 Set RBO pin as input Set RB1 pin as input Deselect DAC Set CS pin as Output Initialize Soft SPI gt output voltage 0 Vref sub procedure DAC Output dim valueDAC as word dim temp as byte volatile Chip Select 0 g Send High Byte temp word valueDAC gt gt 8 temp temp or 0x30 Soft SPI Write temp and OxOF 3 Send Low Byte temp valueDAC 3 Soft SPI Write temp Chip Select 1 end sub main CHECON 0x32 ADIPCFG OxFFFF i InitMain 2048 Y value while if TRUE RBO bit Inc value else if and value 4095 then RBl bit and value gt 0 then Dec value end if end if DAC Output value Delay ms 1 wend end Select DAC chip Store valueDAC 11 8 to temp 3 0 Define DAC setting see MCP4921 datasheet Send high byte via Soft SPI Store valueDAC 7 0 to temp 7 0 Send low byte via Soft SPI Deselect DAC chip Configure AN pins as digital Perform main initialization When program starts DAC gives the output in the mid range Endles
380. ition line main ADPCFG OxFFFF text mikroElektronika Lcd Init Lcd Cmd LCD CLEAR 9 Lcd Cmd LCD CI BE 30 for i 0 to 17 e Lcd Chr 1 i text i 1 4 next i end Watch Values E Eh sh 5h 0 oo orf E fu a Add Remove Properties yg AddAll Gg Remove All Select variable from list text vv Search for variable by assembly name _text Ey v Peripherals Freeze Mame Value text i PC 0x0002DA 65 55 ms Run Pause Debugger F6 and Toggle Breakpoints F5 are mikrolCD debugger functions that are 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 e E in Beans Watch Values e ADPCFG OxFFFF o k E text mikroElektronika E sh ch no el se A a Add Remove lt Properties by AddAll k RemoveAll Lcd Init Select variable from list 9 Lcd Cmd LCD CLEAR text v e Lcd Cmd LCD CURSOR OFF Search for variable by assembly name _text E 30 for i 0 to 17 ds v Peripherals Freeze v 31 DONSOSEPEETPETSIJRERLOSBEEEEM
381. ked For more information on creating new libraries see Creating New Library MikroElektronika 84 mikroBasic PRO for PIC32 Options Edito Output Settings mikoBasic PRO for PIC32 Integrated Tools Active Comments Editor Active Comments Editor is a tool particularly useful when working with Lcd display You can launch it from the drop down menu Tools Active Comments Editor or by clicking the Active Comment Editor Icon A from Tools toolbar Active Comments Editor Enter comment name activeComment Active Comment Actions New Rename Properties 3 Attributes Url Image File Events OnLeftClick Alt Mone OnRightClick OnDblClick OnMouseOver Add Image To Project Add File To Project MikroElektronika 96 mikroBasic PRO for PIC32 ASCII Chart The ASCII Chart is a handy tool particularly useful when working with Lcd display You can launch it from the drop down menu Tools gt ASCII chart or by clicking the View ASCII Chart Icon from Tools toolbar meal Ascii Chart NUL SOH STX ETX EOT ENQ ACK BEL BS LF VT FF CR 0 1 2 3 4 5 6 71 8 9 10 1t 12 13 DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS 19 20 21 24 25 26 28 29 1 49 o2 om gt J o 100 t 116 132 F onig nig a 87 MikroElektronika mikoBasic PRO for PIC32 EEPROM Editor The EEPROM Editor is used for manipulatin
382. ktronika 210 mikroBasic PRO for PIC32 Cf Fat Get File Date Prototype sub procedure Cf Fat Get File Date dim byref year as word dim byref month as byte dim byref day as byte dim byref hours as byte dim byref mins as 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 da y buffer to store day attribute to Upon function execution day attribute is returned through this parameter hours buffer to store hours attribute to Upon function execution hours attribute is returned through this parameter 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 dim year as word dim month day hours mins as byte Cf Fat Get File Date Modifi year month day hours mins Cf Fat Get File Date Modified 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
383. ktronika 324 mikroBasic PRO for PIC32 Lcd Cmd LCD SHIFT RIGHT Move Delay next i while TRUE Endless loop for i 0 to 7 Move text to the left 7 times Lcd Cmd LCD SHIFT LEFT Move Delay next i for i 0 to 7 Move text to the right 7 times Lcd Cmd LCD SHIFT RIGHT Move Delay next i wend end GND LCD COG 2X16 Lcd HW connection 329 MikroElektronika mikoBasic PRO for PIC32 Manchester Code Library mikroBasic PRO for PIC32 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 Manchester RF Send Byte format st1 st2 Cctr B7 Be B5 B4 B3 B2 B1 80 Bi phase coding s m 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
384. l All hardware resources such as program memory data memory and peripherals are located at their respective physical addresses Peripherals such as DMA and Flash controllers use physical addresses and access memory independently of the CPU Virtual addresses are exclusively used by the CPU to fetch and execute instructions Virtual address space can be thought as CPU s logical view and use of its physical resources A graphical representation of the PIC32MX virtual and physical memory is shown in picture below Virtual Memory Map Physical Memory Map OxFFFFFFFF OxFFFFFFFF NOT USED 0xC0000000 SS OxBF000000 MW BMXDUDBA OxBD000000 Ox4FFFFFFF KSEG2 KSEG3 OxBFC00000 WW UOO Y 0xBF 800000 KWAY 0xBD000000 OxAFFFFFFF SS 4 0x40000000 0xA0000000 Wwinw wi w g d ESSO RESERVED V KSEGO KSEG1 0X80000000 Ox7F000000 Ox1D000000 OxOFFFFFFF Noo SSSSSSSSSSSSSS S PIC32 Memory Map 0x7D000000 BMXPUPBA OxOFFFFFFF BMXDUDBA USEG KUSEG 9 axanananan axnononona 169 MikroElektronika mikoBasic PRO for PIC32 As it can be seem the entire 4 GB virtual address space is divided into two primary regions User and Kernel space The lower 2 GB of space called USEG KUSEG and the upper 2 GB are divided into KSEGO KSEG1 KSEG2 and KSEG3 Virtual vs Physical Addresses The PIC32MX s CP
385. l need to take care of these things 1 Write the Interrupt Service Routine You may use Interrupt Assistant to easily write this routine 2 Initialize the module which will generate an interrupt 3 Set the correct priority and subpriority for the used module according to the priorities set in the Interrupt Service Routine 4 Enable Interrupts Interrupt Service Routine Interrupt service routine is defined in this way sub procedure interrupt iv IVT ADC ilevel 7 ics ICS SOFT Interrupt service routine code end sub MikroElektronika 110 mikroBasic PRO for PIC32 where iv reserved word that inform the compiler that it is an interrupt service routine IVT ADC appropriate Interrupt Vector ilevel 7 Interrupt priority level 7 ics Interrupt Context Saving Interrupt Context Saving can be performed in several ways 1 ICS_ SOFT Context saving is carried out by the software 2 ICS_SRS Shadow Register set is use for context saving 3 1CS OFF No context saving 4 ICS AUTO Compiler chooses whether the ICS SOFT or ICS_ SRS will be used User can explicitly declare starting interrupt routine address using org directive sub procedure interrupt org 0x9D000000 iv IVT ADC ilevel 7 ics ICS SOFT Interrupt service routine code end sub Function Calls from Interrupt Calling functions from within the interrupt routine is possible The compiler takes care about the registers being used both in i
386. lculations Example a as longword b as byte a b 5 this is done at word level Conditional expressions Conditional expressions may differ from the same code in assignment expressions due to left side exception Example a as longword b as byte MikroElektronika 222 mikroBasic PRO for PIC32 if b 5 then byte level general rule will not give same result as a 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 to Assignment Statements Conditional Statements Iteration Statements Loops Jump Statements asm Statement Assignment Statements Assignment statements have the following form variable expression The statement evaluates expression a
387. le This example shows how to declare a function which returns a complex type program Example structure TCircle v Structure dim CenterX CenterY as word dim Radius as byte end structure dim MyCircle as TCircle Global variable sub function DefineCircle dim x y as word dim r as byte as TCircle DefineCircle function returns a Structure result CenterX x result CenterY y result Radius r end sub main MyCircle DefineCircle 100 200 30 Get a Structure via function call MyCircle CenterX DefineCircle 100 200 30 CenterX 20 Access a Structure field via function call eeeiererceeteee ppt eriere cres pee i 3 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 module 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 199 MikroElektronika mikoBasic PRO for PIC32 program Volume dim Volume as word sub function First dim a as word dim b as word as word forward sub function Second dim c as word as word dim tmp as word tmp First 2 3 result tmp c end sub sub function First dim a b as word as word result a b end sub main Volume Sec
388. le 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 swap file is to make reading and writing to MMC SD media as fast as possible by using the Mmc Read Sector and Mmc Write Sector functions directly without potentially damaging the FAT system The swap file can be considered as a window on the media where the user can freely write read data It s main purpose in this library is to be used for fast data acquisition when the time critical acquisition has finished the data can be re written into a normal file and formatted in the most suitable way sectors cnt number of consecutive sectors that user wants the swap file to have filename name ofthe file that should be assigned for file operations File name should be in DOS 8 3 flle name extension format The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does no have to take care of that The file name and extension are case insensitive The library will convert
389. le 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 As you type the actual parameter the next expected parameter will become bold channel byte DC Rea Bookmarks Bookmarks make navigation through a large code easier To set a bookmark use Ctrl Shifttnumber The same princliple applies to the removal of the bookmarks To jump to a bookmark use Ctrl number Go to Line The Go to Line option makes navigation through a large code easier Use the shortcut Ctrl G to activate this option MikroElektronika 52 mikroBasic PRO for PIC32 Column Select Mode This mode changes the operation of the editor for selecting text When column select mode is used highlighted text is based on the character column position of the first character selected to the column of the last character of text selected Text selected in this mode does not automatically include all text between the start and end position but includes all text in the columns between the first and last character selected Column mode editing is sometimes referred to as block mode editing as the act of selecting text forms a rectangle To enter this mode press Alt Left mouse button drag the mouse towards the desired dir
390. lected file from the project E Build the active project Run mikroElektronika s Flash programmer For details about adding and removing files from project see Add Remove Files from Project Related topics Project Settings Project Menu Options File Menu Options Project Toolbar Build Toolbar Add Remove Files from Project 59 MikroElektronika mikoBasic PRO for PIC32 Project Settings The following options are available in the Project Settings window Device select the appropriate device from the device drop down list MCU Clock enter the clock frequency value Build Debugger Type choose debugger type Project Settings Eg device Name P32MX480F512L EG MCU Clock Frequency 80 000000 Build D Build Type Release ICD Debug Debugger Software O mikroICD Related topics Edit Project Customizing Projects Project Manager MikroElektronika 60 mikroBasic PRO for PIC32 Library Manager Library Manager enables simple handling libraries being used in a project Library Manager window lists all libraries extension emc1 which are instantly stored in the compiler Uses folder The desirable library is added to the project by selecting check box next to the library name In order to have all library functions accessible simply press the button Check All t and all libraries will be selected In case none library is needed in a project press the
391. level so the floating multiplication and division is slower and consumes more memory comparing it to the integer The PIC32 supports 64 bit data types but they are less efficient They provide higher precision but lack the code size and the execution Nested Calls Limitations There are no Nested Calls Limitations except by RAM size A Nested call represents a function call within the function body either to itself recursive calls or to another function Recursive calls as a form of cross calling are supported by mikroBasic PRO for PIC32 but they should be used very carefully Also calling functions from interrupt is allowed Calling function from both interrupt and main thread is allowed Be careful because this programming technique may cause unpredictable results if common resources are used in both main and interrupt Variable constant and routine alignment Simple type variables whose size exceeds 2 byte int long float double long double and those exceeding 4 bytes are always set to alignment 4 Routines are always set to aligment 4 Boot Start up Initialization Upon reset MCU positions at the address OXBFCO00000 on which the Boot StartUp function is located BootStartUp function configures CPO coprocessor registers SFR registers associated with the interrupt Stack pointer R29 and global pointer R1 By default the MCU is configured as follows Cache Enabled Prefetch enabled for executable c
392. llator frequency of 10 MHz Delay Cyc Prototype sub procedure Delay Cyc dim x y as word y remainder of the NumberOfCycles 16384 division RMuns Non SS Example Delay Cyc 1 10 1x16384 10 16394 cycles pause Delay Cyc is a library function rather than a built in routine it is presented in this topic for the sake of convenience Delay Cyc Long Rems Nothing SSCS Example Delay Cyc Long 16394 16394 cycles pause Delay Cyc Long is a library function rather than a built in routine it is presented in this topic for the sake of convenience MikroElektronika 193 mikroBasic PRO for PIC32 Clock kHz Prototype sub function Clock kHz as longint Description Function returns device clock in kHz rounded to the nearest integer This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Retums Device cockin kHz rounded tothe nearest integer SSCS Example cix Glock OOOO Moes None Clock Mhz Prototype sub function Clock MHz as word Description Function returns device clock in MHz rounded to the nearest integer This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Retums Device dockin MFZ rounded to the nearestinteger Example elk clock LL Notes Nae Ooo Get Fosc kHz Reums De
393. lways refer to the comprehensive Language Reference A complete list of included libraries is available in the mikroBasic PRO for PIC32 Libraries If you are not very experienced in Basic programming don t panic mikroBasic PRO for PIC32 provides plenty of examples making it easy for you to go quickly 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 29 MikroElektronika mikoBasic PRO for PIC32 Software License Agreement mikroElektronika Associates License Statement and Limited Warranty IMPORTANT READ CAREFULLY This license statement and limited warranty constitute a legal agreement License Agreement between you either as an individual or a single entity and mikroElektronika mikroElektronika Associates for software product Software identified above including any software media and accompanying on line or printed documentation BY INSTALLING COPYING OR OTHERWISE USING SOFTWARE YOU AGREE TO BE BOUND BY ALL TERMS AND CONDITIONS OF THE LICENSE AGREEMENT Upon your acceptance of the terms and conditions of the License Agreement mikroElektronika Associates grants you the right to use Software in a way provided below This Software is owned by mikroElektronika Associates and is protected by copyright law
394. ly FAT and ROOT tables will be erased Also the new volume label will be set MikroElektronika 266 mikroBasic PRO for PIC32 Cf Fat Assign Prototype sub function Cf Fat Assign dim byref filename as char 12 dim file cre attr as byte as word Description Assigns file for file operations read write delete All subsequent file operations will be applied over the assigned file Parameters filename name of the file that should be assigned for file operations The file name should be in DOS 8 3 file name extension format The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does not have to take care of that The file name and extension are case insensitive The library will convert them to proper case automatically so the user does not have to take care of that Also in order to keep backward compatibility with the first version of this library file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between the file name and extension i e MIKROELETXT gt MIKROELE TXT In this case the last 3 characters of the string are considered to be file extension file cre attr file creation and attributes flags Each bit corresponds to the appropriate file attribute Bn mas Description i ofon Reiow s 0x40 Device internal use only n
395. ly 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 typ CANSPI1SetOperationMode _CANSPI MODE CONFIG OxFF set CONFIGURATION mode CANSPI1 module must be in config mode for filter settings Set xd of flter Bl FI to 3 CANSPI1SetFilter CANSPI FILTER Bl F1 3 CANSPI CONFIG XTD MSG 249 MikroElektronika mikoBasic PRO for PIC32 CANSPIRead Prototype sub function CANSPIRead dim byref id as longint dim byref Data as byte 8 dim byref DataLen as byte dim byref CAN RX MSG FLAGS as byte as byte Description If at least one full Receive Buffer is found it will be processed in the following way Message ID is retrieved and stored to location provided by the id parameter Message data is retrieved and stored to a buffer provided by the data parameter Message length is retrieved and stored to location provided by the dataLen parameter Message flags are retrieved and stored to location provided by the CANSPI RX MSG FLAGS parameter Parameters id message identifier address data an array of bytes up to 8 bytes in length dataLen data length address CANSPI RX MSG FLAGS message flags address For message receive flags format refer to CANSPI RX MSG FLACS constants See CANSPI RX MSG FLAGS constants 0 if nothing is received
396. ly bytes they can be also used as unsigned operands in arithmetic operations All arithmetic operators associate from left to right Arithmetic Operators Overview operator Operation Gmeunis Rest U U addition byte short word byte short word integer longint integer longint longword oat longword float subtruction byte short word byte short word integer longint integer longint longword float longword float multiplication byte short word word integer integer longint longint longword division rounds down to nearest integer longword integer longword byte shor integer longword float longint float t word longint float byte short word integer longint longword modulus returns the remainder of integer division byte short word byte short word cannot be used with floating points integer longint integer longint longword longword o qeeteem byte short word Division by Zero If O zero is used explicitly as the second operand i e x div 0 the compiler will report an error and will not generate code But in case of implicit division by zero x div y where y is 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 c
397. m DriveX Left Direction as sbit sfr Direction of the DriveX Left pin dim DriveX Left Direction as external Sbit at TRISB13 bit dim DriveX Right Direction as sbit sfr Direction of the DriveX Right pin dim DriveX Right Direction external as sbit at TRISB11 bit dim DriveY Up Direction as sbit sfr Direction of the DriveY Up pin dim DriveY Up Direction a external Sbit at TRISB12 bit dim DriveY Down Direction as sbit sfr Direction of the DriveY Down pin dim DriveY Down Direction as 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 599 MikroElektronika mikoBasic PRO for PIC32 TP TFT Init Prototype sub procedure TP TFT Inits dim display width as word dim display height as word dim readX ChNo as byte dim readY ChNo as 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 ADCI Init Initalize ADC module TP TFT Init 320 240 13 12 Initialize touch panel dimensions 320x240 TP TFT Set ADC Threshold
398. me 7 F Cf Fat Assign filename 0 Cf Fat Delete end sub Y Tests whether file exists and if so sends its creation date and file size via USART sub procedure M Test File Exist dim fsize as longint year as word month day hour minute as byte outstr as char 12 filename 7 B uncomment this line to search for file that DOES exists filename 7 F uncomment this line to search for file that DOES NOT exist if Cf Fat Assign filename 0 0 then file has been found get its date 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 hour outstr UART1 Write Text outstr WordToStr minute outstr UART1 Write Text outstr file has been found get its modified date Cf Fat Get File 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 UART1 Write Text outstr WordToStr hour outstr UART1 Write Text outstr WordToStr minute outstr UART1 Write Text outstr get file size fsize Cf Fat Get File Size LongIntToStr fsize outstr UART1 Write Line outstr else
399. metry Library See also Built in Routines MikroElektronika 238 mikroBasic PRO for PIC32 Hardware Libraries ADC Library CANSPI Library Compact Flash Library Epson S1D13700 Graphic Lcd Library Flash Memory Library Graphic Lcd Library PC Library Keypad Library Lcd Library Manchester Code Library Memory Manager Library Multi Media Card Library OneWire Library Peripheral Pin Select Library Port Expander Library PS 2 Library PWM Library RS 485 Library Software C Library Software SPI Library Software UART Library Sound Library SPI Library SPI Ethernet Library SPI Ethernet ENC24J600 Library SPI Graphic Lcd Library SPI Lcd Library SPI Lcd8 Library SPI T6963C Graphic Lcd Library T6963C Graphic Lcd Library TFT Display Library Touch Panel Library Touch Panel TFT Library UART Library USB Library ADC Library ADC Analog to Digital Converter module is available with a number of PIC32 MCU modules ADC is an electronic circuit that converts continuous signals to discrete digital numbers ADC Library provides you a comfortable work with the module 239 MikroElektronika mikoBasic PRO for PIC32 Library Routines ADCx Init ADCx Init Advanced ADCx Get Sample ADCx Read ADCx Init Prototype sub procedure ADC1 Init Description This routines configures ADC module to work with default settings T
400. mikroBasic PRO for PIC32 Library routines Use Step Over F8 command for these routines It is not possible to force Code Protect while trying to debug MCU with mikrolCD Trying to debug MCU with mikroICD with pull up resistors set to ON on RB6 and RB7 Related topics mikrolCD Debugger Debug Windows Debugger Options 119 MikroElektronika mikoBasic PRO for PIC32 mikroICD Debugger Windows Debug Windows This section provides an overview of available Debug Windows in mikroBasic PRO for PIC32 Breakpoints Window Watch Values Window RAM Window Stopwatch Window EEPROM Watch Window Code Watch Window Breakpoints Window The Breakpoints window manages the list of currently set breakpoints in the project Doubleclicking the desired breakpoint will cause cursor to navigate to the corresponding location in source code In situations when multiple breakpoints are used within the code it is sometimes handy to enable disable certain breakpoints To do this just check uncheck the desired breakpoint using the checkbox in front of the breakpoint s name Breakpoints Enable Line File Name Watch Values Window Watch Values Window is the main Debugger window which allows you to monitor program execution To show the Watch Values Window select Debug Windows 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 upda
401. mikrolCD Debugger Example Here is a step by step mikroICD Debugger Example L SEP No T 7 0L 0o S First you have to write a program We will show how the mikrolCD works using this example program Lcd Test LCD module connections dim LCD RS as sbit at LATDO bit dim LCD EN as sbit at LATD1 bit dim LCD D4 as sbit at LATBO bit dim LCD DS as Sbit at LATB1 bit dim LCD D6 as sbit at LATB2 bit dim LCD D7 as sbit at LATB3 bit dim LCD RS Direction as sbit at TRISDO bit dim LCD EN Direction as sbit at TRISD1 bit dim LCD D4 Direction as sbit at TRISBO bit dim LCD D5 Direction as sbit at TRISB1 bit dim LCD D6 Direction as sbit at TRISB2 bit dim LCD D7 Direction as sbit at TRISB3 bit End LCD module connections dim text as char 16 i as byte main ADPCFG OxFFFF text mikroElektronika Lcd Init Lcd Cmd LCD CLEAR Lcd Cmd LCD CURSOR OFF for i 0 to 17 Lcd Chr 1 i text i 1 next i end MikroElektronika 116 mikroBasic PRO for PIC32 After successful compilation and MCU programming press F9 to start the mikrolCD After the mikrolCD initialization a blue active line should appear d main 23 i C text mikroElektronika Lcd Init 9 Lcd Cmd LCD CLEAR 9 Lcd Cmd LCD CURSOR OFF 30 for i 0 to 17 Lcd Chr i i text i 1 next i end Watch Values Eh Eh Eh 9o oe er m E XX A P Add Remove gt Properties ty AddAll R
402. n it s time to renew the IP address lease SPI Ethernet 24 600 renewDHCP puse 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 if SPI Ethernet 245600 doDHCPLeaseTime lt gt 0 then SPI Ethernet 243600 renewDHCP 5 it s time to renew the IP address lease with 5 secs for a reply end if wend MikroElektronika 456 mikroBasic PRO for PIC32 SPI Graphic Lcd Library mikroBasic PRO for PIC32 provides a library for operating Graphic Lcd 128x64 with commonly used Samsung KS108 KS107 controller via SPI interface For creating a custom set of Glcd images use Glcd Bitmap Editor Tool Important When using this library with PIC32 family MCUs be aware of their voltage incompatibility with certain number of Samsung KS0108 based Glcd modules So additional external power supply for these modules may be required Library uses the SPI module for communication The user must initialize the appropriate SPI module before using the SPI Glcd Library For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by using the SPI Set Active routine See the SPI Library functions This Library is designed to work with the mikroElektronika s Serial Lcd Glcd Adapter Board pinout see schematic at the bottom of this page for details Library Dependency Tree
403. n mikroBasic PRO for PIC32 imposes strict program organization Below you can find models for writing legible and organized source files For more information on file inclusion and scope refer to Modules and to 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 module should look like this program program name include include other modules VK ok ok ok ck ck ck Ck 0k 0k ck Ck Ck Ck ck kk ck ck Ck ck ck kk ck ck ck ock ck kk kk ck kk kk ck kk ko ko k kx ko KKK Declarations globals No KKK KKK ck ck oko ck ck ck KKK KKK kk ck ek ck ck ck ck ck ck kk KKK KK KKK ko ko ko ko ko ko kocko kockok symbols declarations symbol v constants declarations const structures declarations structure variables declarations dim Name Name2 as type absolute 0x123 external volatile register sfr procedures declarations sub procedure procedure name local declarations end sub v functions declarations sub function function name as return type local declarations end sub VK ok ok ck ck ck ck kk ck kk ck Ck ck Ck ck kk ck ck kk ck kk kk ck ck ock ck kk kk kk ck Sk ko kk Sk ko ko k ko
404. n y coordinate of the bottom left corner of the working area y max y coordinate of the upper right corner of the working area TP Get Calibration Consts 8x min Gy min x max y max Get calibration constants TP Set Calibration Consts Prototype sub procedure TP Set Calibration Consts dim x min as word dim x max as word dim y min as word dim y max as word Sets calibration constants Parameters x min x coordinate of the bottom left corner of the working area x max X coordinate of the upper right corner of the working area y min y coordinate of the bottom left corner of the working area y max y coordinate of the upper right corner of the working area TP Set Calibration Consts 148 3590 19 3370 Set calibration constants be m MikroElektronika 554 mikroBasic PRO for PIC32 Touch Panel TFT Library The mikroBasic PRO for PIC32 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 dim DriveX Left as sbit sfr external DriveX Left line dim DriveX Left as sbit at TB13 bit Hidaka me CUT dim DriveY Up as sbit sfr external DriveY Up line dim DriveY Down as sbit sfr external DriveY Down line i DriveY Down as sbit at TB10 bit di
405. n example provided with your compilers doesn t work 630 Your example works if use the same MCU you did but how to make it work for another MCU 630 need this project finished can you help me 631 Do you have some discount on your compilers development systems for students professors 631 have a question about your compilers which is not listed here Where can find an answer 631 MikroElektronika 26 mikroBasic PRO for PIC32 21 MikroElektronika mikoBasic PRO for PIC32 CHAPTER 1 INTRODUCTION mikroBasic PRO for PIC32 is a powerful feature rich development tool for PIC32 microcontrollers It is designed to provide the programmer with the easiest possible solution to developing applications for embedded systems without compromising performance or control E ft te ee oe oes E ee ee eee wee See oe en Seren 2 oe oe we 2m 4 me E he t d bd c mft m em MEA 25404 pe Q inte 9 7 uan tr Q ot rm Cm teta ya dele mns Wee sum change he mening apret Bnrm les d ARAFE Selo b oven Lid com os D htm E mer mme e 5 n A m Dass a z Abre enter Cafas AN pane cm digital DO e ts DAN a 3 Pj hd emie Sir Ioa IRA ird z So LLLA a m m t Smag vue E et nini Apri alise 1a mas PTEE Geu sena Led Omi LOB CUNBON OF DL gt A9 Ow 1 4 Amey p AC Ow 6 nts aie dust ja amend rom DeLee mme aor ied cmai LCD Cut Gow dipl quic F
406. n resistors Parameters ModulecAddress Port Expander hardware address see schematic at 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 s higher byte PortB pull up down resistors configuration is passed in PullUps s lower byte Each bit corresponds to the appropriate pin of the PortA PortB register Set bit enables pull up for corresponding pin Port Expander must be initialized See Expander Init Set Port Expander s PORTA and PORTB pull up resistors Expander Set PullUpsPortAB 0 SFFFF 365 MikroElektronika mikoBasic PRO for PIC32 Library Example The example demonstrates how to communicate with Port Expander MCP23S17 Note that Port Expander pins A2 A1 AO are connected to GND so Port Expander Hardware Address is 0 Copy Code To Clipboard program PortExpander Port Expander module connections dim SPExpanderRST as sbit at LATFO bit SPExpanderCS as sbit at LATF1 bit SPExpanderRST Direction as sbit at TRISFO bit SPExpanderCS Direction as sbit at TRISF1 bit End Port Expander module connections dim counter as word main counter 0 CHECON 0x32 ADIPCFG OxFFFF Configure AN pins as digital TRISB 0x00 LATB OxFF If Port Expander Library uses SPI1 module SPI2 Init Advanced SPI MASTER SPI 8 BIT 4 SPI SS DISABLE SPI DATA SAMPLI Fl
407. n x axis Valid values 0 63 Rems Noi OOOO Dampe serora sexes CS Notes For side x ans and page layout explanation see schematic atthe botom ofthis pags 459 MikroElektronika mikoBasic PRO for PIC32 SPI Glcd Read Data Prototype sub function SPI Glcd Read Data as byte Reads data from the current location of Glcd memory and moves to the next location Retums One byte from Glcd memory Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Glcd side x axis position and page should be set first See the functions SPI Glcd Set Side SPI_ Glcd Set X and SPI Glcd Set Page Parameters None dim data as byte data SPI Glcd Write Data Prototype sub procedure SPI Glcd Write Data dim data as 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 SPI communication see SPI Glcd Init routine Glcd side x axis position and page should be set first See the functions SPI Glcd Set Side SPI Glcd Set X and SPI Glcd Set Page dim data as byte SPI Glcd Write Data data MikroElektronika 460 mikroBasic PRO for PIC32 SPI Glcd Fill Prototype sub procedure SPI Glcd Fill dim pattern as byte Description Fills Glcd memory with byte pattern To clear the Glcd screen use SPI Gicd Fill 0 To fill the screen completely use SPI Gicd Fill OxFF
408. nario 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 1FDEF must be matched with a closing ENDIF 233 MikroElektronika mikoBasic PRO for PIC32 Here is an example Uncomment the appropriate flag for your application DEFINE resolutioni10 DEFINE resolution12 IFDEF resolutionl0O THEN code specific to 10 bit resolution ELSE IFDEF resolution12 THEN code specific to 12 bit resolution ELSE default code ENDIF ENDIF Unlike 1FDEF IFNDEF checks if flag is not defined by means of DEF INE thus producing the opposite results Include Directive l The 1 parameter directive instructs mikroBasic PRO for PIC32 to include the named text file in the compilation In effect the file is inserted in the compiled text right after the 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 mikroBasic PRO for PIC32 will search for file in order specified by the search paths To specify a filename that includes a space surround the file name with quotation marks 41 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
409. nction or procedure Scope extends from the point where it is declared to the end of the cur rent routine These identifiers are referred to as ocals Identifier is declared in the interface section of the Scope extends the interface section of a module from the point where module itis declared to the end of the module and to any other module or pro gram that uses that module The only exception are symbols which have a scope limited to the file in which they are declared Identifier is declared in the implementation sec Scope extends from the point where it is declared to the end of the mod tion of the module but not within any function or ule The identifier is available to any function or procedure in the module 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 MikroElektronika 190 mikroBasic PRO for PIC32 Name Spaces Name space is a scope within which an identifier must be unique The mikroBasic PRO for PIC32 uses two distinc
410. nd 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 mikroBasic PRO for PIC32 will interpret the meaning of the character from the context 223 MikroElektronika mikoBasic PRO for PIC32 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 select case If Statement Use the keyword i to implement a conditional statement The syntax of the i statement has the following form if expression then statements else other statements end if When expression evaluates to true statements execute If expressionis false other statements execute The expression must convert to a boolean type otherwise the condition is ill formed The else keyword with an alternate block of statements other statements is optional 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 end if end if The compiler treats the construction in this way if express
411. nd the output driver for RBO remains turned on Write modified value Charging T capacitor When to use LATx instead of PORTx Depending on your hardware one may experience unpredictable behavior when using PORTx bits for driving output Displays GLCD LCD chip select pins in SPI interfaces and other cases when you need fast and reliable output LATx should be used instead of PORTx 115 MikroElektronika mikroBasic PRO for PIC32 Language Reference mikroBasic PRO for PIC32 Lexical Elements Whitespace Comments Tokens Literals Keywords Identifiers Punctuators Program Organization Program Organization Scope and Visibility Modules Variables Constants Labels Symbols Functions and Procedures Functions Procedures Types Simple Types Arrays Strings Pointers Structures Types Conversions Implicit Conversion Explicit Conversion Operators Introduction to Operators Operators Precedence and Associativity Arithmetic Operators Relational Operators Bitwise Operators Boolean Operators Expressions Expressions TII MikroElektronika mikoBasic PRO for PIC32 Statements Introduction to Statements Assignment Statements Conditional Statements If Statement Select Case Statement Iteration Statements Loops For Statement While Statement Do Statement Jump Statemen
412. ne Draw a circle ge fl in 50 50 and radius 10 SPI Glcd Circle 50 L 465 MikroElektronika mikoBasic PRO for PIC32 SPI Glcd Circle FIII Prototype sub procedure SPI Glcd Circle Fill dim x center as integer dim y center as integer dim radius as integer dim color as 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 Init routine Draw a circle with center in 50 50 and radius 10 SPI Gled Circle Frat S0 30 409 1 MikroElektronika 466 mikroBasic PRO for PIC32 SPI Glcd Set Font Prototype sub procedure SPI Glcd Set Font dim activeFont as LongInt dim aFontWidth aFontHeight as byte dim aFontOffs as word Sets font that will be used with SPI Glcd Write Char and SPI Glcd Write Text routines 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 aFontOf fs number that represents difference between the mikroBasic PRO for PIC32 character set and regular ASCII set eg if A is 65 in ASCII character and
413. nections Soft SPI Injt Init Soft SPI TRISF2 bit RISF3 bit MikroElektronika 394 mikroBasic PRO for PIC32 Soft SPI Read Prototype sub function Soft SPI Read dim data as byte as byte Description This routine performs 3 operations simultaneously It provides clock for the Software SPI bus reads a byte and sends a byte sdata data to be sent Returns Byte received via the SPI bus Soft SPI must be initialized before using this function See Soft SPI Init routine dim data read data send as byte Read a byte and assign it to data read variable data send byte will be sent via SPI during the Read operation data read Soft SPI Read data send Soft SPI Write Prototype sub procedure Soft SPI Write dim data as 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 SAA Library Example This code demonstrates using library routines for Soft SPI communication Also this example demonstrates working with Microchip s MCP4921 12 bit D A converter Copy Code To Clipboard DAC module connections dim Chip Select as sbit at LATDO bit SoftSpi CLK as sbit at LATD6 bit SoftSpi SDI as sbit at RD2 bit SoftSpi SDO as sbit at LATD3 bit dim Chip Select Direction as sbit at TRISDO bit SoftSpi CLK Direction as sb
414. ned to ease the use of compiler and included library routines mE Programmer Fil Package Manager Active Comment Editor Ctrl Alt C Ascii Chart EEPROM Editor Export Code To HTML GLCD Bitmap Editor Interrupt Assistant Ctrl Alt I LCD Custom Character Seven Segment Editor UDP Terminal USART Terminal Ctri T Options F12 Related topics Keyboard shortcuts Tools Toolbar 4l MikroElektronika mikoBasic PRO for PIC32 Help Help Menu Options Help Fi Migration Document Check For Updates tmikroElektronika Support Forums mikroElektronika Web Page A How To Register About Hp pesmpim Related topics Keyboard shortcuts Help Toolbar MikroElektronika 48 mikroBasic PRO for PIC32 mikroBasic PRO for PIC32 IDE IDE Overview The mikroBasic PRO for PIC32 is an user friendly and intuitive environment For a detailed information on a certain part of IDE simply click on it hovering a mouse cursor above a desired IDE part will pop up its name C Prop an Files libre de rond dier nne PRO Fer PC X xamptes evel emet System VIDE v ALCD KOG 2x1 4 LCD mbp 2 fh UA we feet DAC ba ow ee NI T RUNE IM RI d amp 9 97b434b03X Aw dcm deus Dr Queste 30 Tum Meme 0 om we i a byte toep variable 45 dus 4 CESE IE azire mb procedure Bove Delayi Pemstion usod fos text soring v
415. nel toggle the display between graphic panel 0 and graphic 1 SPI MikroElektronika mikoBasic PRO for PIC32 case 1 blinking cursor SPI T6963C cursor 1 SPI T6963C cursor blink 1 case 2 non blinking cursor SPI T6963C cursor 1 SPI T6963C cursor blink 0 end select Delay ms 300 end if Ve r If RB13 is pressed perform the Partial image demonstration LAE d IFDEF PARTIAL IMAGE DEMO if RB13 bit 1 then PI T6963C_setGrPanel 0 PI T6963C_setTxtPanel 0 PI T6963C txtFill 0 PI T6963C_setGrPanel 1 PI T6963C_setTxtPanel 0 PI T6963C graphics 1 PI T6963C text 1 PI T6963C displayGrPanel 1 PI T6963C write text txt2 5 15 SPI T6963C ROM MODE XOR elay lsec Qugcgcuuuuuucu n PI T6963C grFill 0 PI T6963C Partiallmage 0 0 64 64 240 128 mikroE 240x128 bmp Delay ms 1500 n SPI T6963C Partiallmage 0 0 128 128 240 128 mikroE 240x128 bmp Delay ms 1500 SPI T6963C Partiallmage 0 0 240 128 240 128 mikroE 240x128 bmp Delay ms 1500 SPI T6963C txtFill 0 SPI T6963C write text txt 0 0 SPI T6963C ROM MODE XOR SPI T6963C write text txtl 0 15 SPI T6963C ROM MODE XOR end if ENDIF end if end if end if end if Ve Move cursor even if not visible Inc cposx if cposx SPI T6963C txtCols then cposx 0 Inc cposy if cposy SPI T6963C grHeight div SPI T6963C C
416. nes 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 Id 1e set UART1 active RS485Master Send dat 1 160 send message through UARTI1 UART Set Active UART2 Read UART2 Write UART2 Data Ready UART2 Tx Id 1e set UART2 active RS485Master Send dat 1 160 send through UART2 MikroElektronika 568 mikroBasic PRO for PIC32 Library Example This example demonstrates simple data exchange via UART If MCU is connected to the PC you can test the example from the mikroBasic PRO for PIC32 USART communication terminal launch it from the drop down menu Tools USART Terminal or simply click the USART Terminal Icon Ei Copy Code To Clipboard program UARTI dim uart rd as byte main CHECON 0x32 ADIPCFG UART OxFFFF 1 Init 56000 Delay ms 100 UART UART UARI while TRUE if UART1 Data Ready lt gt 0 then end Tl Wri r1 Wri r1 Write Text Start
417. net module has to be initialized See SPI Ethernet Init dim buffer as byte 17 buffer mikroElektronika SPI Ethernet putBytes buffer 16 put an RAM array into ENC28J60 buffer SPI Ethernet putConstBytes Prototype sub procedure SPI Ethernet putConstBytes const ptr as byte dim n as word Description This is MAC module routine It stores requested number of const bytes into xNC28360 RAM starting from current ENC28460 write pointer EWRPT location Parameters ptr const buffer containing bytes to be written into ENC28760 RAM n number of bytes to be written Nothing Requires Ethernet module has to be initialized See SPI Ethernet Init const buffer as byte 17 buffer mikroElektronika SPI Ethernet putConstBytes buffer 16 put a const array into ENC28J60 buffer SPI Ethernet putString Prototype sub function SPI Ethernet putString dim ptr as byte as 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 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 dim buffer as string 16 buffer mikroElektronika SPI Ethernet putString buffer put a RAM string into ENC28J60 buffer MikroElektronika
418. 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 116 mikroBasic PRO for PIC32 Higher Prototype sub function Higher dim number as longint as 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 d 0x12345678 tmp Higher d Equals 0x34 Highest Prototype sub function Highest dim number as longint as byte Description Function returns the highest byte of number Function does not interpret bit patterns of number it merely returns 8 bits as found in register This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Parameters number input 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 14 MikroElektronika
419. ng memory address or a dereferenced value of an object for example myst ring or PORTB txt mikroElektronika an 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 MikroElektronika 596 mikroBasic PRO for PIC32 memcmp Prototype sub function memcmp dim pl p2 as byte dim n as word as integer Description The function returns a positive negative or zero value indicating the relationship of first n words of memory areas starting at addresses p1 and p2 This function compares two memory areas starting at addresses p1 and p2 for n words and returns a value indicating their relationship as follows Value Meaning e pl less than p2 pl equal to p2 gt 0 pl greater than p2 The value returned by the function is determined by the difference between the values of the first pair of words that differ in the strings being compared For parameters p1 and p2 you can use either a numerical value literal variable constant indicating memory address or a dereferenced value of an object for example amp mystring or PORTB txt mikroElektronika txt sub mikro res memcmp txt Gtxt sub 16 returns 69 which is ASCII code of the first differing character letter E memcpy Prototype sub procedure memcpy dim pl p2 as byte dim nn as word Description The function copies nn words from the
420. ng new source file 622 MikroElektronika 29 mikoBasic PRO for PIC32 Opening an existing file 622 Printing an open file 622 Saving file 622 Saving file under a different name 623 Closing file 623 Search Paths 623 Paths for Source Files mbas 624 Edit Project 625 Clean Project Folder 626 Compilation 627 Output Files 627 Assembly View 627 Creating New Library 628 Multiple Library Versions 628 Frequently Asked Questions 629 Can use your compilers and programmer on Windows Vista Windows 7 629 am getting Access is denied error in Vista how to solve this problem 629 What are differences between mikrobasic PRO mikroPascal PRO and mikroC PRO compilers Why do they have different prices 629 Why do your PIC compilers don t support 12F508 and some similar chips 629 What are limitations of demo versions of mikroElektronika s compilers 629 Why do still get demo limit error when purchased and installed license key 629 have bought license for the older version do have to pay license for the new version of the com piler 630 Do your compilers work on Windows Vista Windows 7 630 What does this function procedure routine do 630 try to compile one of the provided examples and nothing happens what is the problem 630 Can get your library sources need to provide all sources with my project 630 Can use code developed in your compilers in commercial purposes Are there some limitations 630 Why does a
421. nnection VCC3 y J veca L C i E um rm c E m LJ cj rm c m r3 qj OSCILLATOR eno Hl 9 PIC32MX460F512L 7 cheno vcc pm o g r3 pos VCC3 r3 m veus B z cj VUSBE3 o VCC3 GND cj MVBUSLOI oo g o DS 9 6S i De i Mis USB connection scheme MikroElektronika 916 mikroBasic PRO for PIC32 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 971 MikroElektronika mikoBasic PRO for PIC32 Button Prototype Description Parameters sub function Button dim byref port as word dim pin as byte dim time as word dim ActiveState as byte as word 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 port button port address pin button pin time debouncing period in milliseconds active state determines what is considered as active st
422. no longer in project and hover the mouse over the comment you will be prompted to either add file to project or remove event definition from Active Comment for this file Warning A File linked to this active comment is missing Would you like to add File to a project and make events associated with in valid or unlink file from Active Comment v Show more info If you remove active comment file from the Project Manager you ll receive this message Warning A Missing a file for this active comment Would you like to add File to a project or delete this Active Comment v Show more info Click on Yes button you ll prompted for an active comment file MikroElektronika 100 mikroBasic PRO for PIC32 Look in Easy_GSM_GPRS e activeComment B S activeComment2 My Recent Documents File name Open Files of type Active Link Files ml C Open as read only My Network If you click No comment will be removed from the source code Renaming Active Comment When you click on rename button you will be prompted to enter new name Active Comments Editor Select Active Comment activeComment Active Comment Actions New Rename Enter new Active Comment Name factiveCommentRename Rename Properties 3 Attributes Url ww mikroe com Image Easy GSM GPRS jpg File Ni 3 Events OnLeftClick Alt OpenUrl OnRightClick None OnDbi
423. normal function call and return discipline Library Routines Setjmp Longjmp Setjmp Prototype sub function setjmp dim byref env as word 4 as integer 0 if the return is from direct invocation nonzero value if the return is from a call to longjmp this value will be set by the 1ongjmp 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 dim buf as word 4 Setjmp buf Longjmp Prototype sub procedure longjmp dim byref env as word 4 dim val as 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 interim the behavior is undefined Parameters env buffer holding the information saved by the corresponding setjmp invocation val value to be returned by the corresponding setjmp function Invocation of 1ongjmp must occur before return from the function in which setjmp was called encounters dim buf as word 4 Longjmp buf 2 MikroElektronika 594 mikroBasic PRO for PIC32 Library Example Example demonstrates function cross calling using setjmp and longjmp functions When called Setjmp saves its calling environment in its buf argument for later use by the Longjmp Longjmp on the
424. nput value Parameters disF1t network traffic receive filter flags Each bit corresponds to the appropriate network traffic receive filter 0x01 MAC Broadcast traffic receive filter flag When set MAC SPI Ethernet 243600 broadcast traffic will be disabled BROADCAST multicast traffic will be disabled MULTICAST KAC mum oC 7 0x80 MAC Unicast traffic receive filter flag When set MAC SPI Ethernet 24 600 unicast traffic will be disabled UNICAST Ethernet module has to be initialized See SPI Ethernet 24 600 Init SPI Ethernet 245 600 Disable SPI Ethernet 243600 CRC Ethernet 24j600 UNICAST disable CRC checking and Unicast poem Advanced filtering available in the ENC24J600 module such as Pattern Match Magic Packet and Hash Table can not be disabled by this routine This routine will change receive filter configuration on the fly It will not in any way mess with enabling disabling receive transmit logic or any other part of the ENC247600 module The NC243600 module should be properly cofigured by the means of SPI Ethernet 24j600 Init routine The ENC243600 module should be properly cofigured by the means of SPI Ethernet 24j600 Init routine MikroElektronika mikroBasic PRO for PIC32 SPI Ethernet 24j600 doPacket Prototype sub function SPI Ethernet 243600 doPacket as byte Description This is MAC module routine It processes next received packet if such exists Packets a
425. ns are relevant MODIFY Data is modified to set the RBO bit WRITE PORTB is written with the modified data The output driver for RBO turns on and the Modify value capacitor starts to charge Write modified value Discharged 00000000 C capacitor 0850000 To Oe The second line PORTB B1 1 will be decoded like in this way READ PORTB is read STORE Because the capacitor is still charging the voltage at RBO is still low and reads as a 0 since we are reading from the pins directly not from the PORTB register Store read Value we didn t expect here value but physically still correct one STO CIA TERNAL REGISTER Read from pins Charging 00000000 c capacitor Charging I 00000000 TC Capacitor Actual voltage levels on MCU pins are relevant MODIFY Data is modified to set the bit WRITE PORTB is written with the new data The output driver for RB1 turns on but the Modify value driver for RBO turns back off INTERNAL i REGISTER baneanenemnemeanenemneneneenennenennenennanennanemnenennanennand Write modified value pe H Charging l capacitor Discharging 00000010 Decne 00000000 173 MikroElektronika mikoBasic PRO for PIC32 To correct the problem in the code insert a delay after each PORTB Bx 1 line or modify the entire PORTB register in a single line PORTB 0500000011 This problem can be avoided by using LATx
426. nsor LCD module connections dim LCD RS as sbit at LATB2 bit dim LCD EN as sbit at LATB3 bit dim LCD D4 as sbit at LATB4 bit dim LCD D5 as sbit at LATB5 bit dim LCD D6 as sbit at LATB6 bit dim LCD D7 as sbit at LATB7 bit dim LCD RS Direction as sbit at TRISB2 bit dim LCD EN Direction as sbit at TRISB3 bit dim LCD D4 Direction as sbit at TRISB4 bit dim LCD D5 Direction as sbit at TRISB5 bit dim LCD Do Direction as sbit at TRISB6 bit dim LCD D7 Direction as sbit at TRISB7 bit End LCD module connections dim temp as float txt as char 16 Convert ADC value to Celsius degrees format sub function ADC to degC as float result ADC1 Get Sample 8 Read ADC value from AN8 pin result 3 25 1024 result 0 5 100 end sub main CHECON 0x32 ADIPCFG OxFFF7 Configure AN8 pin as analog I O ADC1_ Init Initialize ADC Delay 100ms Lcd Init r Initialize LCD Lcd Cmd LCD CLEAR Clear LCD Lcd Cmd LCD CURSOR OFF Turn cursor off Lcd Out 1 1 Temperature 3 while TRUE temp ADC to degC Convert ADC value to Celsius degrees format FloatToStr temp txt Led Chr 2 13 223 Print degree character C for Centigrades Different LCD displays have different char code for degree Lcd Chr 2 14 C instead of 223 If you see greek alpha letter try typing 178 Lcd Out 2 5 txt Display value on the LCD Delay lsec 1 second delay wend en
427. nterrupt and in main thread and performs smart context switching between two of them saving only the registers that have been used in both threads It is not recommended to use a function call from interrupt In case of doing that take care of stack depth Use the DisableContextSaving to instruct the compiler not to automatically perform context switching This means that no register will be saved restored by the compiler on entrance exit from interrupt service routine This enables the user to manually write code for saving registers upon entrance and to restore them before exit from interrupt 141 MikroElektronika mikoBasic PRO for PIC32 Interrupt Example Here is a simple example of handling the interrupts from Timer1 if no other interrupts are allowed program Timerl interrupt sub procedure TimerlInt iv IVT TIMER 1 ilevel 7 ics ICS SRS TIIE bit 0 Clear TIIF LATB not PORTB Invert PORTB end sub main ADIPCFG OxFFFF Initialize AN pins as digital TRISB 0 initialize PORTB as output LATB QxAAAA Initialize PORTB value TMR1 0 reset timer value to zero PRI 65000 Load period register TIIPO bit 1 set interrupt TIIP1 bit 1 t priority T1IP2 bit 1 obo 4 TCKPSO bit 1 Set Timer Input Clock TCKPSI bit 1 Prescale value to 1 256 EnableInterrupts Enable all interrupts TIIE bit 1 Enable Timerl Interrupt ON TICON bit 1 Enable Timerl end M
428. o dock the window in the position indicated release the mouse button Tip To move a dockable window without snapping it into place press CTRL while dragging it Saving Layout Once you have a window layout that you like you can save the layout by typing the name for the layout and pressing the Save Layout Icon ik To set the layout select the desired layout from the layout drop down list and click the Set Layout Icon To remove the layout from the drop down list select the desired layout from the list and click the Delete Layout Icon la Default Layout Code Layout Debug Layout NEN Auto Hide Auto Hide enables you to see more of your code at one time by minimizing tool windows along the edges of the IDE when not in use Click the window you want to keep visible to give it focus Click the Pushpin Icon 2X on the title bar of the window MikroElektronika 82 mikroBasic PRO for PIC32 DERK DOR EZ Project Manager a EE TEES I P RE s EA B Oo Sources S Lcd mbas e Binaries 73 Project level defines 7j Image Files 7 EEPROM Files Active Comments Files amp 7j Output Files 25 Lcd hex Lcd asm 173 Other Files amp Lcd mb m aM S sabeuey paload fii aeure w 32a 044 musumsmusumuumuuusuma ui When an auto hidden window loses focus it automatically slides back to its tab on the edge of the IDE While a window is aut
429. o 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 mikroBasic PRO for PIC32 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 ToolO Tool9 83 MikroElektronika mikoBasic PRO for PIC32 Options Tool Name Notepad File Name C WINDOWS NOTEPAD EXE amp Parameters 1 Macro HEX FILE NAME I Full path and name of the out i Insert Shortcut F11 NT 3 Clear all fields C Close when finished cv Output settings By modifying Output Settings user can configure the content of the output files You can enable or disable for example generation of ASM and List file Also user can choose optimization level and compiler specific settings which include case sensitivity dynamic link for string literals setting described in mikroBasic PRO for PIC32 specifics Build all files as library enables user to use compiled library emc1 on any MCU when this box is checked or for a selected MCU when this box is left unchec
430. o s Keypad Key Press Notes Ne oS Keypad Key Click Prototype sub function Keypad Key Click as word Description Call to Keypad Key Click is a blocking call the function waits until some key is pressed and released When released the function returns 1 to 16 depending on the key If more than one key is pressed simultaneously the function will wait until all pressed keys are released After that the function will return the code of the first pressed key Parameters None The code of a clicked key 1 16 If no key is clicked returns O Port needs to be initialized for working with the Keypad library see Keypad Init kp Keypad Key Click 317 MikroElektronika mikoBasic PRO for PIC32 Library Example The following code can be used for testing the keypad It is written for keypad 4x3 or 4x4 The code returned by the keypad functions 1 16 is transformed into ASCII codes 0 9 A F and then sent via UART1 Copy Code To Clipboard program Keypad Test dim kp oldstate as byte txt as char 6 Keypad module connections dim keypadPort as longword at PORTD dim keypadPort Direction as longword at TRISD End Keypad module connections main CHECON 0x32 ADIPCFG OxFFFF oldstate 0 UART1_Init 19200 Delay ms 10 Keypad Init Initialize Keypad UART1 Write Text Press any key on your keypad UART1 Write 10 UART1 Write 13 while TRUE kp 0 Reset key code va
431. ocedure memset dim p as byte dim character as byte dim n as word Description The function fills the first n words in the memory area starting at the address p with the value of word character For parameter you can use either a numerical value literal variable constant indicating memory address or a dereferenced value of an object for example mystring or PORTB txt mikroElektronika wan memset txt a 2 routine will copy the character a into each of the first n characters of the string txt Prototype sub procedure strcat dim byref sl s2 as string The function appends the value of string s2 to string si and terminates s1 with a null character txt mikroElektronika txt sub mikr txt 3 0 sStrost txt test routine will append the test at the place of th first null character adding terminating null character to the result MikroElektronika 598 mikroBasic PRO for PIC32 strcat2 Prototype sub procedure strcat2 dim byref 1 sl s2 as string Description The procedure adjoins string s2 at the end of the string s1 or at the first null character of the s1 and places the result string into 1 string dim txt as string 16 txt sub as string 5 l as string 21 strcat2 1 txt txt sub Y routine will adjoin strings txt and txt sub and place the result into 1 strchr Prototype sub function strchr dim byref s as string dim ch as byt
432. ode Editor will display a new main module It contains the bare bones of the program program MyProject main procedure main Place program code here end Other than comments nothing should precede the keyword program After the program name you can optionally place the include clauses Place all global declarations constants variables labels routines structures before the label main Other Modules Modules other than main start with the keyword module Newly created blank module contains the bare bones module MyModule implements end Other than comments nothing should precede the keyword module After the module name you can optionally place the include clauses MikroElektronika 192 mikroBasic PRO for PIC32 Interface Section Part of the module above the keyword implements is referred to as interface section Here you can place global declarations constants variables labels routines structures for the project 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 module Prototypes must exactly match the declarations Implementation Section Implementation section hides all the irrelevant innards from other modules allowing encapsulation of code Everything declared below the keyword implements is private i e has its scope limited to the file When you declare an identifier in the implemen
433. ode To Clipboard program I2C Simple main program I2C Simple dim i b as char sub procedure EEPROM 24C02 Init I2C2 Init 100000 end sub ME Writes data to 24C02 EEPROM signle location sub procedure EEPROM _ pede WrSingle dim wAddr as byte dim wData as byte I2C2 Start issue I2C start signal I2C2 Write 0xA0 send byte via I2C command to 24cO2 I2C2 Write wAddr send byte address of EEPROM location I2C2 Write wData send data data to be written I2C2 Stop end sub V Reads data from 24C02 EEPROM single location random sub function EEPROM 24C02 eg EE m rAddr as byte as byte I2C2 Start issue I2C start signal I2C2 Write 0xA0 send byte via I2C device address W I2C2 Write rAddr send byte data address I2C2 Restart issue I2C signal repeated start I2C2 Write 0xA1 send byte device address R result I2C2 Read 1 Read the data NO acknowledge MikroElektronika 314 mikroBasic PRO for PIC32 I2C2 Stop end sub main CH AD T T ECON 0x30 1PCFG OxFFFFFFFF PROM 24C02 Init 0x00 for i 0x00 to 0x80 Inc b Delay ms 5 next i for i 0x00 to 0x80 LATD 1 ATB Delay ms 100 next i end EEPROM 24C02 WrSingle i b Y Y Y Y Set PORTB value to zero Configure PORTB as output Configure PORTB as output
434. ode and constants Flash waitstates set for specified oscillator frequency Executable code allocated in the KSEGO Data allocated in the KSEG1 After this start up function has been executed MCU will jump into the main routine Interupts will be set accordingly to the settings in the Edit Project 167 MikroElektronika mikoBasic PRO for PIC32 PIC32 Memory Organization The PIC32MX microcontrollers provide 4 GB of unified virtual memory address space All memory regions including program memory data memory SFRs and Configuration registers reside in this address space at their respective unique addresses The program and data memories can be optionally partitioned into user and kernel memories In addition the data memory can be made executable allowing the PIC32MX to execute from data memory Key features of PIC32MX memory organization include the following 32 bit native data width Separate User and Kernel mode address spaces Flexible program Flash memory partitioning Flexible data RAM partitioning for data and program space Separate boot Flash memory for protected code Robust bus exception handling to intercept runaway code Simple memory mapping with Fixed Mapping Translation FMT unit Cacheable and non cacheable address regions MikroElektronika 168 mikroBasic PRO for PIC32 PIC32MX Memory Layout The PIC32MX microcontrollers implement two address spaces virtual and physica
435. oduleAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written Data to be written to PortA are passed in Data s higher byte Data to be written to PortB are passed in Data s lower byte Nothing Port Expander must be initialized See Expander Init Port Expander s PortA and PortB should be configured as outputs See Expander Set DirectionPortA Expander Set DirectionPortB and Expander Set DirectionPortAB routines Write a byte to Port Expander s PORTA and PORTB Expander Set DirectionPortAB 0 0000 set expander s porta and portb to be output Expander Write PortAB 0 AA55 Set DirectionPortA sub procedure Expander Set DirectionPortA dim ModuleAddress Data as byte The function sets Port Expander s PortA direction ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written to the PortA direction register Each bit corresponds to the appropriate pin of the PortA register Set bit designates corresponding pin as input Cleared bit designates corresponding pin as output Nothing Port Expander must be initialized See Expander Init Set Port Expander s PORTA to be output Expander Set DirectionPortA 0 00 MikroElektronika mikoBasic PRO for PIC32 Expander Set DirectionPortB Prototype sub procedure Expander Set DirectionPortB dim ModuleAddress Data as byte The function s
436. of displaying and merging text and graphics and it manages all interfacing signals to the displays Row and Column drivers For creating a custom set of Glcd images use Glcd Bitmap Editor Tool Important When using this library with PIC32 family MCUs be aware of their voltage incompatibility with certain number of T6963C based Glcd modules So additional external power supply for these modules may be required Glcd size based initialization routines can be found in setup library files located in the Uses folder The user must make sure that used MCU has appropriate ports and pins If this is not the case the user should adjust initialization routines The library uses the SPI module for communication The user must initialize the appropriate SPI module before using the SPI T6963C Glcd Library For MCUs with multiple SPI modules it is possible to initialize both of them and then switch by using the SPI Set _ Active routine See the SPI Library functions This Library is designed to work with mikroElektronika s Serial Glcd 240x128 and 240x64 Adapter Boards pinout see schematic at the bottom of this page for details To use constants located in Lib SPIT6963C Const mbas file user must include it the source file include Lib SPIT6963C Const 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
437. of numerical value by passing it to one of the following routines ByteToStr ShortToStr WordToStr IntToStr LongIntToStr LongWordToStr FloatToStr WordToStrWithZeros IntToStrWithZeros LongWordToStrWithZeros LongIntToStrWithZeros ByteToHex ShortToHex WordToHex IntToHex LongWordToHex LongintToHex StrTolnt StrToWord The following sub functions convert decimal values to BCD and vice versa Bcd2Dec Dec2Bcd Bcd2Dec16 Dec2Bcd16 MikroElektronika 582 mikroBasic PRO for PIC32 ByteToStr Prototype sub procedure ByteToStr dim input as byte dim byref output as string 3 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 Destination string should be at least 4 characters in length dim t as byte txt as string 3 24 ByteToStr t txt txt is 24 one blank here ShortToStr Prototype sub procedure ShortToStr dim input as short dim byref output as string 4 Description Converts input short signed byte number to a string The output string is right justified and remaining positions on the left if any are filled with blanks Parameters input signed short number to be converted output destination Hp E e Returns Nothing eee Destination string should be at least 5 characters
438. of the include clause It consists of the reserved word include followed by a quoted module name Extension of the file should not be included You can include one file per include clause There can be any number of the include clauses in each source file but they all must be stated immediately after the program or module name 191 MikroElektronika mikoBasic PRO for PIC32 Here s an example program MyProgram include utils include strings include MyUnit For the given module name the compiler will check for the presence of emc1 and mbas files in order specified by search paths If both mbas and emc1 files are found the compiler will check their dates and include the newer one in the project If the mbas file is newer than the emc1 then mbas file will be recompiled and new emc1 will be created overwriting the old emc1 If only the mbas file is found the compiler will create the emc1 file and include it in the project If only the emc1 file is present i e no source code is available the compiler will include it as found If none of the files found the compiler will issue a File not found warning Main Module Every project in mikroBasic PRO for PIC32 requires a single main module file The main module 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 Project Wizard C
439. of the local variable with the global pointer and using it to alter the variable s address should be avoided Notes emc1 files compiled with or without SSA enabled are fully compatible and can be used and mixed without any restrictions except pointers to functions Functions functions declarations and pointers that may point to these functions must be compiled with the same option either SSA enabled or disabled If this is not the case compiler will report an error MikroElektronika 164 mikroBasic PRO for PIC32 Asm code and SSA optimization If converting code from an earlier version of the compiler which consists of mixed asm code with the C code keep in mind that the generated code can substantially differ when SSA optimization option is enabled or disabled This is due to the fact that SSA optimization uses certain working registers to store routine parameters W10 W13 rather than storing them onto the function frame Because of this user must be very careful when writing asm code as existing values in the working registers used by SSA optimization can be overwritten To avoid this it is recommended that user includes desired asm code in a separate routine Debugging Notes SSA also influences the code debugging in such a way that the local variables will be available in the Watch Window only in those parts of the procedure where they have useful value eg on entering the procedure variable isn t available un
440. olean logic and return either TRUE all ones or FALSE zero logical AND logical OR logical exclusive OR XOR logical negation Unary Operators Unary operators are operators that take exactly one argument 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 also but it doesn t affect data For example b 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 Address and Indirection Operator In the mikroBasic PRO for PIC32 address of an object in memory can be obtained by means of an unary operator 6 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 EE constructs a pointer to its operand MikroElektronika 220 mikroBasic PRO for PIC32 See Pointers for more details on this subject Note Besides these sizeof and explicit conversion unary operators are supported also Sizeof Operator The prefix unary operator sizeof returns an integer con
441. on MCU Refer to MCU datasheet for details MikroElektronika 314 mikroBasic PRO for PIC32 Library Example The example changes PWM duty ratio on channels 1 and 2 continuously If LEDs are connected to channels 1 and 2 a gradual change of emitted light will be noticeable Copy Code To Clipboard program Pwm Demo dim current duty old duty current dutyl old dutyl as word pwm periodl pwm period2 as word sub procedure InitMain CHECON 0x32 ADIPCFG OxFFFF initialize AN pins as digital TRISB OxFFFF configure PORTB pins as input PORTD 0 set PORTD to 0 TRISD 0 designate PORTD pins as output end sub main InitMain current duty 100 initial value for current_duty current dutyl 100 initial value for current dutyi pwm periodl PWM Init 5000 1 1 2 pwm period2 PWM Init 10000 2 1 3 PWM Start 1 PWM Start 2 PWM Set Duty current duty 1 set current duty for PWMI PWM Set Duty current dutyl 2 set current duty for PWM2 while TRUE if RBO bit 1 then endless loop button on RBO pressed Delay ms 1 current duty current duty 5 increment current duty if current duty pwm periodl then if we increase current duty greater then possible pwm periodl value current duty 0 reset current duty value to zero end if PWM Set Duty current duty 1 set newly acquired duty ratio end if if RB1 bit 1 then button on RBI pressed Delay ms 1 current d
442. ond 4 end Functions reentrancy Functions reentrancy is allowed Remember that the PIC32 have memory limitations that can vary between MCUs MikroElektronika 200 mikroBasic PRO for PIC32 Types Basic 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 mikroBasic PRO for PIC32 supports many standard predefined and user defined data types including signed and unsigned integers of various sizes arrays strings pointers and structures Type Categories Types can be divided into simple types arrays strings pointers structures 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 mikroBasic PRO for PIC32 has 16 bits Here is an overview of simple types in mikroBasic PRO for PIC32 float 32 bit 1 17549435082 108 6 80564774407 10 8 int64 64 bit 9223372036854775808 9223372036854775807 You can assign signed to unsigned or vice versa only using the explicit conversion Refer to Types Conversions for more information 201 MikroElektr
443. onika mikoBasic PRO for PIC32 Derived Types The derived types are also known as structured types They are used as elements in creating more complex user defined types The derived types include arrays pointers structures Arrays An array represents an indexed collection of elements of the same type called the base type Since 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 type array length Each of the elements of an array is numbered from 0 through array length 1 Every element of an array is of type and can be accessed by specifying array name followed by element s index within brackets Here are a few examples of array declaration dim weekdays as byte 7 dim samples as word 50 main Now we can access elements of array variables for example samples 0 1 if samples 37 0 then x 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 as byte 12 31 28 31 30 31 30 31 31 30 31 30 31 Note that indexing is zero based in the previous example number of days in January is MONTHS 0 and number of days in December is MONTHS 11 MikroElektronika 202 mikroBasic PRO for PIC32
444. onnects the function with specific interrupt vector For more information on IVT refer to the PIC32 Family Reference Manual Configuring Interrupts The PIC32MX interrupt controller can be configured to operate in one of two modes Single Vector mode all interrupt requests will be serviced at one vector address mode out of reset Multi Vector mode interrupt requests will be serviced at the calculated vector address Single Vector Mode In this mode the CPU always vectors to the same address This means that only one ISR can be defined The Single Vector mode address is calculated by using the Exception Base EBase address its address default is OX9FCO01000E The exact formula for Single Vector mode is as follows Single Vector Address EBase 0x200 Multi Vector Mode In this mode the CPU vectors to the unique address for each vector number Each vector is located at a specific offset with respect to a base address specified by the EBase register in the CPU The individual vector address offset is determined by the following equation EBase Vector_Number x Vector_Space 0x200 By default the compiler configures interrupts in the Multi Vector mode with the EBase address set to 0x9FC01000 and vector spacing of 32 Configuring the Interrupt operating mode is performed in the Edit Project window 139 MikroElektronika mikoBasic PRO for PIC32 Interrupt Priorities In the Multi Vector Mode the user is able to a
445. ons Don BesHpies New project Open Project Save Project UNI Edit project settings Close current project Clean project folder n Add File To Project Remove File From Project Build Toolbar 95 0 Build Toolbar comes with the following options Den Besdpon O E Build current project r1 Build all opened projects Build and program active project Start programmer and load current HEX file 11 MikroElektronika mikoBasic PRO for PIC32 Debug Toolbar Debug Toolbar comes with the following options teon Descmpton S O BM sensa smunrermieich chet netoen O B ente MB seem Step Over E3 Step Out OZ Sws remm B i View Stopwatch Window Styles Toolbar Styles toolbar allows you to easily change colors of your workspace Office 2003 Blue v Office 2003 Blue Office 2003 Silver Office 2003 Olive Office XP Chocolate Arctic Silverfox Soft sand MikroElektronika 18 mikroBasic PRO for PIC32 Tools Toolbar Tools Toolbar comes with the following default options E Run USART Terminal A EEPROM ASCII Chart CI Seven Segment Editor Open Active Comment editor apee o Tip The Tools toolbar can easily be customized by adding new tools in Options menu window View Toolbar ia fn View Toolbar provides access to assembly code listing file and statistics windows C Be plon Open assembly code in editor FJ Op
446. ons after preprocessing To remove file s from the project click the Remove File from Project Icon a 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 p 1d 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 pld Next open it and write something like this PLD TEST Once you have done this save the file In the Project Manager add pld test 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 project level defines Related topics Project Manager Project Settings Edit Project 619 MikroElektronika mikoBasic PRO for PIC32 Source Files Source files containing source code should have the extension mbas The list of source files relevant to the application is stored in project file with extension mbp32 along with other project information You can compile source files only if they are part of the
447. opened for reading See Mmc Fat Reset dim character as byte Mmc Fat Read character MikroElektronika 344 mikroBasic PRO for PIC32 Mmc Fat Rewrite Requires MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init The file must be previously assigned See Mmc Fat Assign open file for writing Mme Fat Rewrite Mmc Fat Append Prototype sub procedure Mmc Fat Append Description Opens the currently assigned file for appending Upon this function execution file pointers will be positioned after the last byte in the file so any subsequent file write operation will start from there Nothing Requires MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init The file must be previously assigned See Mmc Fat Assign open file for appending Mmc Fat Append None Mmc Fat Delete Requires MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init The file must be previously assigned See Mmc Fat Assign delete current fil Mme Fat Delete None 945 MikroElektronika mikoBasic PRO for PIC32 Mmc Fat Write 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 Protot
448. or PIC32 SPI Lcd8 Out Cp iia sub procedure SPI Lcd8 Out CP dim byref text as 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 SPI communication see SPI Lcd8 Config routine Write text Here at current cursor position SPI Leds Out Cp Here SPI Lcd8 Chr Prototype sub procedure SPI Lcd8 Chr dim row column out char as byte Prints character on Lcd at specified position Both variables and literals can be passed as character Parameters row writing position row number column Writing position column number out char character to be written Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routine LET Write character i at row 2 column 3 SPI Leds Chr 2 3 YE SPI Lcd8 Chr Cp idea li sub procedure SPI Lcd8 Chr CP dim out char as 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 A Write character e at current cursor position SPI Lcd8 Chr Cp e 481 MikroElektronika mikoBasic PRO for PIC32 SPI Lcd8 Cmd Rems NM OSS Lcd needs to be initialized for SPI communication see SPI Lcd8 Config rout
449. or example time needed for preprocessing compilation and linking used RAM and ROM space generated baud rate with error percentage etc 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 v Errors Warnings Hints Line Message No 1 133 1015 1010 134 133 1015 1010 134 139 1144 1144 1144 145 140 141 103 1 1 9 0 0 0 0 0 0 0 Double click the message line in the Message Window to highlight the line where the error was encountered Message Text mBPIC32 exe DBG pP32MX460F512L MSF Compilation Started Hint Compiling unit C Program Files Mikroel Hint Unit __Lib_Delays mbas has been reco Compiled Successfully Compilation Started Hint Compiling unit C Program Files Mikroel Hint Unit LCD mbas has been recompiled Compiled Successfully All files Compiled in 15 ms Used RX bytes 32 100 Free RX bytes Static RAM bytes 48 Dynamic RAM bytes Used ROM bytes 3356 1 Free ROM b Project Linked Successfully Linked in 219 ms Project LCD mbp32 completed
450. ort 80 GET method with pathnames will return the HTML main page s will return board status as text string tO t7 will toggle RDO to RD7 bit and return HTML main page all other requests return also HTML main page Copy Code To Clipboard program HTTP Demo Y 3k ok oe oe oe eoe oe oe oe oe oe oe oe oe oe oe oe eoe e 6 x6 AG KKK X B B AB BG B BG kot x RAM variables Y mE ehternet NIC pinout dim SPI Ethernet Rst as sbit at LATFO bit SPI Ethernet CS as sbit at LATF1 bit MikroElektronika 430 mikroBasic PRO for PIC32 SPI SPI i Ethernet Rst Direction as sbit at TRISFO bit Ethernet CS Direction as sbit at TRISF1 bit end ethernet NIC definitions dim myMacAddr Y Y myIpAddr gwlIpAddr ipMask dnsIpAddr as byte 6 my MAC address as byte 4 my IP address as byte 4 gateway router IP address as byte 4 network mask for example 255 255 255 0 as byte 4 DNS server IP address 3k oe oe eoe eoe oe eee oe oe eoe oe eoe eoe oe eoe eoe oe eoe eee eoe oe eoe eoe e ee e x R AB B A A BG BG BG Bx A AG xRG xA Xx ROM constant strings const httpHeader as string 31 HTTP 1 1 200 OK chr 10 Content type HTTP header const httpMimeTypeHTML as string 13 text html chr 10 chr 10 HTML MIME type const httpMimeTypeScript as string 14 text plain tchr 10 chr 10 TEXT MIME type const
451. ou to have identical representation of UART library for both MCUs in Library Manager Related topics Library Manager Project Manager Managing Source Files mikroBasic PRO for PIC32 Frequently Asked Questions This is a list of frequently asked questions about using mikroElektronika compilers If your question is not answered on this page please contact mikroElektronika Support Desk Can use your compilers and programmer on Windows Vista Windows 7 Our compilers and programmer software are developed to work on and tested on Windows 98 Windows 2000 Windows ME Windows XP 32 and 64 bit Windows Vista 32 and 64 bit and Windows 7 32 and 64 bit and they work fine on these operating systems You can find the latest drivers on our website am getting Access is denied error in Vista how to solve this problem Please turn off User Account Control UAC This should make your software fully functional To do this follow the path in your Windows Vista logged in as administrator Control Panel User Accounts Turn User Account Control on or off uncheck Use User Account Control UAC and click OK What are differences between mikrobasic PRO mikroPascal PRO and mikroC 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
452. outine 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 dim buffer as string 16 buffer mikroElektronika SPI Ethernet 245 600 putString buffer put a RAM string into ENC24J600 buffer SPI Ethernet 24j600 putConstString Prototype sub function SPI Ethernet 243600 putConstString const ptr as byte as word Description This is MAC module routine It stores whole const string excluding null termination into ENC247600 RAM starting from current ENC247600 write pointer EWRPT location Parameters ptr const string to be written into ENC247600 RAM Number of bytes written into ENC247600 RAM Requires Ethernet module has to be initialized See SPI Ethernet 24j600 Init const buffer as string 16 buffer mikroElektronika SPI Ethernet 243600 putConstString buffer put a const string into ENC24J600 buffer SPI Ethernet 24j600 getByte Prototype sub function SPI Ethernet 243600 getByte as 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 modul
453. 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 Te963c Trigonometry MikroElektronika 508 mikroBasic PRO for PIC32 External dependencies of T6963C Graphic Lcd Library The following variables must be defined in all projects using T6963C Description Graphic Lcd library dim T6963C dataPort as byte sfr T6963C Data Port dim T6963C dataPort as byte at external PORTB dim T6963C ctrlwr as sbit sfr A dim T6963C ctrlwr as sbit at Write signal E far S external Be DIE dim T6963C ctrlrd as sbit sfr i T6963C ctrlrd as sbit at Read signal NE external EL bit dim T6963C ctrlcd as sbit sfr i T6963C ctrlcd as sbit at Command Data signal ML external FO bit dim T6963C ctrlrst as sbit sfr im T6963C ctrlrst as sbit at Reset signal o Rr quM external FA bit dim T6963C ctrlwr Direction as Direction of the Write pin i L6963C ctrlwr Direction as sbit sfr external Loi epin 7 E2 Dit dim T76963C ctrlrd Direction as Directi fth amp Read pi i lrd Direction as sbit sfr
454. param2 as byte dim param3 as word as word First define the procedural type dim MyPtr as TMyFunctionType This is a pointer to previously defined type dim sample as word sub function Func1 dim pl p2 as byte dim p3 as word as word Now define few functions which will be pointed to Make sure that parameters match the type definition result pl and p2 or p3 end sub sub function Func2 dim abc def as byte dim ghi as word as word Another function of the same kind Make sure that parameters match the type definition result abc def ghi end sub sub function Func3 dim first yellow as byte dim monday as word as word Yet another function Make sure that parameters match the type definition result monday yellow first end sub main program main MyPtr Funcl MyPtr now points to Funcl MikroElektronika 206 mikroBasic PRO for PIC32 Sample MyPtr 1 2 3 Y Perform function call via pointer call Funcl the return value is 3 MyPtr Func2 v 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 O0 end Operator The operator constructs a pointer to its operand The following rules are applied to 6 If x is a variable amp x returns a pointer to x Note If variable x is of arr
455. parate source code module 193 MikroElektronika mikoBasic PRO for PIC32 For example lets create a project which will calculate circle area and will have sub function and sub procedure definition in two different modules and a call to these routines in the third separate module So the project will be consisted of the main module Main Module mpas and First Module mpas and Second _ Module mpas modules In the Main Module we will define routine called r squared calculates radius squared Also both modules must be included in the Main Module program Main Module include First Module include Second Module Include both used modules sub function r square dim r as float as float Definition of the r square routine result r r end sub main CircleArea CircleArea routine call end end In the First Module we will define and declare routine called pi x squared calculates pi multiplied by the radius squared module First Module sub procedure pi r square dim rr as float Declaration of the pi r square routine implements sub procedure pi r square dim rr as float Definition of the pi r square routine dim res as float res rr 3 14 end sub end In the Second Module 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 module Second Module su
456. part will match as that is the first alternative tried and it successfully matches the target string this might not seem important but it is important when you are capturing matched text using parentheses Also remember that is interpreted as a literal within square brackets so if you write bit bat bot you re really only matching biao Examples rou tine te matches strings routine or route Metacharacters Subexpressions The bracketing construct may also be used for define regular subexpressions Subexpressions are numbered based on the left to right order of their opening parenthesis The first subexpression has number 1 Examples int 8 10 matches strings which contain 8 9 or 10 instances of the int routi 0 9 a e matches routi0e routile routine routinne routinnne etc Metacharacters Backreferences Metacharacters 1 through 9 are interpreted as backreferences matches previously matched subexpression Examples N11 matches aaaa and cc 1 matches abab and 123123 d 1 matches 13 in double quotes or 4 in single quotes or 77 without quotes etc MikroElektronika 108 mikroBasic PRO for PIC32 Keyboard Shortcuts Below is a complete list of keyboard shortcuts available in mikroBasic PRO for PIC32 IDE Fi z Shift F3 Alt F3 Ctrl A Ctrl C Ctrl F Ctrl R Ctrl
457. pe sub procedure Expander Set PullUpsPortA dim ModuleAddress Data as byte Description The function sets Port Expander s PortA pull up down resistors Parameters ModulcAddress Port Expander hardware address see schematic at the bottom of this page Data data for choosing pull up down resistors configuration Each bit corresponds to the appropriate pin of the PortA register Set bit enables pull up for corresponding pin Nothing Port Expander must be initialized See Expander Init Set Port Expander s PORTA pull up resistors Expander Set PullUpsPortA 0 SFF Notes None OOOO MikroElektronika 364 mikroBasic PRO for PIC32 Expander Set PullUpsPortB Prototype sub procedure Expander Set PullUpsPortB dim ModuleAddress Data as 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 Init Set Port Expander s PORTB pull up resistors Expander Set PullUpsPortB 0 OxFF Expander Set PullUpsPortAB Prototype sub procedure Expander Set PullUpsPortAB dim ModuleAddress as byte dim PullUps as word The function sets Port Expander s PortA and PortB pull up dow
458. pin direction as Direction of the RS 485 Transmit dim RS485 rxtx pin direction as sbit Sbit sfr external Receive pin at TRISF2 bit 371 MikroElektronika mikoBasic PRO for PIC32 Library Routines RS485Master Init RS485Master Receive RS8485Master Send RS485Slave Init RS485Slave Receive RS485Slave Send RS485Master Init Rems Nothing OOOO O Requires Global variables RS485 rxtx pin this pin is connected to RE DE input of RS 485 transceiver see schematic at the bottom of this page RE DE signal controls RS 485 transceiver operation mode RS485 rxtx pin direction direction of the RS 485 Transmit Receive pin must be defined before using this routine UART HW module needs to be initialized See UARTx Init RS485 module pinout dim RS485 rxtx pin as sbit at RF2 bit dim RS485 rxtx pin direction as sbit at TRISF2 bit End of RS485 module pinout UART1 Init 9600 initialize UART1 module RS485Master Inat intialize MCU as a Master for RS 485 communication MikroElektronika 378 mikroBasic PRO for PIC32 RS485Master Receive Prototype sub procedure RS485Master Receive dim byref data as byte 10 Description Receives 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 0 2 message content data bu
459. play Cursor Prototype sub procedure S1D13700 Display Cursor dim mode as byte Description Displays cursor Parameters mode mode parameter Valid values Glcd module needs to be initialized See the S1D13700 Init routine set cursor on 1D13700 Display Cursor S1D13700 CURSOR ON S1D13700 Write Char Prototype sub procedure S1D13700 Write Char dim c as char dim x as word dim y as word dim mode as 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 SIDIJJG0 OVERLAY XOR In this mode the text and graphics data are combined via the logical exclusive OR S1013200 OVERLAY AND The text and graphic data shown on display are combined via the logical AND function S1D13700 OVERLAY OR Glcd module needs to be initialized See the S1D13700 Init routine TUE S1D13700 Write Char A 22 23 S1D13700 OVERLAY OR MikroElektronika 286 mikroBasic PRO for PIC32 S1D13700 Write Text Prototype sub procedure S1D13700 Write Text dim byref str as string dim x y as word dim mode as byte Description Writes text
460. pos y coordinate of horizontal line Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the line color 0 white 1 black and 2 inverts each dot Nothing Requires Glcd needs to be initialized see Glcd Init routine Draw a horizontal line between dots 10 20 and 50 20 Glcd H Line 10 50 20 1 None 303 MikroElektronika mikoBasic PRO for PIC32 Glcd Rectangle Prototype sub procedure Glcd Rectangle dim x upper left y upper left x bottom right y bottom right color as 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 see Glcd Init routine Draw a rectangle between dots 5 5 and 40 40 Glcd Rectangle 5 5 40 40 1 Glcd Rectangle Round Edges Prototype sub procedure Glcd Rectangle Round Edges dim x upper left as byte dim y upper left as byte dim x bottom right as byte dim y bottom right as byte dim radius as byte dim color as byte
461. project Managing Source Files Creating new source file To create a new source file do the following 1 Select File New Unit from the drop down menu or press Ctrl N or click the New File Icon 3 from the File Toolbar LLL 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 H from the File Toolbar and name it as you want If you use the New Project Wizard an empty source file named after the project with extension mbas will be created automatically The mikroBasic PRO for PIC32 does not require you to have a source file named the same as the project it s just a matter of convenience Opening an existing file 1 Select File Open from the drop down menu or press Ctrl O or click the Open File Icon x from the File Pre Toolbar In Open Dialog browse to the location of the file that you want to open select it and click the Open button 2 The selected file is displayed in its own tab If the selected file is already open its current Editor tab will become active Printing an open file 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
462. ption 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 51013700 thage inage 0 T MikroElektronika 292 mikroBasic PRO for PIC32 S1D13700 Partiallmage Prototype sub procedure 351D13700 Partiallmage dim x left y top width height picture width picture height as word dim image as const byte Nothing Description Displays a partial area of the image on a desired location Parameters x left x coordinate of the desired location upper left coordinate y top y coordinate of the desired location upper left coordinate width desired image width height desired image height picture width width of the original image picture height height of the original image image image to be displayed Bitmap array is located in code memory Note Image dimension must match the display dimension Glcd module needs to be initialized See the S1D13700 Init routine Draws a 10x15 part of the image starting from the upper left corner on the coordinate 10 12 Original image size is 16x32 51013700 PartialImage 10 12 10 15 16 32 G8 image 293 MikroElektronika mikoBasic PRO for PIC32 Flash Memory Library This library provides routines for accessing microcontroller s internal Flash memo
463. r 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 symbols and appear automatically Use the folding symbols to hide unhide the code subsections PORTA 0 PORTB 0 Led_Init LCD Out 1 1 txt 0 LCD Out 2 1 txt 1 delay_ms 1000 Lcd Cmd 1 LCD Out 1 1 txt 1 LCD Out 2 4 txt 2 delay ms 500 end begin E 51 MikroElektronika mikoBasic PRO for PIC32 Another way of folding unfolding code subsections is by using Alt and Alt If you place a mouse cursor over the tooltip box the collapsed text will be shown in a tooltip style box begin begin i PORTA 0 PORTB 0 Lcd Init LCD Out 1 1 txt 0 LCD Out 2 1 txt 1 delay ms 1000 Lcd Cmd 1 LCD Out i 1 txt 1 LCD_Out 2 4 txt 2 delay_ms S00 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 aR variable sfr SPDR byte variab
464. r countelkjdflkj9r but not countr count r matches strings like counter countar and countr but not countelkj9r counte 2 r matches string counteer counte 2 r matches strings like counteer counteeer counteeer etc counte 2 3 r matches strings like counteer or counteeer but not counteeeer A little explanation about greediness Greedy takes as many as possible non greedy takes as few as possible For example b and b applied to string abbbbc return bbbb b returns b b returns empty string b 2 3 returns bb b 2 3 returns bbb Metacharacters Alternatives You can specify a series 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
465. r CP character i next i Lcd Cmd LCD RETURN HOME Lcd Chr pos row pos char 0 end sub eic 91 MikroElektronika mikoBasic PRO for PIC32 Seven Segment Editor The Seven Segment Editor is a convenient visual panel which returns decimal hex value for any viable combination you would like to display on seven segment display Click on the parts of seven segment image to get the requested value in the edit boxes You can launch it from the drop down menu Tools Seven Segment Editor or by clicking the Seven Segment Editor Icon min from Tools toolbar Seven Segment Editor Common cathode 113 Com i UDP Terminal The mikroBasic PRO for PIC32 includes the UDP Terminal You can launch it from the drop down menu Tools UDP Terminal MikroElektronika UDP Terminal Settings IP Address 192 168 020 025 Port 10001 u Send mikroElektronika Append CR Send as typing FE Send as number mikroElektronika mikroElektronika MikroElektronika 92 mikroBasic PRO for PIC32 USART Terminal The mikroBasic PRO for PIC32 includes the USART communication terminal for RS232 communication You can launch it from the drop down menu Tools USART Terminal or by clicking the USART Terminal Icon ill from Tools toolbar Send mikroElektronika Send Repeat sending Support ASCH Append Newline 6518 Sendasci Repeat sending every F Send as typing
466. r CP dim Out Char as byte Prints character on Lcd at current cursor position Both variables and literals can be passed as character Out Char character to be written Lcd needs to be initialized for SPI communication see SPI Lcd Config routine Write character e at current cursor position SPI Lcd Chr Cp e None 475 MikroElektronika mikoBasic PRO for PIC32 SPI Lcd Cmd Reums NM SOS Lcd needs to be initialized for SPI communication see SPI 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 SPI Lcd Command dh Purpose LCD FIRST ROW Move cursor to the 1st row LCD RETURN HOME Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected MikroElektronika 416 mikroBasic PRO for PIC32 Library Example Default Pin Configuration Use SPI Lcd Init for default pin settings see the first figure below Copy Code To Clipboard program Spi Lcd dim text as char 16 dim counter as byte Port Expander module connections dim SPExpanderRST as sbit at LATD8 bit dim SPExpanderCS as sbit at LATD9 bit dim SPExpanderRST Direction as sbit at TRISD8 bit dim SPExpanderCS Direction as sbit at TRISD9 bit End Port Expander module connections sub procedu
467. r address S1D13700 Write Parameter Hi start send higher byte cursor address S1D13700 Read Parameter Remum Nothing SSS Example rarameter 51013700 Read Paranerer0 OOSOSOSCSC S S1D13700 Fill Prototype sub procedure S1D13700 Fill dim d as byte dim start as word dim len as 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 S1D13700 Fill 0x20 0x3000 Ox7FEF 283 MikroElektronika mikoBasic PRO for PIC32 S1D13700 GrFill Prototype sub procedure 51D13700 GrFill dim d as byte Description Fill graphic layer with appropriate value 0 to clear Parameters d value to fill graphic layer with Gled module needs to be initialized See the S1D13700 Init routine clear current graphic panel 1D13700 GrFill 0 S1D13700 TxtFill Prototype sub procedure S1D13700 TxtFill dim d as byte Description Fill current text panel with appropriate value 0 to clear Parameters d this value will be used to fill text panel Glcd module needs to be initialized See the S1D13700 Init routine clear current text panel S1D13700 TxtFill 0 S1D13700 Display GrLayer Prototype lt sub proced
468. r as byte as longword 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 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
469. r parameter Valid values 1 8 64 and 256 use timer x timer to be used with the PWM module Valid values 2 Timer2 and 3 Timer3 OxFFFF if timer settings are not valid otherwise returns calculated timer period MCU must have the HW PWM Module Notes Number of available PWM channels depends on MCU Refer to MCU datasheet for details 313 MikroElektronika mikoBasic PRO for PIC32 PWM Set Duty Prototype sub procedure PWM Set Duty dim duty channel as word The function changes PWM duty ratio Parameters duty PWM duty ratio Valid values 0 to timer period returned by the PWM Init function channel number of PWM channel to change duty to Requires MCU must have the HW PWM Module PWM channel must be properly initialized See PWM Init routine Set channel 1 duty ratio to 50 dim pwm periodi as word PWM Set Duty pwm periodl div 2 1 Notes Number of available PWM channels depends on MCU Refer to MCU datasheet for details PWM Start Rems NM OOOO Requires MCU must have the HW PWM Module PWM channel must be properly configured See the PWM Init and PWM Set Duty routines start PWM at channel 1 PWM Start 1 Notes Number of available PWM channels depends on MCU Refer to MCU datasheet for details PWM Stop Rum Nothing OOS MCU must have the HW PWM Module stop PWM at channel 1 PWM Stop 1 Notes Number of available PWM channels depends
470. radient orientation gradient color from sets the starting gradient color 543 MikroElektronika mikoBasic PRO for PIC32 Description gradient color to sets the ending gradient color TFT module needs to be initialized See the TFT Init routine Enable gradient from black to white color left right orientation TFT Set Brush 0 0 1 LEFT TO RIGHT CL BLACK CL WHIT TFT Line Prototype sub procedure TFT Line dim x1 yl x2 y2 as integer Description Draws a line from x1 y1 to x2 y2 Parameters x1 X coordinate of the line start y1 y coordinate of the line end x2 X coordinate of the line start y2 y coordinate of the line end TFT module needs to be initialized See the TFT Init routine Example TFT Line 0 0 239 127 MikroElektronika 544 mikroBasic PRO for PIC32 TFT H Line Prototype sub procedure TFT H Line dim x start x end y pos as 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 l0 50 20 TFT V Line Prototype sub procedure TFT V Line dim y start y end x pos as integer Description Draws a vertical line on TFT Parameters y start y coordina
471. re Move Delay Function used for text moving Delay ms 500 i You can change the moving speed here end sub main text mikroElektronika CHECON 0x32 ADIPCFG OxFFFF Configure AN pins as digital If Port Expander Library uses SPI2 module Initialize SPI module used with PortExpander SPI2 Init Advanced SPI MASTER SPI 8 BIT 4 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE LOW SPI ACTIVE 2 IDLE Spi Lcd Config 0 Initialize LCD over SPI interface Spi Lcd Cmd LCD CLEAR Clear display Spi Lcd Cmd LCD CURSOR OFF Turn cursor off Y Y Y Spi Lcd Out 1 6 mikroE Print text to LCD 1st row 6th column Spi Lcd Chr CP Append I Spi Lcd Out 2 1 text Print text to LCD 2nd row 1st column Delay ms 2000 Spi Led Out 3 1 mikroE For LCD with more than two rows Spi Lcd Out 4 15 mikroE For LCD with more than two rows Moving text for counter 0 to 3 Move text to the right 4 times Spi Lcd Cmd LCD SHIFT RIGHT Move Delay next counter while TRUE Endless loop for counter 0 to 6 Move text to the left 7 times Spi Lcd Cmd LCD SHIFT LEFT Move Delay next counter for counter 0 to 6 Move text to the right 7 times Spi Lcd Cmd LCD SHIFT RIGHT Move Delay next counter wend end ATI MikroElektronika mikoBasic PRO for PIC32 OSCILLATOR PIC32MX460F512L ote w
472. re SPI Library The following variables must be defined in all projects using Software SPI Description Library external a external i SoftSpi CLK i 2 I aim ids im SA Sbi eip Clock line dim SoftSpi CLK as sbit at LATF6 bit external dim SoftSpi SDI Direction as Direction of the Data In pin dim SoftSpi SDI Direction as spit at sbit sfr external pin TRISF2 bit dim SoftSpi SDO Direction as An dim SoftSpi SDO Direction as sbit at sbit sfr external Direction ar ine Date Ouf pln TRISF3 bit dim SoftSpi CLK Direction as dim SoftSpi CIK Direction as sbit at sbit sfr external Direction ofthe Engels pim TRISF6 bit Library Routines Soft SPI Init Soft SPI Read Soft SPI Write 393 MikroElektronika mikoBasic PRO for PIC32 Soft SPI Init Rems NM S S Requires Global variables SoftSpi_SDI Data in line SoftSpi SDO Data out line SoftSpi CLK Data clock line SoftSpi SDI Direction Direction of the Data in pin SoftSpi SDO Direction Direction of the Data out pin SoftSpi CLK Direction Direction of the Data clock pin must be defined before using this function DAC module connections dim dim dim dim dim dim SoftSpi Cl SoftSpi SDI LK SoftSpi SDO SoftSpi C LK as sbit at LATF6 bit as sbit at RF2 bit as sbit at LATF3 bit Direction as sbit at TRISF6 bit SoftSpi SDI Direction as sbit at SoftSpi SDO Direction as sbit at End DAC module con
473. re processed in the following manner ARP amp ICMP requests are replied automatically upon TCP request the SPI Ethernet 24j600 UserTCP function is called for further processing upon UDP request the SPI Ethernet 24j600 UserUDP function is called for further processing Parameters None 0 upon successful packet processing zero packets received or received packet processed successfully 1 upon reception error or receive buffer corruption ENC24J600 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 24600 Init while TRUE Ethernet 243600 doPacket process received packets Ethernet 243600 doPacket must be called as often as possible in user s code SPI Ethernet 24j600 putByte Prototype sub procedure SPI Ethernet 24 600 putByte dim v as byte Description This is MAC module routine It stores one byte to address pointed by the current ENC247600 write pointer EWRPT Nothing Ethernet module has to be initialized See SPI Ethernet 24600 Init dim data as byte Ethernet 243600 putByte data put an byte into ENC24J600 buffer 445 MikroElektronika mikoBasic PRO for PIC32 SPI Ethernet 24j600 putBytes Prototype sub procedure SPI Ethernet 24
474. register when writing to ports rather than using PORTx registers Writing to a LATx register is equivalent to writing to a PORTx register but readings from LATx registers return the data value held in the port latch regardless of the state of the actual pin For example lets analyze the following example LATB BO 1 LATB B1 1 The first line LATB BO 1 will be decoded like in this way READ LATB is read STORE Data is stored inside a temporary internal register in the MCU OIUre reau 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 Write gpa pc modified value Discharged 0 l capacitor capacitor MikroElektronika 174 mikroBasic PRO for PIC32 The second line LATB B1 1 will be decoded like in this way READ LATB is read STORE Since the voltage levels on MCU pins are no longer relevant we get the expected value Store read Expected value value Read from LATB T e capacitor Actual voltage levels on MCU pins are no longer relevant when using LATx for output MODIFY Data is modified to set the bit WRITE LATB is written with the new data The Modify value output driver for RB1 turns on a
475. renewDHCP 458 SPI Graphic Lcd Library 459 Library Dependency Tree 459 External dependencies of SPI Lcd Library 459 Library Routines 459 SPI Glcd Init 460 SPI Glcd Set Side 461 SPI Glcd Set Page 461 SPI Glcd Set X 461 SPI Glcd Read Data 462 SPI Glcd Write Data 462 SPI Glcd Fill 463 SPI Glcd Dot 463 MikroElektronika 18 mikroBasic PRO for PIC32 SPI Glcd Line 464 SPI Glcd V Line 464 SPI Glcd H Line 465 SPI Glcd Rectangle 465 SPI Glcd Rectangle Round Edges 466 SPI Glcd Rectangle Round Edges Fill 466 SPI Glcd Box 467 SPI Glcd Circle 467 SPI Glcd Circle FIlI 468 SPI Glcd Set Font 469 SPI Glcd Write Char 470 SPI Glcd Write Text 470 SPI Glcd Image 471 SPI Glcd Partiallmage 471 Library Example 472 HW Connection 474 SPI Lcd Library 475 Library Dependency Tree 475 External dependencies of SPI Lcd Library 475 Library Routines 475 SPI Lcd Config 476 SPI Lcd Out 476 SPI Lcd Out Cp 477 SPI Lcd Chr 477 SPI Lcd Chr Cp 477 SPI Lcd Cmd 478 Available SPI Lcd Commands 478 Library Example 479 Default Pin Configuration 479 SPI Lcd8 8 bit interface Library 481 Library Dependency Tree 481 External dependencies of SPI Lcd Library 481 Library Routines 481 SPI Lcd8 Config 482 SPI Lcd8 Out 482 SPI Lcd8 Out Cp 483 SPI Lcd8 Chr 483 SPI Lcd8 Chr Cp 483 SPI Lcd8 Cmd 484 Available SPI Lcd8 Commands 484 Library Example 485 SPI T6963C Graphic Lcd Library 487 Library Dependency Tree 487 External dependencies of SPI T6963C Graphic Lcd Libra
476. reply txt var PORTD result result Spi Ethernet _putString txt WordToStr PORTD dyna result result Spi Ethernet _putString dyna txt y result result Spi Ethernet _putString txt add HTTP requests counter to reply WordToStr httpCounter dyna txt var REQ result result Spi Ethernet putString txt result result Spi Ethernet putString dyna txt WU result result Spi Ethernet putString txt else if getRequest 5 t then if request path name starts with t toggle PORTD LED bit number that comes after 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 bitMask getRequest 6 0 convert ASCII to integer bitMask 1 lt lt bitMask create bit mask PORTD PORTD xor bitMask toggle PORTD with xor operator end if end if end if if result 0 then what do to by default result SPI Ethernet putConstString httpHeader HTTP header result result SPI Ethernet putConstString 8httpMimeTypeHTML with HTML MIME type result result SPI Ethernet putConstString G8indexPage HTML page first part result result SPI Ethernet putConstString 8indexPage2 HTML page second part end if return to the library with the number of bytes to transmit end sub Y this function is called by the library the user accesses to the UDP request by successive
477. riable Wait for key to be pressed and released while kp 0 kp Keypad Key Click Store key code in kp variable wend Prepare value for output transform key to it s ASCII value select case kp i case 10 3 kp 42 Uncomment this block for keypad4x3 3 case 11 i kp 48 Y MZ b case 12 kp 35 g 3 case else kp kp 48 case 1 kp 49 1 Uncomment this block for keypad4x4 case 2 kp 50 2 case 3 kp 51 3 case 4 kp 65 A case 5 kp 52 4 MikroElektronika 318 mikroBasic PRO for PIC32 case 6 kp 53 5 case 7 kp 54 6 case 8 kp 66 B case 9 kp 55 7 case 10 kp 56 S8 case 11 kp 57 9 case 12 kp 67 C case 13 kp 42 case 14 kp 48 0 case 15 kp 35 t case 16 kp 68 D end select UART1 Write Text Key pressed UART1 Write kp Send value of pressed button to UART UART1 Write 10 UART1 Write 13 wend end HW Connection OSCILLATOR iD 4x4 Keypad connection scheme 319 MikroElektronika mikoBasic PRO for PIC32 Lcd Library mikroBasic PRO for PIC32 provides a library for communication with Lcds with HD44780 compliant controllers through the 4 bit interface An example of Lcd connections is given on the schematic at the bottom of this page For creating a set of custom Lcd characters use Lcd Custom Character Tool Library Depen
478. rite A3 Soft I2C Stop Requires Soft IC must be configured before using this function See Soft I2C Init routine Issue STOP signal Soft I2C 9top None 389 MikroElektronika mikoBasic PRO for PIC32 Soft I2C Break Prototype sub procedure Soft I2C Break Description All Software I C Library functions can block the program flow see note at the top of this page Calling this routine from interrupt will unblock the program execution This mechanism is similar to WDT dim datal error counter as byte sub procedure TimerlInt org IVT ADDR TIINTERRUPT counter 0 if counter 20 Soft I2C Break counter 0 reset counter else Inc counter increment counter end if TIIF bit Clear Timerl overflow interrupt flag end sub main try Soft I2C Init with blocking prevention mechanism IPCO IPCO or 0x1000 Interrupt priority level 1 TIIE bit 1 Enable Timerl interrupts T1CON 0x8030 Timerl ON internal clock FCY prescaler 1 256 Soft I2C Init TITE bit Disable Timerl interrupts end eee Interrupts should be disabled before using Software C routines again see note at the top of this page MikroElektronika 390 mikroBasic PRO for PIC32 Library Example The example demonstrates use of the Software I C Library The dPIC32 MCU is connected SCL SDA pins to PCF8583 RTC real time clock Program sends date time to RTC Copy Cod
479. rn Match Magic Packet and Hash Table can not be enabled by this routine Additionaly all filters except CRC enabled with this routine will work in OR mode which means that packet will be received if any of the enabled filters accepts it This routine will change receive filter configuration on the fly It will not in any way mess with enabling disabling receive transmit logic or any other part of the ENC28J60 module The ENC28360 module should be properly cofigured by the means of SPI Ethernet Init routine Parameters enF1t network traffic receive filter flags Each bit corresponds to the appropriate network traffic receive filter 0x01 MAC Broadcast traffic receive filter flag When set SPI Ethernet MAC broadcast traffic will be enabled BROADCAST MAC Multicast traffic receive filter flag When set SPI Ethernet MAC multicast traffic will be enabled MULTICAST CRC check flag When set packets with invalid i CRC field will be discarded MAC Unicast traffic receive filter flag When set 0x80 MAC unicast traffic will be enabled Nothing Ethernet module has to be initialized See SPI Ethernet Init SPI Ethernet Enable SPI Ethernet CRC or _ SPI Ethernet UNICAST enable CRC checking and Unicast traffic Advanced filtering available in the ENC28J60 module such as Pattern Match Magic Packet and Hash Table can not be enabled by this routine Additionaly all filters except CRC enabled with this rou
480. rnal dependencies of the Epson S1D13700 Graphic Lcd Library 281 Library Routines 282 S1D13700 Init 283 S1D13700 Write Command 284 S1D13700 Write Parameter 285 S1D13700 Read Parameter 285 S1D13700 Fill 285 S1D13700 GrFill 286 S1D13700 TxtFill 286 S1D13700 Display GrLayer 286 S1D13700 Display TxtLayer 287 S1D13700 Set Cursor 287 S1D13700 Display Cursor 288 S1D13700 Write Char 288 S1D13700 Write Text 289 S1D13700 Dot 289 S1D13700 Line 290 S1D13700 H Line 290 S1D13700 V Line 291 S1D13700 Rectangle 291 S1D13700 Box 292 S1D13700 Rectangle Round Edges 292 S1D13700 Rectangle Round Edges Fill 293 S1D13700 Circle 293 MikroElektronika 12 mikroBasic PRO for PIC32 S1D13700 Circle Fill 294 S1D13700 Image 294 S1D13700 Partiallmage 295 Flash Memory Library 296 Library Routines 296 Flash Write Word 297 Flash Write Row 297 Flash Erase Page 297 Graphic Lcd Library 298 Library Dependency Tree 298 External dependencies of Graphic Lcd Library 299 Glcd Init 300 Glcd Set Side 302 Glcd Set X 302 Glcd Set Page 302 Glcd Read Data 303 Glcd Write Data 303 Glcd Fill 304 Glcd Dot 304 Glcd Line 304 Glcd V Line 305 Glcd H Line 305 Glcd Rectangle 306 Glcd Rectangle Round Edges 306 Glcd Rectangle Round Edges Fill 307 Glcd Box 307 Glcd Circle 308 Glcd Circle Fill 308 Glcd Set Font 309 Glcd Write Char 310 Glcd Write Text 310 Glcd Image 311 Glcd Partiallmage 311 I C Library 312 Library Routines 312 I2Cx Init 312 I2Cx Init Advanced 313 I
481. rnet 24j600 getGwlpAddress Prototype sub function SPI Ethernet 243600 getGwIpAddress as word Description This routine should be used when DHCP server is present on the network to fetch assigned gateway IP address Pointer to the global variable holding gateway IP address Requires Ethernet module has to be initialized See SPI Ethernet 24j600 Init di gwlpAddr as byte 4 user gateway IP address buffer memcpy gwIpAddr SPI Ethernet 243600 getGwIpAddress 4 fetch gateway IP address User should always copy the IP address from the RAM location returned by this routine into it s own gateway IP address buffer These locations should not be altered by the user in any case SPI Ethernet 24j600 getDnslpAddress Prototype Prototype sub function SPI Ethernet sub function SPI _Ethernet_24 600_getDnsIpAddress as word _getDnsIpAddress sub function SPI _Ethernet_24 600_getDnsIpAddress as word word 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 cr dnsIpAddr as byte 4 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 loca
482. roBasic PRO for PIC32 Library Routines TFT Init TFT Set Index TFT Write Command TFT Write Data TFT Set Active TFT Set Font TFT Write Char TFT Write Text TFT Fill Screen TFT Set Pen TFT Set Brush TFT Dot TFT Line TFT H Line TFT V Line TFT Rectangle TFT Rectangle Round Edges TFT Circle TFT Image TFT Partiallmage TFT Image Jpeg TFT RGBToColor16bit TFT Color16bitTOoRGB 533 MikroElektronika mikoBasic PRO for PIC32 TFT Init Prototype sub procedure TFT Init dim display width display height as word 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 TFT DataPort Data Port TFT WR Write signal pin TFT RD Read signal pin TFT CS Chip Select signal pin TFT RS Register Select signal pin TFT RST Reset signal pin TFT DataPort Direction Direction of Data Port TFT WR Direction Direction of Write signal pin FT RD Direction Direction of Read signal pin FT CS Direction Direction of Chip Select signal pin CFT RS Direction Direction of Register Select signal pin TFT RST Direction Direction of Reset signal pin must be defined before using this function TFT display connections dim TFT DataPort as byte at LATE dim TFT WR as sbit at LATD13 bit dim l RD as sbit at LATD12 bit dim CS as s
483. roject should be entered By default currently active project will be set for export You can change it any time by clicking the Open Button i 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 Project successfully exported You have successfully exported the project All Files From the project are now copied to D Project Now Export Project has copied all project files into desired folder and changed project search paths so you can easily move the entire folder to another location and run the project 103 MikroElektronika mikoBasic PRO for PIC32 Jump To Interrupt Lets you choose which interrupt you want to jump to Requirement Interrupt routine is included in project You can call Jump To Interrupt by selecting Run gt Jump To Interrupt from the drop down menu or by clicking the Jump To Interrupt Icon fu from the Watch Values Window Available Interrupts Ox0000 IVT CORE TIMER VECTOR 0x0001 IVT CORE SOFTWARE 0 VECTOR 0x0002 IVT CORE SOFTWARE 1 VECTOR 0x0003 IVT EXTERNAL 0 VECTOR 0x0004 IVT TIMER 1 VECTOR 0x0005 IVT INPUT CAPTURE 1 VECTOR 0x0006 IT OUTPUT COMPARE 1 VECTOR 0x0007 IVT EXTERNAL 1 VECTOR 0x0008 IVT TIMER 2 VECTOR 0x0009 IVT INPUT CAPTURE 2 VECTOR 0x000A IVT OUTPUT COMPARE 2 VECTOR 0x000B IVT EXT
484. rwise it returns 0 mr 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 The 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 because 1234 0001 V 5678 gt QI01 3 and 0001 vw Chat We m Similarly 1234 or 5678 1234 xor 5678 not 1234 equals 1230 0010 0011 0100 0110 0111 1000 0010 0011 0000 1230 equals 567C equals 444C equals SEDCB MikroElektronika 218 mikroBasic PRO for PIC32 Unsigned and Conversions If a number is converted from less complex to more complex data type the upper bytes are filled with zeroes If a number is converted from more complex to less complex data type the data is simply truncated the upper bytes are lost For example dim a as byte dim b as word h SAA SFOFO banda a is extended with zeroes b becomes 00A0 sT OM ll Signed and Conversions If number is converted from less complex to more complex data type the upper bytes are filled with ones if sign bit is 1 number is negative
485. ry The program Flash array for the PIC32MX device is built up of a series of rows A row contains 128 32 bit instruction words or 512 bytes A group of 8 rows compose a page which therefore contains 8 1512 4096 bytes or 1024 instruction words A page of Flash is the smallest unit of memory that can be erased at a single time The program Flash array can be programmed in one of two ways Row programming with 128 instruction words at a time Word programming with 1 instruction word at a time The CPU stalls waits until the programming operation is finished The CPU will not execute any instruction or respond to interrupts during this time If any interrupts occur during the programming cycle they remain pending until the cycle completes Library Routines Flash Write Word Flash Write Row Flash Erase Page MikroElektronika 294 mikroBasic PRO for PIC32 Flash Write Word Prototype sub procedure FLASH Erase32 dim flash address as longint Description Writes one 32 bit word in the program Flash memory on the designated address Parameters address address of the FLASH memory word wdata data to be written Nothing Requires Nothing Flash Write Row Prototype sub procedure FLASH Write Block dim flash address as longint dim data address as word Description Writes one row in the program Flash memory 128 32 bit words or 512 bytes on the designated address Parameters address ad
486. ry 487 Library Routines 488 SPI T6963C config 489 19 MikroElektronika mikoBasic PRO for PIC32 SPI T6963C writeData 490 SPI T6963C writeCommand 490 SPI T6963C setPtr 491 SPI T6963C waitReady 491 SPI T6963C fill 491 SPI T6963C dot 492 SPI T6963C write char 492 SPI T6963C write text 493 SPI T6963C line 494 SPI T6963C rectangle 494 SPI T6963C rectangle round edges 495 SPI T6963C rectangle round edges fill 495 SPI T6963C box 496 SPI T6963C circle 496 SPI T6963C circle fill 496 SPI T6963C image 497 SPI T6963C Partiallmage 497 SPI T6963C sprite 498 SPI T6963C set cursor 498 SPI T6963C clearBit 498 SPI T6963C setBit 499 SPI T6963C negBit 499 SPI T6963C displayGrPanel 499 SPI T6963C displayTxtPanel 500 SPI T6963C setGrPanel 500 SPI T6963C setTxtPanel 500 SPI T6963C panelFill 501 SPI T6963C grFill 501 SPI T6963C txtFill 501 SPI T6963C cursor height 502 SPI T6963C graphics 502 SPI T6963C text 502 SPI T6963C cursor 503 SPI T6963C cursor blink 503 Library Example 503 HW Connection 509 T6963C Graphic Lcd Library 510 Library Dependency Tree 510 External dependencies of T6963C Graphic Lcd Library 511 Library Routines 512 T6963C init 513 T6963C writeData 514 T6963C writeCommand 515 T6963C setPtr 515 T6963C waitReady 515 T6963C fill 516 T6963C dot 516 MikroElektronika 20 mikroBasic PRO for PIC32 T6963C write char 517 T6963C write text 518 T6963C line 518 T6963C rectangle 519 T6963C rectangle round edges 519 T
487. ry 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 213 MikroElektronika mikoBasic PRO for PIC32 Copy Code To Clipboard program CF Fatl6 Test dim set compact flash pinout Cf Data Port as byte at PORTE CF RDY as sbit at RD7 bit CF WE as sbit at LATD6 bit CF OE as sbit at LATD5 bit CF CD1 as sbit at RD4 bit CF CE1 as sbit at LATD3 bit CF A2 as sbit at LATD2 bit CF Al as sbit at LATD1 bit CF AO as sbit at LATDO bit CF RDY direction as sbit at TRISD7 bit CF WE direction as sbit at TRISD6 bit CF OE direction as sbit at TRISD5 bit CF CD1 direction as sbit at TRISD4 bit CF CE1 direction as sbit at TRISD3 bit CF A2 direction as sbit at TRISD2 bit CF Al direction as sbit at TRISD1 bit CF A0 direction as sbit at TRISDO bit eof compact flash pinout const LINE LEN 37 dim i err txt as string 20 file contents as string LINE LEN filename as string 14 File names character as byt
488. s PortA Parameters ModulecAddress Port Expander hardware address see schematic at the bottom of this page bata data to be written Nothing Requires Port Expander must be initialized See Expander Init Port Expander s PortA should be configured as output See Expander Set DirectionPortA and Expander Set DirectionPortAB routines Write a byte to Port Expander s PORTA Expander Set DirectionPortA 0 00 set expander s porta to be output Expander Write PortA 0 SAA Expander Write PortB POMPE sub procedure Expander Write PortB dim ModuleAddress Data as byte The function writes byte to Port Expander s PortB Parameters ModulecAddress Port Expander hardware address see schematic at the bottom of this page bata data to be written Requires Port Expander must be initialized See Expander Init Port Expander s PortB should be configured as output See Expander Set DirectionPortB and Expander Set DirectionPortAB routines Write a byte to Port Expander s PORTB Expander Set DirectionPortB 0 500 set expander s portb to be output Expander Write PortB 0 55 MikroElektronika 362 mikroBasic PRO for PIC32 Expander Write PortAB Prototype Description Parameters Requires Expander Prototype Description Parameters sub procedure Expander Write PortAB dim ModuleAddress as byte dim Data as word The function writes word to Port Expander s ports M
489. s are available Dem Description Add Search Path Remove Search Path ca Purge Invalid Paths Paths for Source Files mbas You can specify either absolute or relative path to the source file If you specify a relative path mikroBasic PRO for PIC32 will look for the file in following locations in this particular order 1 the project folder folder which contains the project file mbp32 2 your custom search paths 3 mikroBasic PRO for PIC32 installation folder Uses folder Related topics File Menu File Toolbar Project Manager Project Settings mikroBasic PRO for PIC32 Edit Project Edit Project gives you option to change MCU you wish to use change its oscillator frequency and build type Also Edit Project enables you to alter specific configuration bits of the selected device As you alter these bits appropriate register values will be updated also This can be viewed in the Configuration Registers pane When you have finished configuring your device you can save bit configuration as a scheme using Save scheme button In case you need this scheme in another project you can load it using Load Scheme button There is also a Default button which lets you select default configuration bit settings for the selected device Edit Project PLL Input Divider 2x Divider PLL Multiplier MCU Name P32MX460F512L MCU and Oscillator 20x Multiplier USB PLL Input Divider 12x
490. s 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 misapplication Any replacement of Software will be warranted for the rest of the original warranty period or thirty 30 days whichever is longer TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW MIKROELEKTRONIKA ASSOCIATES AND ITS SUPPLIERS DISCLAIM ALL OTHER WARRANTIES AND CONDITIONS EITHER EXPRESSED OR IMPLIED INCLUDED BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY FITNESS FORA PARTICULAR PURPOSE TITLE AND NON INFRINGEMENT WITH REGARD TO SOFTWARE AND THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES MikroElektronika 30 mikroBasic PRO for PIC32 IN NO EVENT SHALL MIKROELEKTRONIKA ASSOCIATES OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL INCIDENTAL INDIRECT OR CONSEQUENTIAL DAMAGES WHATSOEVER INCLUDING WITHOUT LIMITATION DAMAGES FOR LOSS OF BUS
491. s loop If RBO button is pressed increment value If RB1 button is pressed 1 decrement value Send value to DAC chip Slow down key repeat pac MikroElektronika mikroBasic PRO for PIC32 Software UART Library mikroBasic PRO for PIC32 provides library which implements Software UART communication These routines are hardware independent and can be used with any MCU The Software UART Library provides easy communication with other devices via the RS232 protocol Important The Software UART library implements time based activities so interrupts need to be disabled when using it Library Routines Soft UART Init Soft UART Read Soft UART Write Soft UART Break Soft UART Init Prototype sub function Soft UART Init dim byref port as word dim rx tx as word dim baud rate as longword dim inverted as word 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
492. s 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 MIKRO007 TXT O0xAO0 Long File Names LFN are not supported 343 MikroElektronika mikoBasic PRO for PIC32 Mmc Fat Reset EUOU pR sub procedure Mmc Fat Reset dim byref size as longword 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 dim size as longword Mmc _ Fat Reset size Mmc_Fat_Read Prototype sub procedure Mmc Fat Read dim byref bdata as 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
493. s to be initialized See the T6963C init routine clear current graphic panel T6963C grFiil 0 None T6963C txtFill Rems Noting OOOO SS me o o a T6963C txtFill 0 T6963C cursor height Prototype sub procedure T6963C_ cursor height dim n as word Parameters n cursor height Valid values 0 7 Rems Noting SSCS Example re963c cursor neien O OOOO moss fne OOS 523 MikroElektronika mikoBasic PRO for PIC32 T6963C graphics Prototype sub procedure T6963C graphics dim n as word Enable disable graphic displaying Parameters n graphic enable disable parameter Valid values 0 disable graphic dispaying and 1 enable graphic displaying Toshiba Glcd module needs to be initialized See the T6963C init routine enable graphic displaying T6963C graphics 1 T6963C text n on off parameter Valid values 0 disable text displaying and 1 enable text displaying ems Ning Cd enable text displaying T6963C text 1 T6963C cursor Prototype sub procedure 76963C cursor dim n as word Set cursor 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 MikroElektronika 524 mikroBasic PRO for PIC32 T6963C cursor blink Prototype sub procedure 76963C cursor blink dim n as word Enable disable cursor blinking P
494. 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 dim data as byte 512 Cf Write Sector 22 data 265 MikroElektronika mikoBasic PRO for PIC32 Cf Fat Init Prototype sub function Cf Fat Init as word Initializes CF card reads CF FAT16 boot sector and extracts necessary data needed by the library 0 if CF card was detected and successfully initialized 1 if FAT16 boot sector was not found 255 if card was not detected init the FAT library if Cf Fat Init 0 then end if Cf Fat QuickFormat Prototype sub function Cf Fat QuickFormat dim byref cf fat label as string 11 as word Formats to FAT16 and initializes CF card Parameters cf fat label volume label 11 characters in length If less than 11 characters are provided the label will be padded with spaces If null string is passed the volume will not be labeled 0 if CF card was detected successfully formated and initialized 1 if FAT16 format was unsuccessful 255 if card was not detected format and initialize the FAT library if Cf Fat QuickFormat mikroE 0 then end if 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 on
495. shiba Glcd module needs to be initialized See SPI T6963C Config routine EB I7 SPI T6963C write text GLCD LIBRARY Di 0 0 SPI T6963C ROM MODE XOR 491 MikroElektronika mikoBasic PRO for PIC32 SPI T6963C line Prototype sub procedure SPI T6963C line dim x0 y0 xl yl as integer dim pcolor as byte Draws a line from x0 y0 to x1 y1 Parameters x0 x coordinate of the line start y0 y coordinate of the line end x1 x coordinate of the line start yl y coordinate of the line end pcolor color parameter Valid values SPI T6963C BLACK and SPI_T6963C_WHITE es Reg RR Example SPI_T6963C_line 0 0 239 127 SPI 769630 WHITE a he 5 o EE SPI T6963C rectangle Prototype sub procedure SPI T6963C rectangle dim x0 y0 xl yl as integer dim pcolor as byte Draws a rectangle on Glcd Parameters x0 x coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine ETT SPI T6963C rectangle 20 20 219 107 SPI T6963C WHITE Notes Nme SSS MikroElektronika 492 mikroBasic PRO for PIC32 SPI T6963C rectangle round edges Prototype sub procedure SP
496. sic PRO for PIC32 SPI Ethernet getDnslpAddress Prototype sub function SPI Ethernet getDnsIpAddress as word Description This routine should be used when DHCP server is present on the network to fetch assigned DNS IP address Pointer to the global variable holding DNS IP address Ethernet module has to be initialized See SPI Ethernet Init di dnsIpAddr as byte 4 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 Prototype Prototype sub function SPI Ethernet getIpMask as wrd function SPI Ethernet sub function SPI Ethernet getIpMask as word sd as word 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 dim IpMask as byte 4 user IP subnet mask buffer memcpy IpMask SPI Ethernet _getIpMask 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
497. signed int x bottom right unsigned int y bottom right unsigned short round radius unsigned short color 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 S1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine S1D13700 Rectangle Round Edges 20 20 219 107 12 S1D13700 WHITE MikroElektronika 290 mikroBasic PRO for PIC32 S1D13700 Rectangle Round Edges Fill Prototype sub procedure S1D13700 Rectangle Round Edges Fill dim x upper left as word dim y upper left as word dim x bottom right as word dim y bottom right as word dim round radius as word dim color as byte Description Draws a filled rounded edge rectangle on Glcd Parameters x upper left x coordinate of the upper left rectangle corner y upper left y coordinate of the upper left rectangle corner x bottom right x coordinate of the lower right rectangle corner y bottom right y coordinate of the lower right rectangle corner round radius radius of the rounded edge pcolor color parameter Valid values
498. ssign a group priority and group subpriority level to each of the interrupt vectors The user selectable priority levels range from 1 the lowest priority to 7 the highest If an interrupt priority is set to zero the interrupt vector is disabled for both interrupt and wake up purposes Interrupt vectors with a higher priority level preempt lower priority interrupts The subpriority will cause that when two interrupts with the same priority are pending the interrupt with the highest subpriority will be handled first The user selectable subpriority levels range from 0 the lowest subpriority to 3 the highest Interrupts and Register Sets The PIC32MX family of devices employs two register sets a primary register set for normal program execution and a shadow register set for highest priority interrupt processing Register Set Selection in Single Vector Mode In Single Vector mode you can select which register set will be used By default the interrupt controller will instruct the CPU to use the first register set This can be changed later in the code Interrupts and Register Sets When a priority level interrupt matches a shadow set priority the interrupt controller instructs the CPU to use the shadow set For all other interrupt priorities the interrupt controller instructs the CPU to use the primary register set Interrupt Coding Requirements In order to correctly utilize interrupts and correctly write the ISR code the user wil
499. st Lcd mbas Lib Math emcl Lib MathDouble emcl Lib System emcl Lib Delays mcl _ Lib LcdConsts emcl Lib Lcd emcl Specify input files wv MikroElektronika 112 mikroBasic PRO for PIC32 CHAPTER 4 Introduction The mikrolCD is a highly effective tool for a Real Time debugging on hardware level The mikrolCD debugger enables you to execute the mikroBasic PRO for PIC32 program on a host PIC32 microcontroller and view variable values Special Function Registers SFR RAM CODE and EEPROM memory along with the mikroICD code execution on hardware 113 MikroElektronika mikoBasic PRO for PIC32 Se 1 1 1 1 0 CC aAA If you have appropriate hardware and software for using the mikrolCD select mikrolCD Debug Build Type before compiling the project Project Settings Choose ICD Debuc type if you want to use mikroICD debug Build Type O Release ICD Debug Debugger Q Software mikroICD Now compile the project by pressing Ctrl F9 or by pressing Build Icon on Build Toolbar Se O2 11i o O C C OOOOO A NeOeOeOo D cCA X Run the mikrolCD by selecting Run gt Start Debugger from the drop down menu or by clicking the Start Debugger Icon IET Starting the Debugger makes more options available Step Into Step Over Run to Cursor etc Line that is to be executed is color highlighted blue by default There is also notification abou
500. stant 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 longword returns 4 sizeof float v 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 dim i j as integer samples as integer 7 sizeof samples 1 j sizeof integer 2 sizeof samples i l0 sizeof integer 20 H U e If the operand is a parameter declared as array type or function type sizeof gives the size of the pointer When applied to structures sizeof gives the total number of bytes including any padding The op
501. stretches image by a given factor if 2 it will double the image TFT module needs to be initialized See the TFT Init routine Draws a 10x15 part of the image starting from the upper left corner on the coordinate 10 12 TFT Partiallmage l10 12 10 Us amage 1 TFT Image Jpeg Prototype sub function TFT Image Jpeg dim left top as word dim image as far const ae as byte 0 if image is loaded and displayed successfully 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 Requires TFT module needs to be initialized See the TFT Init routine TFT Image Jpeg 0 0 image 547 MikroElektronika mikoBasic PRO for PIC32 TFT RGBToColor16bit Prototype sub function TFT RGBToColorl bit dim rgb red rgb green rgb blue as byte as word Retums Returns a color value in the following bit order 5 bits red 6 bits green and 5 bits blue color Description Converts 5 6 5 RGB format into true color format Parameters rgb red red component of the image rgb green green component of the image rgb blue blue component of the image TFT module needs to be initialized See the TFT Init routine Example colorl6 TFT Image Jpeg 150 193 65 TFT Color16bitTOoRGB Prototype sub procedure TFT Colorl6bit
502. sub procedures must have the same declarations in the interface and implementation section Otherwise compiler will report an error Scope and Visibility Scope Visibility Name Spaces Modules Include Clause Main Module Other Modules Interface Section Implementation Section Variables External Modifier Variables and PIC32 Constants Labels Symbols Functions and Procedures 192 192 192 192 193 193 193 194 194 195 195 195 195 197 197 198 198 199 MikroElektronika mikroBasic PRO for PIC32 Functions 199 Calling a function 199 Procedures 200 Forward declaration 201 Functions reentrancy 202 Types 203 Type Categories 203 Simple Types 203 Derived Types 204 Arrays 204 Array Declaration 204 Constant Arrays 204 Multi dimensional Arrays 205 Strings 205 String Concatenating 206 Pointers 207 Pointers and memory spaces 207 Function Pointers 208 Operator 209 Pointer Arithmetic 210 Assignment and Comparison 210 Pointer Addition 211 Pointer Subtraction 211 Structures 212 Structure Member Access 213 Types Conversions 214 Implicit Conversion 214 Explicit Conversion 215 Conversions Examples 215 Typedef Specifier 216 Type Qualifiers 216 Qualifier const 216 Qualifier volatile 217 Operators 217 Operators Precedence and Associativity 217 Arithmetic Operators 218 Arithmetic Operators Overview 218 Division by Zero 218 Unary Arithmetic Operators 218 Relational Operators 219 Relational Operators Overview 219
503. t categories of identifiers 1 Global variables are visible throughout the whole unit from the place of declaration Also they can be seen in other units if they are declared above the Implementation section 2 Local variables parameters types function results must be unique within the block in which they are declared For example dim level as byte sub procedure control dim sens as byte dim location as byte location 1 sens location level 123 end sub sub procedure temperature location 0 ILLEGAL sens 23 ILLEGAL redefinition of sens level 95 end sub Modules In mikroBasic PRO for PIC32 each project consists of a single project file and one or more module files The project file with extension mbp32 contains information on the project while modules with extension mbas contain the actual Source code See Program Organization for a detailed look at module arrangement Modules allow you to break large programs into encapsulated modules 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 module is stored in its own file and compiled separately compiled modules are linked to create an application To build a project the compiler needs either a source file or a compiled module file for each module Include Clause mikroBasic PRO for PIC32 includes modules by means
504. t as string Prints text on the Lcd starting from specified position Both string variables and literals can be passed as a text Parameters row starting position row number column Starting position column number text text to be written Lcd needs to be initialized for SPI communication see SPI Lcd Config routine Write text Hello on Lcd starting from row 1 column 3 SPI Lcd Out l 3 Hello MikroElektronika 474 mikroBasic PRO for PIC32 SPI Lcd Out Cp Prototype sub procedure SPI Lcd Out dim row column as byte dim byref text as string Prints text on the Lcd starting from specified position Both string variables and literals can be passed as a text text text to be written Lcd needs to be initialized for SPI communication see SPI Lcd Config routine Write text Here at current cursor position SPI Lcd Out CP He re None SPI Lcd Chr Prototype sub procedure SPI Lcd Chr dim Row Column Out Char as byte Description 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 Nothing Requires Lcd needs to be initialized for SPI communication see SPI Lcd Config routine ET Write character i at row 2 column 3 SPI Led Chr 2 3 i SPI Lcd Chr Cp Prototype sub procedure SPI Lcd Ch
505. t propagation 164 Copy propagation 164 Value numbering 164 Dead code ellimination 164 Stack allocation 164 Local vars optimization 164 Better code generation and local optimization 164 Single Static Assignment Optimization 165 Introduction 165 Proper Coding Recommendations 166 Asm code and SSA optimization 167 Debugging Notes 167 Warning Messages Enhancement 167 CHAPTER 7 168 PIC32 Specifics 168 Types Efficiency 169 Nested Calls Limitations 169 Variable constant and routine alignment 169 Boot Start up Initialization 169 PIC32 Memory Organization 170 PIC32MX Memory Layout 171 Virtual vs Physical Addresses 172 Memory Type Specifiers 173 code 173 data 173 rx 173 sfr 173 Read Modify Write Problem 174 CHAPTER 8 178 mikroBasic PRO for PIC32 Language Reference 178 Lexical Elements Overview 180 Whitespace 181 MikroElektronika 1 mikoBasic PRO for PIC32 Newline Character Whitespace in Strings Comments Tokens Token Extraction Example Literals Long and Unsigned Suffixes Floating Point Literals Character Literals String Literals Keywords Identifiers Case Sensitivity Uniqueness and Scope Identifier Examples Punctuators Brackets Parentheses Comma Colon Dot Program Organization Organization of Main Module Organization of Other Modules 181 181 182 182 182 183 183 183 184 184 185 187 187 188 188 188 188 189 189 189 189 190 190 191 192 Note Sub functions and
506. t the program execution and it can be found in the Watch Window yellow status bar Note that some functions take more time to execute execution is indicated with Running message in the Watch Window Status Bar Related topics mikrolCD Debugger Example Debug Windows Debugger Options MikroElektronika 114 mikroBasic PRO for PIC32 mikrolCD Debugger Options Debugger Options pus Function Toolbar Description Key Icon T 8 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 Step ver 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 Skep 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 el janis Broanoit Toggle breakpoints option sets new breakpoints or removes those F5 already set at the current cursor position Related topics Run Menu Debug Toolbar ao e E F6 E F8 E 115 MikroElektronika mikoBasic PRO for PIC32
507. t to be written The Lcd module needs to be initialized See Lcd Init routine Write text Here at current cursor position Led Out Cp Herel Lcd Chr isis dud sub procedure Lcd Chr dim row column as word dim out char as 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 Write Sage ae 1 at row 2 column 3 Lcd Chr S Dany MikroElektronika 322 mikroBasic PRO for PIC32 Lcd Chr Cp Prototype sub procedure Lcd Chr Cp dim out char as byte Description Prints character on Lcd at current cursor position Both variables and literals can be passed as a character Parameters out char character to be written Nothing Requires The Lcd module needs to be initialized See Lcd Init routine Write character e at current cursor position Led Chr Cp e None Lcd Cmd Clear Lcd display Lcd Cmd LCD CLEAR Predefined constants can be passed to the function see Available Lcd Commands Available Lcd Commands Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected CD RETURN HOME 323 MikroElektronika mikoBasic PRO for PIC32 Library Example The
508. ta to the assigned file Lt Set filename for single file tests write data to the assigned file appends data to it 391 MikroElektronika mikoBasic PRO for PIC32 Mmc Fat Append Prepare file for append file contents for mikroElektronika 2009 Prepare file for append file contents 26 10 Y LF Mmc Fat Write file contents 27 Write data to assigned file end sub e E Opens an existing file reads data from it and puts it to USART sub procedure M Open File Read filename 7 B Mmc Fat Assign filename 0 Mmc Fat Reset size To read file sub procedure returns size of file while size gt 0 Mmc Fat Read character UART1 Write character Write data to UART Dec size wend end sub V Deletes a file If file doesn t exist it will first be created and then deleted sub procedure M Delete File filename 7 F Mmc Fat Assign filename 0 Mmc Fat Delete end sub 2 2 Tests whether file exists and if so sends its creation date i and file size via USART sub procedure M Test File Exist dim fsize as longint year as word month day hour minute as byte outstr as char 12 filename 7 B if Mmc Fat Assign filename 0 0 then file has been found get its date mc Fat Get File Date year month day hour minute UART1 Write Text created WordToStr year outstr UART1 Write Text outstr ByteToStr month_ outstr UART
509. tatement and like goto the use of return statement is generally discouraged 229 MikroElektronika mikoBasic PRO for PIC32 Here is a simple example sub procedure Procl dim error as byte we re doing something here if error TRUE then return end if some code which won t be executed if error is true end sub Note Return statements performs the same as exit statement except in functions If breaking out of a function with return statement return value will not be specified In such cases exit statement should be used Goto Statement Use the goto statement to unconditionally jump to a local label for more information refer to Labels The syntax of the goto statement is goto label name This will transfer control to the location of a local label specified by label name The goto line can come before or after the label Label 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 The 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 the goto statement is breaking out from deeply nested control structures if disaster goto Error end if next
510. tation section of a module you cannot use it outside the module but you can use it in any block or routine defined within the module By placing the prototype in the interface section of the module above the implements you can make the routine public i e visible outside of module Prototypes must exactly match the declarations 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 include statements above the label main Specifying a data type for each variable is mandatory Syntax for variable declaration is dim identifier list as type Here identifier list is a comma delimited list of valid identifiers and type can be any data type For more details refer to Types and Types Conversions For more information on variables scope refer to the chapter Scope and Visibility Here are a few examples dim i j k as byte dim counter temp as word dim samples as longint 100 External Modifier Use the external modifier to indicate that the actual place and initial value of the variable sub function or sub procedure body is defined in a se
511. te dim wr rd cd rst as byte Description Initializes T6963C Graphic Lcd controller Display RAM organization The library cuts RAM into panels a complete panel is one graphics panel followed by a text panel see schematic below Parameters width width of the Glcd panel height height of the Glcd panel ntW font width DeviceAddress SPI expander hardware address see schematic at the bottom of this page wr Write signal pin on Glcd control port rd read signal pin on Glcd control port cd command data signal pin on Glcd control port rst reset signal pin on Glcd control port Returns Nothing Requires Global variables SPExpanderCs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before using this function The SPI module needs to be initialized See the SPIx_Init and SPIx Init Advanced routines 487 MikroElektronika mikoBasic PRO for PIC32 Port Expander module connections dim SPExpanderRST as sbit at LATFO bit SPExpanderCS as sbit at LATF1 bit SPExpanderRST Direction as sbit at TRISFO bit SPExpanderCS Direction as sbit at TRISF1 bit End Port Expander module connections Initialize SPI module SPIL Init SPI T6963C Config 240 64 8 SPI T6963C writeData Prototype sub procedure SPI T6
512. te and tne when tis routine Bcompled Example str votetbateting T DoGetVersion sub function DoGetVersion as string Returns Srmgwihcurencomplervei 1 Str DoGetVersion for example str will take the value of 8 2 1 6 None 157 MikroElektronika mikoBasic PRO for PIC32 KVAO TO KVA1 PRetums Virtual aderessinthe kse Example address KVAO TO KVA1 0x9FC00000 Notes None KVA1 TO KVAO eme wnan 000 Example address KVA1 TO KVAO 0xBFC00000 ees p aiii KVA_TO_PA Reums Appropriate physical ageress I o Requires Nothing Example address KVA TO PA 0xBFC00000 etes None MikroElektronika 158 mikroBasic PRO for PIC32 PA TO KVAO Retums Appropriate vrtuat adaress inne kse SSS Example address PA TO KVAO 0x1D000000 O jNme PA_TO_KVA1 Reums Vrwdad essteKSEGL SSCS Example address PA TO KVA1 0x1D000000 mas oe O S CPO GET Prototype sub function CPO GET dim const register as TCPOREG as longword Description Function returns the value of the coprocessor register or part of the register based upon the argument entered Parameters Parameter must be a constant from the enumerated built in constants list which can be found at the bottom of this page Returns Value of the coprocessor register or part of the register 159 MikroElektronika mikoBasic PRO for PIC32 CPO
513. te of the line start y end y coordinate of the line end x pos X coordinate of vertical line TFT module needs to be initialized See the TFT Init routine Draw a vertical line between dots 10 5 and 10 25 TFT V Line 5 25 10 TFT Rectangle Prototype sub procedure TFT Rectangle dim x upper left y upper left x bottom right y bottom right as 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 es TFT Rectangle 20 20 219 107 545 MikroElektronika mikoBasic PRO for PIC32 TFT Rectangle Round Edges Prototype sub procedure TFT Rectangle Round Edges dim x upper left y upper left x bottom right y bottom right round radius as word Description Draws a rounded edge rectangle on TFT Parameters x upper left x coordinate of the upper left rectangle corner y upper left y coordinate of the upper left rectangle corner x bottom right x coordinate of the lower right rectangle corner y bottom right y coordinate of the lower right rectangle corner round radius radius of the rounded edge TFT module needs to be initialized See the TFT Init routine E
514. ted along with the code execution Recently changed items are coloured red There are two ways to add variable register into the watch list by its real name variable s name in program code Just select wanted variable register from Select variable from list drop down menu and click the ox Add button by its name ID assembly variable name Simply type name ID of the variable register you want to display into Search for variable by assemby name box and click the x add button MikroElektronika 120 mikroBasic PRO for PIC32 Also it is possible to add all variables in the Watch Values Window by clicking Add All button To remove a variable from the Watch Values Window just select the variable that you want to remove and then click the 96 Remove button or press the Delete key It is possible to remove all variables from the Watch Values Window by clicking kA Remove All button You can also expand collapse complex variables i e struct type variables strings etc by clicking the appropriate button or beside variable name Watch Yalues Aey En Bx Select variable from list PC 0x00028E 9655 99 ms E Double clicking a variable or clicking the S Properties button opens the Edit Value window in which you can assign a new value to the selected variable register Also you can choose the format of variable register representation between decimal hexadecimal binary float or character All repres
515. teger number to be converted output destination string dim t as integer txt as string 6 t 3276 IntToStrWithZeros t txt fxt as 03276 LongWordToStrWithZeros Prototype sub procedure LongWordToStrWithZeros dim input as longword dim byref output as string 10 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 input unsigned long number to be converted output destination string Nothing dim t as longword txt as string 10 12345678 LongWordToStrWithZeros t txt txt is 0012345678 587 MikroElektronika mikoBasic PRO for PIC32 LongIntToStrWithZeros Prototype sub procedure LongIntToStrWithZeros dim input as longint dim byref output as string 11 ESSE Converts input longint to a string The output string is right justified and the remaining positions on the Pee if any are filled with zeros Parameters input word to be converted output destination string dim t as longint txt as string 11 12345678 LongIntToStrWithZeros t txt xt 2s 00123545678 ByteToHex Prototype dim procedure ByteToHex dim input as byte dim byref output as string 2 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
516. ter 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 dim receive as word read data if ready if UART1 Data Ready 1 then receive VARTI Read end if Nu UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library UARTx Tx Idle Prototype sub function UARTx Tx Idle as word 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 least one UART module Used UART module must be initialized before using this routine See UARTx Init and UARTx_Init_ Advanced routines If the previous data has been shifted out send next data if UART1 Tx Idle 1 then UART1 Write data end if module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library a UART library routines require you to specify the module you want to use To select the desired UART MikroElektronika 564 mikroBasic PRO for PIC32
517. terrupt iv IVT UART 2 ilevel 7 ics ICS SRS RS485Master Receive dat U2RXIF bit 0 ensure interrupt not pending end sub main ent 0 CHECON 0x32 AD1PCFG OxFFFF PORTB PORTD TRISB TRISD oO Oo UART2 Init 19200 Delay ms 100 initialize UART2 module RS485Master Init initialize MCU as Master dat 0 OxAA dat 1 OxFO dat 2 OxOF dat 4 0 ensure that message received flag is 0 dat 5 0 ensure that error flag is 0 dat 6 0 U2IPO0 bit 1 set interrupt UZTPT bit 1 priority U2IP2 bit 1 oo URXISEL1 U2STA bit 0 0x Interrupt flag bit is set when a character is received U2RXIF bit 0 ensure interrupt not pending MikroElektronika 382 mikroBasic PRO for PIC32 MVEC bit 1 Interrupt controller configured for multi vectored mode asm ei RO Enable all interrupts end asm U2RXIE bit 1 enable intterupt RS485Master Send dat 1 160 while TRUE upon completed valid message receiving 1 data 4 is set to 255 Inc cnt if dat 5 0 then if an error detected signal it PORTD OxAA 1 by setting portd to 0xAA end if if dat 4 0 then if message received successfully ent 0 dat 4 0 clear message received flag j dat 3 for i 1 to dat 3 show data on PORTB PORTB dat i 1 next i dat 0 dat 0 1 send back to master Delay ms 1 RS485Master Send dat 1 160 end if if cnt 100000
518. terrupt flag bit is set when a character is ensure interrupt not pending Interrupt controller configured for multi vectored mode Enable all interrupts enable intterupt if an error detected signal it by x setting portd to 0xAA upon completed valid message receive 3 data 4 is set to OxFF show data on PORTB next i dat 0 dat 0 1 increment received dat 0 Delay ms 1 RS485Slave Send dat l1 and send it back to master end if wend end MikroElektronika 384 mikroBasic PRO for PIC32 HW Connection Shielded pair no longer than 300m OSCILLATOR PIC32MX460F512L a o VCC3 IGND vec Example of interfacing PC to PIC32 MCU via RS485 bus with LTC485 as RS 485 transceiver mikoBasic PRO for PIC32 Message format and CRC calculations Q How is CRC checksum calculated on RS485 master side Copy Code To Clipboard START BYTE 0x96 10010110 STOP BYTE 0xA9 10101001 PACKAGE ADDRES S DATALEN DATA1 DATA2 DATA3 CRC START BYTE 0x96 if exists if exists if exists STOP BYTE OxA9 DATALEN bits bit7 1 0 bit6 1 0 bit5 0 bit4 1 BYTE 0 bit3 1 BYTE 0 bit2 1 BYTE 0 bitlbitO0 MASTER SENDS SLAVE SENDS ADDRESS WAS XORed with 1 IT WAS EQUAL TO START BYTE or STOP BYTE ADDRESS UNCHANGED FIXED DATA3 if exists WAS XORed with 1 IT WAS EQUAL TO START BYTE or STOP
519. text CF cards are widely used memory elements commonly used with digital cameras Great capacity and excellent access time of only a few microseconds make them very attractive for microcontroller applications In CF card data is divided into sectors One sector usually comprises 512 bytes Routines for file handling the Cf Fat routines are not performed directly but successively through 512B buffer Important Routines for file handling can be used only with FAT16 file system Library functions create and read files from the root directory only Library functions populate both FAT1 and FAT2 tables when writing to files but the file data is being read from the FAT1 table only i e there is no recovery if the FAT1 table gets corrupted If MMC SD card has Master Boot Record MBR the library will work with the first available primary logical partition that has non zero size If MMC SD card has Volume Boot Record i e there is only one logical partition and no MBRs the library works with entire card as a single partition For more information on MBR physical and logical drives primary secondary partitions and partition tables please consult other resources e g Wikipedia and similar Before writing operation make sure not to overwrite boot or FAT sector as it could make your card on PC or digital camera unreadable Drive mapping tools such as Winhex can be of great assistance Library Dependency Tree g Comp
520. th path EAP lt size gt Heap size in bytes Gc Generate COFF file PF Project file name SSA Enable SSA optimization UICD ICD build type INTDEF Interrupt settings EBASE Exception base address mT Aawe 111 MikroElektronika mikoBasic PRO for PIC32 Example mBPIC32 exe MSF DBG p32MX460F512L Y DL 011111114 f080 N C NLcdNLcd mbp32 SP C Program Files Mikroelektronika mikroBasic PRO for PIC32 Defs SP C Program Files Mikroelektronika mikroBasic PRO for PIC32 Uses SP C N Led Lib Math emcl Lib MathDouble emcl Lib System emcl Lib Delays emcl Lib LcdConsts emcl Lib Lcd emcl Lcd mbas Parameters used in the example MSF Short Message Format used for internal purposes by IDE DBG Generate debug info p32MX460F5121L MCU P32MX460F512L selected Y Dynamic link for string literals enabled DL All files built as libraries 011111114 Miscellaneous output options fo80 Setoscillator frequency in MHz N C NLcdNLod mbp32 SP C NProgram Files Mikroelektronika mikroBasic PRO for PIC32 Defs Output files generated to file path specified by filename SP C Program Files Mikroelektronika mikroBasic PRO for PIC32 Defs Add directory to the search path list SP C Program Files Mikroelektronika mikroBasic PRO for PIC32 Uses Add directory to the search path list SP C Led Add directory to the search path li
521. that The file name and extension are case insensitive The library will convert them to proper case automatically so the user does not have to take care of that Also in order to keep backward compatibility with the first version of this library file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between the file name and extension i e MIKROELETXT gt MIKROELE TXT In this case the last 3 characters of the string are considered to be file extension file attr file creation and attributes flags Each bit corresponds to the appropriate file attribute MikroElektronika 212 mikroBasic PRO for PIC32 5 Device internal use only never found on disk 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 Parameters Volume Label Subdirectory 0 otherwise CF card and CF library must be initialized for file operations See Cf Fat Init Try to create a swap file with archive atribute whose size will be at least 1000 sectors 1 If it succeeds it sends the No of start sector over UART dim size as longword j Cf Fat Get Swap File 1000 mikroE txt 0x20 i size 0 then UART1 Write OxAA UART1 Write Lo size UART1 Write Hi size UART1 Write Higher size UART1 Write Highest size UART1 Write 0xAA Long File Names LFN are not supported Libra
522. the loop by changing final value With each iteration statement list will be executed initial value and final value should be expressions compatible with counter statement list may be consisted of statements that don t change the value of the counter Note that the parameter step value may be negative allowing you to create a countdown MikroElektronika 226 mikroBasic PRO for PIC32 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 statements final value statement list is a list of statements that do not change the value of counter Here is an example of calculating scalar product of two vectors a and b of length 10 using the for statement s for B next i le o 0 to 9 st alil i Endless Loop The for statement results in an endless loop if final value equals or exceeds the range of the counters type While Statement Use the while keyword to conditionally iterate a statement The syntax of the while statement is while expression statements wend statements are executed repeatedly as long as expression evaluates true The test takes place before statements are executed Thus if expression evaluates false on the first pass the loop does not execute Here is an example of calculating scal
523. 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 file creation and attributes flags Each bit corresponds to the appropriate file attribute Pei wask Description o foo Resow Ls oxo pesce tema use ony never found ond 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 349 MikroElektronika mikoBasic PRO for PIC32 Try to create a swap file with archive atribute whose size will be at least 1000 sectors If it succeeds it sends No of start sector over UART dim size as longword size Mmc Fat Get Swap File 1000 mikroE txt 0x20 if size lt gt 0 then UART1 Write 0xAA UART1 Write Lo size UART1 Write Hi size UART1 Write Higher size UART1 Write Highest size UART1 Write 0xAA end if 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 l
524. 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 dim error as word sectorNo as longword dataBuffer as byte 512 510 Mmc Write Sector sectorNo dataBuffer 339 MikroElektronika mikoBasic PRO for PIC32 Mmc Read Cid Prototype sub function Mmc Read Cid dim byref data cid as byte 16 as byte 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 dim error as word dataBuffer as byte 512 rror Mmc Read Cid dataBuffer Mmc Read Csd Prototype sub function Mmc Read Csd dim byref data csd as byte 16 as 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 dim error as word dataBuffer as byte 512 rror Mmc Read Csd dataBuffer MikroElektronika 340 mikroBasic PRO for PIC32 Mmc Fat Init Prototype sub function Mmc Fat Init as word Initializes MMC SD card reads MMC SD FAT16 boot sector and extracts necessary data needed by the library Parameters None 0 if MMC SD card w
525. they can be easily recreated when the project is rebuilt Select which files you want to remove from the project folder Please note that selected files will be permanently deleted from your disk if you click COG xml LCD asm LCD cfg LCD dbg LCD dct LCD dit LCD emcl LCD hex LCD log LCD Ist LCD mbas LCD mbp32 LCD mbp32_callertable txt LCD user dic v v v IV M a C Program Files Mikroelektronika mikroBasic PRO For PIC32 Examples Development Sys Related topics Customizing Projects MikroElektronika O A mikroBasic PRO for PIC32 Compilation When you have created the project and written the source code it s time to compile it Select Project Build from the drop down menu or click the Build Icon 3h from the Build Toolbar If more more than one project is open you can compile all open projects by selecting Project Build All Projects from the drop down menu or click the Build All Projects Icon By trom the Build Toolbar Progress bar will appear to inform you about the status of compiling If there are some errors you will be notified in the Messages Window If no errors are encountered the mikroBasic PRO for PIC32 will generate output files Output Files Upon successful compilation the mikroBasic PRO for PIC32 will generate output files in the project folder folder which contains the project file mbp32 Output files are summarized in the table below Intel HEX Intel style
526. 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 bufferto store hours of modification attribute to Upon function execution hours of modification attribute is returned through this parameter Prototype sub procedure Cf Fat Get File Date Modified dim byref year as word dim byref 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 dim year as word dim month day hours mins as byte Date Modified year month day hours mins 271 MikroElektronika mikoBasic PRO for PIC32 Cf Fat Get File Size Reums Szeofhecurenlyassgnedfiembyes 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 dim my file size as longword my file size Cf Fat Get File Srze Cf Fat Get Swap File Prototype sub function Cf Fat Get Swap File dim sectors cnt as longword dim byref filename as string 11 dim file att
527. til 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 sub procedure SSA Test dim y as char if y then Variable y might not have been initialized asm nop end asm end if end sub main SSA Test end Related topics Code Optimization PIC32 Specifics mikroBasic PRO for PIC32 specifics Memory type specifiers 165 MikroElektronika mikoBasic PRO for PIC32 CHAPTER 7 PIC32 Specifics In order to get the most from the mikroBasic PRO for PIC32 compiler the user should be familiar with certain aspects of PIC32 MCU This knowledge is not essential but it can provide a better understanding of the PIC32 s capabilities and limitations and their impact on the code writing as well MikroElektronika 166 mikroBasic PRO for PIC32 Types Efficiency First of all the user should know that PIC32 s ALU which performs arithmetic operations is optimized for working with 32 bit types Also it performs hardware multiplication and division on the integer
528. tine 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 417 MikroElektronika mikoBasic PRO for PIC32 Prototype sub procedure SPI Ethernet Disable dim disFlt as byte SPI Ethernet Disable Description This is MAC module routine This routine disables appropriate network traffic on the ENC28J60 module by the means of it s receive filters unicast multicast broadcast crc Specific type of network traffic will be disabled if a corresponding bit of this routine s input parameter is set Therefore more than one type of network traffic can be disabled at the same time For this purpose predefined library constants see the table below can be ORed to form appropriate input value Parameters disF1t network traffic receive filter flags Each bit corresponds to the appropriate network traffic receive filter MAC Broadcast traffic receive filter flag When set SPI Ethernet MAC broadcast traffic will be disabled BROADCAST x02 MAC Multicast traffic receive filter flag When set MAC SPI Ethernet multicast traffic will be disabled MULTICAST o o x e
529. tion part of a program or routine You can declare any number of constants after the keyword const const constant name as 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 it the compiler assumes the smallest type that can accommodate value Note You cannot omit type when declaring a constant array Here are a few examples const MAX as longint 10000 const MIN 1000 compiler will assume word type const SWITCH n compiler will assume char type const MSG Hello compiler will assume string type const MONTHS as byte 12 31 28 31 30 31 30 31 31 30 31 30 31 195 MikroElektronika mikoBasic PRO for PIC32 Labels Labels serve as targets for goto and gosub statements Mark the desired statement with label and colon like this label identifier statement No special declaration of label is necessary in mikroBasic PRO for PIC32 Name of the label needs to be a valid identifier The labeled statement and goto gosub statement must belong to the same block Hence it is not possible to jump into or out of routine Do not mark more than one statement in a block with the same label Note The label main marks the entry point of a program and must be present in the main modul
530. tions should not be altered by the user in any case 451 MikroElektronika mikoBasic PRO for PIC32 SPI Ethernet 24j600 getlpMask Prototype sub function SPI Ethernet 243600 getIpMask as word Description This routine should be used when DHCP server is present on the network to fetch assigned DNS IP address Pointer to the global variable holding IP subnet mask Requires Ethernet module has to be initialized See SPI Ethernet 24j600 Init Available for PIC18 family MCUs only dim IpMask as byte 4 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 Prototype sub procedure SPI Ethernet 243600 confNetwork dim byref ipMask gwIpAddr dnsIpAddr as byte 4 Description Configures network parameters IP subnet mask gateway IP address DNS IP address when DHCP is not used Parameters ipMask IP subnet mask gwlpAddr gateway IP address dnsIpAddr DNS IP address Nothing Requires Ethernet module has to be initialized See SPI Ethernet 24j600 Init dim ipMask as network mask for example 255 255 255 0 gwlpAddr as gateway router IP address dnsIpAddr as DNS server IP address gwlIpAddr gwlIpAddr gwlIpAddr gwlIpAddr
531. to record a series of keystrokes and then playback or repeat the recorded keystrokes n MikroElektronika mikoBasic PRO for PIC32 The Macro offers the following commands 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 mikroBasic PRO for PIC32 provides this possibility through the Image Preview Window To add an image to the Image Preview Window right click the Image Files node in the Project Manager E Project Manager 1 1 R5485 Master Example mbp32 40 eysssid ase Ay Rs485 Master Example mbp32 S Sources 2 R5485 Master Example mbas Binaries Project Level Defines iy EEPROM File m Active Comm S Output Files Add Project 3B R5485 Cy Other Files C3 Add File To Project Remove File From Project Close Project Ctri K M Build Ctr F9 ES mE Programmer Fil MikroElektronika D mikroBasic PRO for PIC32 Now navigate to the desired image file and simply add it Project Manager 1 1 R5485 Master Example mbp32 zu
532. to use To select the desired C module simply change the letter x in the routine prototype for a number from 1 to 5 Number of IPC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library dim data as byte if I2Cl Is Idle then I2Cl Write data end if MikroElektronika 312 mikroBasic PRO for PIC32 I2Cx Read peice sub function I2Cx Read dim ack as word as byte Reads a byte from the lC bus Parameters ack acknowledge signal parameter If the ack 0 acknowledge signal will be sent after reading oe the not acknowledge signal will be sent Retums Received data Requires MCU with at least one lC module Used I C module must be initialized before using this function See I2Cx Init routine Also START signal needs to be issued in order to use this function See I2Cx Start dim take as byte Read data and send the not acknowledge signal take I2C1 Read 1 PC library routines require you to specify the module you want to use To select the desired C module simply change the letter x in the routine prototype for a number from 1 to 5 Number of IC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library I2Cx Write prototipo sub function I2Cx Write dim data as byte as word Sends data byte via the IC bus data data to be sent 0 if there were no errors 1 if write
533. tor 590 CF Write Insrt 590 1 MikroElektronika 264 mikroBasic PRO for PIC32 Cf Write Byte Prototype sub procedure Cf Write Byte dim data as 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 dim data as byte data_ OxAA Cf Write Byte data_ Cf_Read_Sector Prototype sub procedure Cf Read Sector dim sector number as longword dim byref buffer as byte 512 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 dim data as byte 512 Cf Read Sector 22 data Cf Write Sector Prototype sub procedure Cf Write Sector dim sector number as longword dim byref buffer as byte 512 Description Writes 512 bytes of data provided by the buffer parameter to one CF sector Parameters sector number
534. tructure Each Dot contains two members x and y coordinates memory is allocated when you instantiate the structure like this dim m n as Dot This variable declaration creates two instances of Dot called n and n A member can be of the previously defined structure type For example Structure defining a circle structure Circle dim radius as float dim center as Dot end structure Structure Member Access You can access the members of a structure by means of dot as a direct member selector If we had declared the variables circlel and circle2 ofthe previously defined type Circle dim circlel circle2 as Circle we could access their individual members like this circlel radius 3 7 circlel center x 0 circlel center y 0 You can also commit assignments between complex variables if they are of the same type circle2 circlel This will copy values of all members 211 MikroElektronika mikoBasic PRO for PIC32 Types Conversions Conversion of variable of one type to a variable of another type is typecasting mikroBasic PRO for PIC32 supports both implicit and explicit conversions for built in types Implicit Conversion Compiler will provide an automatic implicit conversion in the following situations statement requires an expression of particular type according to language definition and we use an expression of different type operator requires an operand of particular type and we use an operand
535. ts Break and Continue Statements Exit Statement Goto Statement Gosub Statement asm Statement Directives Compiler Directives Linker Directives Lexical Elements Overview The following topics provide a formal definition of the mikroBasic PRO for PIC32 lexical elements They describe different categories of word like units tokens recognized by the language In the tokenizing phase of compilation the source code file is parsed i e broken down into tokens and whitespace The tokens in mikroBasic PRO for PIC32 are derived from a series of operations performed on your programs by the compiler A mikroBasic PRO for PIC32 program starts as a sequence of ASCII characters representing the source code created by keystrokes using a suitable text editor such as the mikroBasic PRO for PIC32 Code Editor The basic program unit in mikroBasic PRO for PIC32 is a file This usually corresponds to a named file located in RAM or on disk having the extension mbas MikroElektronika 178 mikoBasic PRO for PIC32 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 two sequences dim tmp as byte dim j as word and dim tmp as byte dim j as word are lexically equivalent and parse identically Newline
536. tter example We got the starting sequence Exit so we do not loop forever 331 MikroElektronika mikoBasic PRO for PIC32 do temp Man Receiv if error flag lt gt 0 Lcd Chr CP Inc ErrorCount if ErrorCount 20 then temp Man Synchro Man Receive Init ErrorCount 0 end if else if error flag then temp lt gt 0x0 Lcd Chr CP temp Inc counter if counter 25 then Lcd Cmd LCD CLEAR temp Man Synchro end if else counter end if Delay ms 25 end if loop until wend end 0 0x01 I temp Attempt byte receive If error occured Write question mark on LCD Update error counter In case of multiple errors Try to synchronize again Alternative try to Initialize Receiver again Reset error counter No error occured If End byte was received see Transmitter example do not write anymore received byte on Lcd else write character on Lcd Counts how many chars have been written on Lcd If there were more then 25 characters synchronization is off Clear the Lcd of garbled communication Try to synchronize again Y Y Y reset counter If End byte was received exit do loop 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 dim MANRXPIN as sbit
537. ub function Ord dim character as char as 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 ASCI code ofthe cnaraccons 0 S Example c Ord A returns 65 moes None SSCS SetBit Prototype sub procedure SetBit dim byref register as word dim rbit as byte Description Function sets the bit roit of register Parameter rbit needs to be a variable or literal with value 0 15 For more information on register identifiers see Predefined Globals and Constants This is an inline routine the code is generated in the place of the call Parameters register desired register rbit desired bit meus Noting Example SetBit PORTB 2 Set RB2 ee Nene ClearBit Prototype sub procedure ClearBit dim byref register as word dim rbit as byte Description Function clears the bit rbit of register Parameter rbit needs to be a variable or literal with value 0 7 See Predefined globals and constants for more information on register identifiers This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Parameters register desired register rbit desired bit eum Wo Example ClearBit PORTC 7 Clear RC7 Notes wn ooo MikroElektronika 150
538. uest 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 8dyna 28 then puts the request string converted into upper char into the transmit buffer while reqLength lt gt 0 Spi Ethernet putByte Spi Ethernet getByte reqLength reqLength 1 435 MikroElektronika mikoBasic PRO for PIC32 wend back to the library with the length of the UDP reply end sub main CHECON 0x32 ADIPCFG OxFFFC all digital but RB1 AN1 and RBO ANO PORTB 0 TRISB OxFFFF set PORTB as input for buttons and adc PORTD 0 TRISD 0 set PORTD as output ADCl Init httpCounter 0 set mac address myMacAddr 0 0x00 myMacAddr 1 0x14 myMacAddr 2 0xA5 myMacAddr 3 0x76 myMacAddr 4 0x19 myMacAddr 5 0x3F set IP address myIpAddr 0 192 myIpAddr 1 168 myIpAddr 2 20 myIpAddr 3 60 set gateway address gwlpAddr 0 192 gwlpAddr 1 168 gwlIpAddr 2 20 gwlpAddr 3 6 set dns address dnsIpAddr 0 192 dnsIpAddr 1 168 dnsIpAddr 2 20 dnsIpAddr 3 1 set subnet mask ipMask 0 255 ipMask 1 255 ipMask 2 255 ipMask 3 0 MikroElektronika 436 mikroBasic PRO for PIC32 CS my cR Oe HE X starts ENC28J60 with reset bit on PORTC BO bit on PORTC B1 MAC amp IP address full duplex SPI2 Init Advanced SP
539. ul packet processing zero packets received or received packet processed successfully 1 upon reception error or receive buffer corruption NC28460 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 TRUF Ethernet doPacket process received packets hernet doPacket must be called as often as possible in user s code SPI Ethernet putByte Prototype sub procedure SPI Ethernet putByte dim v as byte Description This is MAC module routine It stores one byte to address pointed by the current ENC28J60 write pointer EWRPT v value to store Nothing Ethernet module has to be initialized See SPI Ethernet Init dim data as byte SPI Ethernet putByte data put an byte into ENC28J60 buffer 419 MikroElektronika mikoBasic PRO for PIC32 SPI Ethernet putBytes Prototype sub procedure SPI Ethernet putBytes dim ptr as byte dim n as word Description This is MAC module routine It stores requested number of bytes into ENC28360 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 Nothing Requires Ether
540. ular bit is set then corresponding meaning is TRUE or else it will be FALSE 253 MikroElektronika mikoBasic PRO for PIC32 Copy Code To Clipboard const CANSPI RX FILTER BITS as byte 07 Use this to access filter bits CANSPI RX FILTER 1 as byte 00 CANSPI RX FILTER 2 as byte 01 CANSPI RX FILTER 3 as byte 02 CANSPI RX FILTER 4 as byte 03 CANSPI RX FILTER 5 as byte 04 CANSPI RX FILTER 6 as byte 05 CANSPI RX OVERFLOW as byte 08 Set if Overflowed else cleared _CANSPI_ RX INVALID MSG as byte 10 Set if invalid else cleared CANSPI RX XTD FRAME as byte 20 Set if XTD message else cleared CANSPI RX RTR FRAME as byte 40 Set if RTR message else cleared CANSPI RX DBL BUFFERED as byte 80 Set if this message was hardware double buffered You may use bitwise and to adjust the appropriate flags For example Copy Code To Clipboard if MsgFlag and _CANSPI_RX OVERFLOW lt gt 0 then Receiver overflow has occurred We have lost our previous message end if CANSPI_MASK Constants The CANSPI_ MASK constants define mask codes Function CANSPISetMask expects one of these as it s argument Copy Code To Clipboard const _CANSPI MASK Bl as byte 0 CANSPI MASK B2 as byte 1 CANSPI FILTER Constants The CANSPI FILTER constants define filler codes Functions CANSPISetFilter expects one of these as it s argument Copy
541. unded edge rectangle Y zd IFDEF LINE DEMO SPI T6963C Rectangle Round Edges 10 10 229 117 12 SPI T6963C WHIT SPI T6963C Rectangle Round Edges 30 30 209 97 12 SPI T6963C WHITI SPI T6963C Rectangle Round Edges 50 50 189 77 12 SPI T6963C WHITI ENDIF m a m E Y Y Draw filled rounded edge rectangle Y IFDEF FILL DEMO SPI T6963C Rectangle Round Edges Fill 10 10 229 117 12 SPI T6963C WHITE SPI T6963C Rectangle Round Edges Fill 20 20 219 107 12 SPI T6963C BLACK SPI T6963C Rectangle Round Edges Fill 30 30 209 97 12 SPI T6963C WHITE 40 50 SPI T6963C Rectangle Round Edges Fill 40 199 87 12 SPI T6963C BLACK SPI T6963C Rectangle Round Edges Fill 50 189 77 12 SPI T6963C WHITE ENDIF y 3 Draw a cross i 503 MikroElektronika mikoBasic PRO for PIC32 IFDEF LINE DE MO SPI T6963C line 0 0 239 127 27 239 0 SPI T6963C line 0 ENDIF Y 3 Draw circles Y IFDEF LINE DE MO Znnnnnnn DIF Y Ji Draw filled circles Y IFDEF FILL DEMO PI T6963C circl PI T6963C circl PI T6963C circl PI T6963C Gircl PI T6963C circl PI T6963C Garcb PI T6963C circl PI T6963C eircl PI T6963C circl PI T6963C circl
542. unication see SPI Glcd Init routine Draw a line between dots 0 0 and 20 30 SPI Gled Line 0 0 20 30 1 None SPI Glcd V Line Prototype sub procedure SPI Glcd V Line dim y start y end x pos color as 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 Gled V Line 5 25 10 1 MikroElektronika 462 mikroBasic PRO for PIC32 SPI Glcd H Line Prototype sub procedure SPI Glcd H Line dim x start x end y pos color as byte Draws a horizontal line on Glcd Parameters x start x coordinate of the line start Valid values 0 127 x end X coordinate of the line end Valid values 0 127 y pos y coordinate of horizontal line Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the line color 0 white 1 black and 2 inverts each dot Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draw a horizontal line between dots 10 20 and 50 20 SPI Gled H Line 10 50 20 1 None
543. ur own templates to the list by entering the desired keyword description and code of your template in appropriate boxes Autocomplete macros can retreive system and project information DATE current system date TIMES current system time SDEVICES device MCU name as 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 ptemplate provided with mikroBasic PRO for PIC32 installation MikroElektronika 56 mikroBasic PRO for PIC32 Code Explorer The Code Explorer gives clear view of each item declared inside the source code You can jump to a declaration of any item by double clicking it or pressing the Enter button Also besides the list of defined and declared objects code explorer displays message about the first error and it s location in code Code Explorer Za LZ E web links http wwnw mikroe com Gi Include Qi main LCD RS LCD EN LCD D4 LCD D5 LCD D6 LCD D7 LCD RS Direction LCD EN Direction LCD D4 Direction LCD D5 Direction LCD D6 Direction o e o e e 9 M LCD D7 Direction txti txt2 txt3 txt4 i o love Delay The following options are available in the Code Explorer kon Description Expand Collapse all nodes in tree 9 Locate declaration in code 5 MikroElektronika
544. ure S1D13700 Display GrLayer dim mode as byte Description Display selected graphic layer Parameters mode graphic layer mode Valid values Glcd module needs to be initialized See the S1D13700 Init routine Turn on graphic layer S1D13700 Display GrLayer S1D13700 LAYER ON MikroElektronika 284 mikroBasic PRO for PIC32 S1D13700 Display TxtLayer Prototype sub procedure S1D13700 Display TxtLayer dim mode as byte Description Display selected text layer Parameters mode text layer mode Valid values Glcd module needs to be initialized See the S1D13700 Init routine Display on text layer S1D13700 Display TxtLayer S1D13700 LAYER ON S1D13700 Set Cursor Prototype sub procedure S1D13700 Set Cursor dim width as byte dim height as byte dim mode as byte 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 S 1D13700 CURSOR UNDERSCORE Set cursor shape underscore S1D13700 CURSOR BLOCK Set cursor shape block Glcd module needs to be initialized See the S1D13700 Init routine set cursor with the following properties width 5px height 10px cursor shape block S1D13700 Set Cursor 5 10 S1D13700 CURSOR BLOCK 285 MikroElektronika mikoBasic PRO for PIC32 S1D13700 Dis
545. usy OxFFFF if at least one Transmit Buffer is available ba The CANSPI module must be in mode in which transmission is possible See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page send message extended CAN message with the appropriate ID and data dim tx flags as byte data as byte 8 msg id as longint CANSPISetOperationMode CAN MODE NORMAL OxFF set NORMAL mode CANSPI1 must be in mode in which transmission is possible tx flags _CANSPI TX PRIORITY 0 and CANSPI TX XTD FRAME set message 2 tx flags CANSPI Constants There is a number of constants predefined in the CANSPI library You need to be familiar with them in order to be able to use the library effectively Check the example at the end of the chapter CANSPI OP MODE Constants The CANSPI OP MODE constants define CANSPI operation mode Function CANSPISetOperationMode expects one of these as it s argument 291 MikroElektronika mikoBasic PRO for PIC32 Copy Code To Clipboard const CANSPI MODE CANSPI MODE NO CANSPI MODE SLI CANSPI MODE LO CANSPI MODE LI alt CANSPI MODE CO TS as RMAL as EEP as OP as STEN as NFIG as byte byte byte byte byte byte SEO 0 20 40 60 80 Use this to acc
546. uty current duty 5 decrement current duty if current duty pwm periodl then if we decrease current duty greater then possible pwm periodl value overflow current duty pwm periodl set current duty to max possible value end if PWM Set Duty current duty 1 set newly acquired duty ratio end if 319 MikroElektronika mikoBasic PRO for PIC32 if RB2 bit 1 then Delay ms 1 current dutyl current dutyl 5 if current dutyl pwm period2 then possible pwm period2 value current dutyl 0 end if PWM Set Duty current dutyl 2 end if if RB3 bit Delay ms 1 current dutyl current dutyl 5 if current dutyl pwm period2 then possible pwm periodi value overflow 1 then current dutyl pwm period2 end if PWM Set Duty current dutyl 2 end if Delay ms 1 wend end HW Connection button on RB2 pressed increment current dutyl if we increase current dutyl greater then reset current dutyl value to zero set newly acquired duty ratio button on RB3 pressed decrement current dutyi if we decrease current dutyl greater then set current duty to max possible value slow down change pace a little PWM demonstration MikroElektronika 316 mikroBasic PRO for PIC32 RS 485 Library RS 485 is a multipoint communication which allows multiple devices to be connected to a single bus mikroBasic PRO for PIC32 provides a set of library routines for
547. ve function both SPI modules have to be previously initialized Library Routines SPIx Init SPIx Init Advanced SPIx Read SPIx Write SPI Set Active 405 MikroElektronika mikoBasic PRO for PIC32 SPIx Init Prototype sub procedure SPIx Init Description Configures and initializes the SPI module with default settings Default settings Master mode 8 bit data mode Serial clock set to System clock 64 Slave Select disabled Input data sampled in the middle of interval Clock idle state low Serial output data changes on transition from idle clock state to active clock state Parameters None MCU must have the SPI1 module Initialize the SPI1 module with default settings SFTI 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 MikroElektronika A06 mikroBasic PRO for PIC32 SPIx Init Advanced Prototype sub procedure SPIx Init Advanced dim master mode data mode clock divider slave select data sample clock idle edge as word Configures and initializes
548. vice dock O OC Example elk coors zo LL Get Fosc kHz is a library function rather than a built in routine it is presented in this topic for the sake of convenience 154 MikroElektronika mikoBasic PRO for PIC32 Get Fosc Per Cyc Prototype sub function Get Fosc Per Cyc as 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 Parameters None Returns Device s clock per cycle rounded to the nearest integer dim clk per cyc as word clk per eyc Get Fose Per Cyec Reset eum nonn OOOO C moes oe OOOO ClrWat Prototype sub procedure ClrWdt This procedure is equal to assembler instruction clrwdt Reums Nang Example ermo 7 Gesn WF Mos Nae OSS MikroElektronika 199 mikoBasic PRO for PIC32 DisableContextSaving Prototype sub procedure DisableContextSaving Description Use the DisableContextSaving to instruct the compiler not to automatically perform context switching This means that no register will be saved restored by the compiler on entrance exit from interrupt service routine This enables the user to manually write code for saving registers upon entrance and to restore them before exit from interrupt Parameters None This routine must be called
549. w Stopwatch Window EEPROM Watch Window Code Watch Window Breakpoints Window The Breakpoints window manages the list of currently set breakpoints in the project Doubleclicking the desired breakpoint will cause cursor to navigate to the corresponding location in source code In situations when multiple breakpoints are used within the code it is sometimes handy to enable disable certain breakpoints To do this just check uncheck the desired breakpoint using the checkbox in front of the breakpoint s name Breakpoints Enable Line File Name Watch Values Window Watch Values Window is the main Debugger window which allows you to monitor program execution To show the Watch Values Window select Debug Windows Watch from the View drop down menu The Watch Values Window displays variables and registers of the MCU with their addresses and values Values are updated along with the code execution Recently changed items are coloured red There are two ways to add variable register into the watch list by its real name variable s name in program code Just select wanted variable register from Select variable from list drop down menu and click the d Add button by its name ID assembly variable name Simply type name ID of the variable register you want to display into Search for variable by assemby name box and click the a add button 121 MikroElektronika mikoBasic PRO for PIC32 Also it is possible to add
550. 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 from the File Toolbar MikroElektronika 620 mikroBasic PRO for PIC32 Saving file under a different name 1 Make sure that the window containing the file that you want to save is the active window 2 Select File Save As from the drop down menu The New File Name dialog will be displayed 3 In the dialog browse to the folder where you want to save the file 4 In the File Name field modify the name of the file you want to save 5 Click the Save button Closing file 1 Make sure that the tab containing the file that you want to close is the active tab 2 Select File Close from the drop down menu or right click the tab of the file that you want to close and select Close option from the context menu 3 If the file has been changed since it was last saved you will be prompted to save your changes Search Paths You can specify your own custom search paths select Project Edit Search Paths option from the drop down menu Search Paths C Program Files Mikroelektronika mikroBasic PRO For PIC32 defs C Program Files Mikroelektronika mikroBasic PRO For PIC32 uses C Program Files Mikroelektronika mikroBasic PRO For PIC32 Examples Development SystemslLV32MX vellCD 621 MikroElektronika mikoBasic PRO for PIC32 Following option
551. word Display selected graphic panel n graphic panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine display graphic panel 1 SPI T6963C displayGrPanel 1 None 497 MikroElektronika mikoBasic PRO for PIC32 SPI T6963C displayTxtPanel eum Noting 00 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine display text panel 1 SPI T6963C displayTxtPanel 1 SPI T6963C setGrPanel Description Compute start address for selected peers panel and set appropriate internal pointers All subsequent graphic operations will be preformed at this graphic panel n graphic panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine set graphic panel 1 as current graphic panel SPI T6963C setGrPanel Notes None eee SPI T6963C setTxtPanel Description Compute start address for selected text panel and set appropriate internal pointers All subsequent text operations will be preformed at this text panel n text panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine set text panel 1 as v MI text panel SPI T6963C setTxtPanel INots None ees MikroElektronika 498 mikroBasic PRO for PIC32 SPI T6963C panelFill Prototype sub procedure SPI T6963C panelFill dim v as word Description
552. xample TFT Rectangle Round Edges 20 20 219 107 12 TFT Circle Prototype sub procedure TFT Circle dim x center y center radius as 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 eris TFT Circle 120 64 110 TFT Image Prototype sub procedure TFT Image dim left top as word dim image as far const byte dim stretch as 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 rrrimse 0 Ginage dj MikroElektronika 546 mikroBasic PRO for PIC32 TFT Partial Image image as far const byte dim stretch as byte Description Displays a partial area of the image on a desired location Prototype sub procedure TFT Partial Image dim left top width height as word dim Parameters left left coordinate of the image top top coordinate of the image width desired image width height desired image height image image to be displayed Bitmap array is located in code memory stretch
553. y are filled with zeros Parameters input integer number to be converted output destination string Nothing Requires Nothing dim input as integer txt as string 4 input 32768 IntToHex input txt r txt as 8000 LongWordToHex Prototype sub procedure LongWordToHex dim input as longword dim byref output as string 8 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 output destination string Nothing dim input as longword txt as stringis input 65535 LongWordToHex input txt txt is OOOOFFFF MikroElektronika 590 mikroBasic PRO for PIC32 LonglntToHex Prototype sub E m LongIntToHex dim input as longint dim byref output string 8 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 output destination string dim input as longint txt as string 8 2147483648 LongIntToHex input txt itxt is 800000007 StrTolnt Prototype sub function StrToInt dim byref input as string 6 as integer Converts a string to an integer input string to
554. y txt txt sub v copies string txt sub to txt strlen Prototype sub function strlen dim byref s as string as word The function returns the length in words of the string s The length does not include the null terminating character txt mikroElektronika res strlen txt calculates the length of the txt string result 16 strncat Prototype sub procedure strncat dim byref sl s2 as string dim size as 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 txt mikroElektronika txt sub mikr EXE 5 strncat txt txt sub 4 routine appends first 4 characters from the string txt sub at the place of first null character in the txt string strncpy Prototype sub procedure strncpy dim byref sl s2 as string dim size as word Description The function copies at most size characters from the string s2 to the string s1 If s2 contains fewer characters than size s1 is padded out with null characters up to the total length of the size characters txt mikroElektronika txt sub mikr strncpy txt txt_sub 4 7 copies first 4 characters form the string txt sub to Tox MikroElektronika 600 mikroBasic PRO for PIC32 strspn Prototype sub function strspn d
555. ype sub function Mmc Fat _ Assign dim byref filename as char 11 dim file cre attr as byte as word Description Assigns file for file operations read write delete All subsequent file operations will be applied on an assigned file Parameters filename name ofthe file that should be assigned for file operations File name should be in DOS 8 3 flle name extension format The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does no have to take care of that The file name and extension are case insensitive The library will convert 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 Bn mas Descriptor ofo Rao O e oxo Device internal use only never toundon disk File creation flag If file does not exist and this flag is set a new file with specified name will be created 1 if file already exists or file doe
556. ype sub procedure Mmc Fat Write dim byref fdata as byte 512 dim data len as 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 dim file contents as byte 42 Mmc Fat Write file contents 2 write data to the assigned file Mmc Fat Set File Date Prototype sub procedure Mmc Fat Set File Date dim year as word dim month as byte dim day as byte dim hours as byte dim mins as byte dim seconds as byte Description Sets the date time stamp Any subsequent file write operation will write this stamp to the currently assigned file s time date attributes Parameters year year attribute Valid values 1980 2107 month month attribute Valid values 1 12 da y day attribute Valid values 1 31 hours hours attribute Valid values 0 23 mins minutes attribute Valid values 0 59 seconds seconds attribute Valid values 0 59 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 Example Mic Fat Set File Date 2005 9 30 17 41 0 Notes None SSCS MikroElektronika 346 mikroBasic PRO for PIC32 Mmc Fat Get File Date Prototype sub procedure Mmc Fat Get File Date dim byref year as word dim byref month as byte dim byref day as byte dim b
557. yref hours as byte dim byref mins as 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 month attribute is returned through this parameter da y buffer to store day attribute to Upon function execution day attribute is returned through this parameter hours buffer to store hours attribute to Upon function execution hours attribute is returned through this parameter 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 dim year as word month day hours mins as byte Mmc Fat Get File Date year month day hours mins 34 MikroElektronika mikoBasic PRO for PIC32 Mmc Fat Get File Date Modified Prototype sub procedure Mmc Fat Get File Date Modified dim byref year as word dim byref month as byte dim byref day as byte dim byref hours as byte dim byref mins as 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 stor
558. yw 8 Nem C ux B hte Cunt 9 Delwy ms 503 Yow cen Change the moring spend bere ete LE Deiar oe aparcre osrrrr Configure AN pane e digital L Id tat 9 LDR wer 4 nnt ext Lesenict xt example led Cmd LC CLEAM Led Om LC CmPSoe or LEB Ow 1 5 txt LER Owt 1 5 0004 Peer medion Vot Ord LOR CLEAM LEB Own 1 1 tuta Teiwy 2008 Moving tent bd O torie ote 3 TrTdE Xx MAXX 2xXx7i n 3 m 3 F ropa sarg a Led Omdi LC WNIFT PIGNT e ae 3 Dran a Bove Dealer met 5 Mame Pine a 1x O onie TE Do Cmm re teerrtarteten C Ol for s ote 7 ouas m Loa Cmdi Lcb SWIFT LEFT See Sos se sove Pelri x3 Tee 0 e we i o feri o de tasca N Ai Te Beve Delay 2 Patna KD Deus mr m tot eres p 30 Joss 2 woregs a re Mecca Ne un arte w D ben aa ret m Pete I ANCE COS 22608 CD atm 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 dete
Download Pdf Manuals
Related Search
Related Contents
Folheto de modelo Satellite Pro C660-1D9 pastourelle n° 76 - secteur inter paroissial de sorgues – mode d`emploi Mode d`emploi du CHA13St Hustler® Sport CE Parts Manual HR2280/2180 Cordless Barcode Scanner Quick Guide OT200c User Guide Global Machinery Company LS1620 User's Manual Consumer Tool user manual - European Centre for Ecotoxicology VeriPlexTM Human Interferon 9-plex ELISA Kit Copyright © All rights reserved.