Mikrobasic Pro Pic32 v100-23513
Mikrobasic Pro Pic32 v100-23513
Mikrobasic Pro Pic32 v100-23513
Compiler
MikroElektronika
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 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
2
mikroBasic PRO for PIC32
MikroElektronika
3
mikoBasic PRO for PIC32
MikroElektronika
5
mikoBasic PRO for PIC32
MikroElektronika
6
mikroBasic PRO for PIC32
DoGetDateTime 159
DoGetVersion 159
KVA0_TO_KVA1 160
KVA1_TO_KVA0 160
KVA_TO_PA 160
PA_TO_KVA0 161
PA_TO_KVA1 161
CP0_GET 161
CP0_SET 162
EnableInterrupts 162
DisableInterrupts 162
Code Optimization 164
Constant folding 164
Constant 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
7
mikoBasic 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
Relational Operators in Expressions 219
Bitwise Operators 220
Bitwise Operators Overview 220
MikroElektronika
9
mikoBasic PRO for PIC32
MikroElektronika
10
mikroBasic PRO for PIC32
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
External 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_PartialImage 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_PartialImage 311
I²C Library 312
Library Routines 312
I2Cx_Init 312
I2Cx_Init_Advanced 313
I2Cx_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
MikroElektronika
13
mikoBasic PRO for PIC32
MikroElektronika
14
mikroBasic PRO for PIC32
Mmc_Read_Csd 342
Mmc_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_Delete 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
MikroElektronika
15
mikoBasic PRO for PIC32
MikroElektronika
17
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_getIpAddress 452
SPI_Ethernet_24j600_getGwIpAddress 453
SPI_Ethernet_24j600_getDnsIpAddress 453
SPI_Ethernet_24j600_getIpMask 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_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_FIll 468
SPI_Glcd_Set_Font 469
SPI_Glcd_Write_Char 470
SPI_Glcd_Write_Text 470
SPI_Glcd_Image 471
SPI_Glcd_PartialImage 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 Library 487
Library Routines 488
SPI_T6963C_config 489
MikroElektronika
19
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_PartialImage 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
T6963C_rectangle_round_edges_fill 520
T6963C_box 520
T6963C_circle 520
T6963C_circle_fill 521
T6963C_image 521
T6963C_PartialImage 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 534
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 dependencies 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
UARTx_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 573
MikroElektronika
22
mikroBasic PRO for PIC32
MikroElektronika
23
mikoBasic 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
ltrim 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
ldexp 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
Creating new source file 622
MikroElektronika
25
mikoBasic PRO for PIC32
MikroElektronika
26
mikroBasic PRO for PIC32
MikroElektronika
27
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.
MikroElektronika
28
mikroBasic PRO for PIC32
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 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 always 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.
MikroElektronika
29
mikoBasic PRO for PIC32
BY INSTALLING, COPYING, OR OTHERWISE USING SOFTWARE, YOU AGREE TO BE BOUND BY ALL TERMS
AND CONDITIONS OF THE LICENSE AGREEMENT.
Upon your acceptance of the terms and conditions of the License Agreement, mikroElektronika Associates grants you
the right to use Software in a way provided below.
This Software is owned by mikroElektronika Associates and is protected by copyright law and international copyright
treaty. Therefore, you must treat this Software like any other copyright material (e.g., a book).
You may transfer Software and documentation on a permanent basis provided. You retain no copies and the recipient
agrees to the terms of the License Agreement. Except as provided in the License Agreement, you may not transfer,
rent, lease, lend, copy, modify, translate, sublicense, time-share or electronically transmit or receive Software, media
or documentation. You acknowledge that Software in the source code form remains a confidential trade secret of
mikroElektronika Associates and therefore you agree not to modify Software or attempt to reverse engineer, decompile,
or disassemble it, except and only to the extent that such activity is expressly permitted by applicable law notwithstanding
this limitation.
If you have purchased an upgrade version of Software, it constitutes a single product with the mikroElektronika
Associates software that you upgraded. You may use the upgrade version of Software only in accordance with the
License Agreement.
LIMITED WARRANTY
Respectfully excepting the Redistributables, which are provided “as is”, without warranty of any kind, mikroElektronika
Associates warrants that Software, once updated and properly used, will perform substantially in accordance with the
accompanying documentation, and Software media will be free from defects in materials and workmanship, for a period
of ninety (90) days from the date of receipt. Any implied warranties on Software are limited to ninety (90) days.
mikroElektronika Associates’ and its suppliers’ entire liability and your exclusive remedy shall be, at mikroElektronika
Associates’ option, either (a) return of the price paid, or (b) repair or replacement of Software that does not meet
mikroElektronika Associates’ Limited Warranty and which is returned to mikroElektronika 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 FOR A 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 BUSINESS PROFITS AND BUSINESS INFORMATION, BUSINESS INTERRUPTION, OR
ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE PRODUCT
OR THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES, EVEN IF MIKROELEKTRONIKA
ASSOCIATES HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IN ANY 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 INTO A MIKROELEKTRONIKA ASSOCIATES SUPPORT SERVICES AGREEMENT, MIKROELEKTRONIKA
ASSOCIATES’ ENTIRE LIABILITY REGARDING SUPPORT SERVICES SHALL BE GOVERNED BY THE TERMS OF
THAT AGREEMENT.
GENERAL PROVISIONS
This statement may only be modified in writing signed by you and an authorised officer of mikroElektronika Associates.
If any provision of this statement is found void or unenforceable, the remainder will remain valid and enforceable
according to its terms. If any remedy provided is determined to have failed for its essential purpose, all limitations of
liability and exclusions of damages set forth in the Limited Warranty shall remain in effect.
This statement gives you specific legal rights; you may have others, which vary, from country to country. mikroElektronika
Associates reserves all rights not specifically granted in this statement.
mikroElektronika
Visegradska 1A,
11000 Belgrade,
Europe.
MikroElektronika
31
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 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 mikroICD(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.
You can choose between two registering methods, I work online or I work offline, based on your current internet
connection and click Request license key now button:
MikroElektronika
32
mikroBasic PRO for PIC32
If you choose I work online registering method, following page will be opened in your default browser:
MikroElektronika
33
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:
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.
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.
MikroElektronika
35
mikoBasic PRO for PIC32
CHAPTER 2
mikroBasic PRO for PIC32
Environment
MikroElektronika
36
mikroBasic PRO for PIC32
MikroElektronika
37
mikoBasic PRO for PIC32
File
File Menu Options
The File menu is the main entry point for manipulation with the source files.
File Description
Open a new editor window.
Save the active source file with the different name or change the file type.
Print Preview.
Print.
Exit IDE.
MikroElektronika
38
mikroBasic PRO for PIC32
Edit
Edit Menu Options
The Edit Menu contains commands for editing the contents of the current document.
Edit Description
Undo last change.
Find text in current file, in all opened files, or in files from desired folder.
MikroElektronika
39
mikoBasic PRO for PIC32
Advanced » Description
Comment selected code or put single line comment if there is no selection.
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.
Replace Text
Dialog box for searching for a text string in file and replacing it with another text string.
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.
Go To Line
Dialog box that allows the user to specify the line number at which the cursor should be positioned.
MikroElektronika
41
mikoBasic PRO for PIC32
View
View Menu Options
View Menu contains commands for controlling the on-screen display of the current project.
MikroElektronika
42
mikroBasic PRO for PIC32
View Description
Show/Hide Software Simulator / mikroICD (In-Circuit Debugger) Debug Windows.
Show/Hide Toolbars.
View Assembly.
View Listing.
View Statistics.
The Tools toolbar can easily be customized by adding new tools in Options(F12) window.
MikroElektronika
43
mikoBasic PRO for PIC32
Project
Project Menu Options
Project Menu allows the user to easily manipulate current project.
Project Description
Open New Project Wizard
Export Project.
Related topics: Keyboard shortcuts, Project Toolbar, Creating New Project, Project Manager, Project Settings
MikroElektronika
44
mikroBasic PRO for PIC32
Build
Build Menu Options
Build Menu allows the user to easily manage building and compiling process.
Build Description
Build active project.
Related topics: Keyboard shortcuts, Project Toolbar, Creating New Project, Project Manager, Project Settings
MikroElektronika
45
mikoBasic PRO for PIC32
Run
Run Menu Options
Run Menu is used to debug and test compiled code on a software or harware level.
Run Description
Start Software Simulator or mikroICD (In-Circuit Debugger).
Stop Debugger.
Run/Pause Debugger.
Step Into.
Step Over.
Step Out.
Run To Cursor.
Toggle Breakpoint.
Clear Breakpoints.
MikroElektronika
46
mikroBasic PRO for PIC32
Tools
Tools Menu Options
Tools Menu contains a number of applications designed to ease the use of compiler and included library routines.
Tools Description
Run mikroElektronika Programmer.
Generate HTML code suitable for publishing source code on the web.
MikroElektronika
47
mikoBasic PRO for PIC32
Help
Help Menu Options
Help Description
Оpen Help File.
MikroElektronika
48
mikroBasic PRO for PIC32
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):
- The Code Editor features adjustable Syntax Highlighting, Code Folding, Code Assistant, Parameters Assistant, Spell
Checker, Auto Correct for common typos and Code Templates (Auto Complete).
- The Code Explorer is at your disposal for easier project management.
- The Project Manager alows multiple project management
- General project settings can be made in the Project Settings window
- Library manager enables simple handling libraries being used in a project
- The Messages Window displays all information, messages and errors detected during compiling and linking.
- The source-level Software Simulator lets you debug executable logic step-by-step by watching the program flow.
- The New Project Wizard is a fast, reliable, and easy way to create a project.
- Help files are syntax and context sensitive.
- Like in any modern Windows application, you may customize the layout of 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).
MikroElektronika
49
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
MikroElektronika
50
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 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 and Uncomment Icon from
the Advanced Edit Toolbar.
Code Folding
Code folding is IDE feature which allows users to selectively hide and display sections of a source file. In this way it is
easier to manage large regions of code within one window, while still viewing only those subsections of the code that
are relevant during a particular editing session.
While typing, the code folding symbols ( and ) appear automatically. Use the folding symbols to hide/unhide the
code subsections.
MikroElektronika
51
mikoBasic PRO for PIC32
If you place a mouse cursor over the tooltip box, the collapsed text will be shown in a tooltip style box.
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.
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.
Bookmarks
Bookmarks make navigation through a large code easier. To set a bookmark, use Ctrl+Shift+number. 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 mode editing is sometimes referred to as block mode editing as the act of selecting text forms a rectangle.
To enter this mode, press Alt + Left mouse button, drag the mouse towards the desired direction thus selecting the
text.
Editor Colors
MikroElektronika
53
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.
This option is already set up to automatically correct some words. For example, if you type whiel, it will be corrected
to while when you press the spacebar:
MikroElektronika
54
mikroBasic PRO for PIC32
The user can easily add its common typos by entering original typo, for example btye, 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.
MikroElektronika
55
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:
You can add your own templates to the list by entering the desired keyword, description and code of your template in
appropriate boxes.
Autocomplete macros can retreive system and project information:
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.
Icon Description
MikroElektronika
57
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.
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.
MikroElektronika
58
mikroBasic PRO for PIC32
Icon Description
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
MikroElektronika
59
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.
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 .emcl) 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 and all libraries will be selected.
In case none library is needed in a project, press the button Clear All and all libraries will be cleared from the
project.
Icon Description
Refresh Library by scanning files in “Uses” folder. Useful when new libraries are added by copying files to
“Uses” folder.
Rebuild all available libraries. Useful when library sources are available and need refreshing.
MikroElektronika
61
mikoBasic PRO for PIC32
Upon package installation, a new node with the package name will be created in the Library Manager. For example:
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:
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.
Statistics
After successful compilation, you can review statistics of your code. Click the Statistics Icon .
MikroElektronika
63
mikoBasic PRO for PIC32
Variables
Displays variables sorted by addresses.
MikroElektronika
64
mikroBasic PRO for PIC32
SFR Locations
Displays list of used SFR locations.
MikroElektronika
65
mikoBasic PRO for PIC32
Functions
Sorts and displays functions in various ways.
MikroElektronika
66
mikroBasic PRO for PIC32
MikroElektronika
67
mikoBasic PRO for PIC32
Function Tree
Displays Function Tree with the relevant data for each function.
MikroElektronika
68
mikroBasic PRO for PIC32
Memory Summary
Displays summary of RAM and ROM memory in a pie-like form.
MikroElektronika
69
mikoBasic PRO for PIC32
Messages Window
Messages Window displays various informations and notifications about the compilation process.
It reports for example, time needed for preprocessing, compilation and linking; used RAM and ROM space, generated
baud rate with error percentage, etc.
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.
Double click the message line in the Message Window to highlight the line where the error was encountered.
MikroElektronika
70
mikroBasic PRO for PIC32
Quick Converter
Quick Converter enables the user to easily transform numbers from one base to another.
User can convert integers of various sizes (8, 16 or 32 bits), signed and unsigned, using different representation
(decimal, hexadecimal, binary and character).
Also, Quick Converter features float point numbers conversion from/to Float Decimal, Float 32bit (IEEE), Float 32bit
(Microchip) and Radix 1.15 for dsPIC family of MCUs.
Macro Editor
A macro is a series of keystrokes that have been 'recorded' in the order performed. A macro allows you to 'record' a
series of keystrokes and then 'playback', or repeat, the recorded keystrokes.
MikroElektronika
71
mikoBasic PRO for PIC32
Icon Description
Stops capturing keystrokes that was started when the Start Recording command was selected.
New macro.
Delete macro.
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:
MikroElektronika
72
mikroBasic PRO for PIC32
Now, navigate to the desired image file, and simply add it:
Next, right click the added file, and choose Set As Preview Image:
MikroElektronika
73
mikoBasic PRO for PIC32
Once you have added the image, it will appear in the Image Preview Window:
Also, you can add multiple images to the Image Files node, but only the one that is set will be automatically displayed
in the Image Preview Window upon opening the project.
By changing the Image Preview Window size, displayed image will be fit by its height in such a way that its proportions
will remain intact.
Toolbars
This section provides an overview of the toolbars available in 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
74
mikroBasic PRO for PIC32
File Toolbar
Icon Description
Print Preview.
Print.
Edit Toolbar
Icon Description
MikroElektronika
75
mikoBasic PRO for PIC32
Icon Description
Go to ending delimiter.
Go to line.
Generate HTML code suitable for publishing current source code on the web.
Find/Replace Toolbar
Icon Description
Replace text.
MikroElektronika
76
mikroBasic PRO for PIC32
Project Toolbar
Icon Description
New project.
Open Project
Save Project
Build Toolbar
Icon Description
MikroElektronika
77
mikoBasic PRO for PIC32
Debug Toolbar
Icon Description
Run/Pause Debugger.
Stop Debugger.
Step Into.
Step Over.
Step Out.
Run To Cursor.
Toggle Breakpoint.
Clear Breakpoints.
Styles Toolbar
Styles toolbar allows you to easily change colors of your workspace.
MikroElektronika
78
mikroBasic PRO for PIC32
Tools Toolbar
Icon Description
EEPROM
ASCII Chart
Options menu
Tip : The Tools toolbar can easily be customized by adding new tools in Options menu window.
View Toolbar
View Toolbar provides access to assembly code, listing file and statistics windows.
Icon Description
MikroElektronika
79
mikoBasic PRO for PIC32
Layout Toolbar
Styles toolbar allows you to easily customize workspace through a number of different IDE layouts.
Icon Description
Help Toolbar
Icon Description
How To Register.
MikroElektronika
80
mikroBasic PRO for PIC32
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.
MikroElektronika
81
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.
Step 4: To dock the window in the position indicated, release the mouse button.
Tip : To move a dockable window without snapping it into place, press CTRL while dragging it.
Saving Layout
Once you have a window layout that you like, you can save the layout by typing the name for the layout and pressing
the Save Layout Icon .
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 .
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.
MikroElektronika
82
mikroBasic PRO for PIC32
When an auto-hidden window loses focus, it automatically slides back to its tab on the edge of the IDE. While a window
is auto-hidden, its name and icon are visible on a tab at the edge of the IDE. To display an auto-hidden window, move
your pointer over the tab. The window slides back into view and is ready for use.
Options
Options menu consists of three tabs: Code Editor, Tools and Output settings.
Code editor
The Code Editor is advanced text editor fashioned to satisfy needs of professionals.
Tools
The 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 Tool0 - Tool9.
MikroElektronika
83
mikoBasic PRO for PIC32
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 (*.emcl) on any MCU (when this box is checked), or for a
selected MCU (when this box is left unchecked).
For more information on creating new libraries, see Creating New Library.
MikroElektronika
84
mikroBasic PRO for PIC32
MikroElektronika
85
mikoBasic PRO for PIC32
Integrated Tools
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 from Tools toolbar.
MikroElektronika
86
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 › ASCII chart or by clicking the View ASCII Chart Icon from Tools toolbar.
MikroElektronika
87
mikoBasic PRO for PIC32
EEPROM Editor
The EEPROM Editor is used for manipulating MCU's EEPROM memory. You can launch it from the drop-down menu
Tools › EEPROM Editor.
When you run mikroElektronika programmer software from mikroBasic PRO for PIC32 IDE - project_name.hex file
will be loaded automatically while ihex file must be loaded manually.
MikroElektronika
88
mikroBasic PRO for PIC32
MikroElektronika
89
mikoBasic 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.
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.
MikroElektronika
90
mikroBasic PRO for PIC32
MikroElektronika
91
mikoBasic PRO for PIC32
UDP Terminal
The mikroBasic PRO for PIC32 includes the UDP Terminal. You can launch it from the drop-down menu Tools › UDP
Terminal.
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 from Tools
toolbar.
MikroElektronika
93
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.
By clicking the button you are prompted to enter a name for the comment:
MikroElektronika
94
mikroBasic PRO for PIC32
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 button.
There are four predefined event types you can apply to an Active Comment:
1. OnLeftClick + Alt
2. OnRightClick
3. OnDoubleClick
4. OnMouseOver
MikroElektronika
95
mikoBasic PRO for PIC32
First three event types can have one of the following three actions:
Attributes are tightly bounded with events. For example, you can not have OnLeftClick + Alt -> OpenFile if there is no
file attribute set, or if there is no file added to project. The same behavior applies to image attribute.
Let's start editing our Active Comment by entering some valid web address in the URL field:
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:
MikroElektronika
96
mikroBasic PRO for PIC32
You can see the contents of the created XML file by expanding Active Comment Editor:
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 or button.
MikroElektronika
97
mikoBasic PRO for PIC32
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:
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
PreviewImage action, and OnLeftClick + Alt will be assigned to OpenUrl action:
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:
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:
MikroElektronika
99
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:
Notice that when you stop typing, Add Comment To Project button will show. By clicking on it, you will open Active
Comment Editor and comment name will be already set, so you need only to adjust attributes and settings.
After saving you can always edit your active comment by Active Comment Editor, and switch between comments
directly from editor.
If you remove a file from the Project Manager or add an Active Comment File which contains information about the file
which is no longer in project, and hover the mouse over the comment, you will be prompted to either add file to project
or remove event definition from Active Comment for this file:
If you remove active comment file from the Project Manager, you'll receive this message:
MikroElektronika
100
mikroBasic PRO for PIC32
If you click No, comment will be removed from the source code.
MikroElektronika
101
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:
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:
In the empty input boxes, current location and the destination folder of the desired project should be entered.
By default, currently active project will be set for export. You can change it any time by clicking the Open Button .
Once you have entered the appropriate data, click Export Project button. After exporting is done, and if everything was
OK, you'll receive a message:
Now, Export Project has copied all project files into desired folder and changed project search paths, so you can easily
move the entire folder to another location and run the project.
MikroElektronika
103
mikoBasic PRO for PIC32
Jump To Interrupt
Lets you choose which interrupt you want to jump to.
You can call Jump To Interrupt by selecting Run › Jump To Interrupt from the drop-down menu, or by clicking the Jump
To Interrupt Icon , from the Watch Values Window.
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
of characters matches that series of characters in the target string, so the pattern “short” would match “short”
in the target string. You can cause characters that normally function as metacharacters or escape sequences to be
interpreted by preceding them with a backslash “\”.
For instance, metacharacter “^” matches beginning of string, but “\^” matches character “^”, and “\\” matches
“\”, etc.
Examples:
Escape sequences
Characters may be specified using an escape sequences: “\n” matches a newline, “\t” a tab, etc. More generally,
\xnn, where nn is a string of hexadecimal digits, matches the character whose ASCII value is nn.
If you need wide (Unicode) character code, you can use ‘\x{nnnn}’, where ‘nnnn’ - one or more hexadecimal
digits.
Examples:
Character classes
You can specify a character class, by enclosing a list of characters in [], which will match any of the characters from
the list. If the first character after the “[“ is “^”, the class matches any character not in the list.
MikroElektronika
105
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:
Metacharacters
Metacharacters are special characters which are the essence of regular expressions. There are different types of
metacharacters, described below.
Examples:
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
Example:
routi\de - matches strings like 'routi1e', 'routi6e' and so on, but not 'routine', 'routime' and
so on.
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.
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.
MikroElektronika
107
mikoBasic PRO for PIC32
Examples:
A little explanation about "greediness". "Greedy" takes as many as possible, "non-greedy" takes as few as possible.
For example, 'b+' and 'b*' applied to string 'abbbbc' return 'bbbb', 'b+?' returns 'b', 'b*?' returns empty
string, 'b{2,3}?' returns 'bb', 'b{2,3}' returns 'bbb'.
Metacharacters - Alternatives
You can specify a series of alternatives for a pattern using "|" to separate them, so that bit|bat|bot will match
any of "bit", "bat", or "bot" in the target string as would "b(i|a|o)t)". The first alternative includes everything
from the last pattern delimiter ("(", "[", or the beginning of the pattern) up to the first "|", and the last alternative
contains everything from the last "|" to the next pattern delimiter. For this reason, it's common practice to include
alternatives in parentheses, to minimize confusion about where they start and end.
Alternatives are tried from left to right, so the first alternative found for which the entire expression matches, is the
one that is chosen. This means that alternatives are not necessarily greedy. For example: when matching rou|rout
against "routine", only the "rou" part will match, as that is the first alternative tried, and it successfully matches the
target string (this might not seem 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:
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:
Metacharacters - Backreferences
Metacharacters \1 through \9 are interpreted as backreferences. \ matches previously matched subexpression #.
Examples:
MikroElektronika
108
mikroBasic PRO for PIC32
Keyboard Shortcuts
Below is a complete list of keyboard shortcuts available in mikroBasic PRO for PIC32 IDE.
MikroElektronika
109
mikoBasic PRO for PIC32
MikroElektronika
110
mikroBasic PRO for PIC32
CHAPTER 3
mikroBasic PRO for PIC32
Command Line Options
Usage: mBPIC32.exe [-<opts> [-<opts>]] [<infile> [-<opts>]] [-<opts>]]
Infile can be of *.mbas, *.emcl and *.pld type.
MikroElektronika
111
mikoBasic PRO for PIC32
Example:
MikroElektronika
112
mikroBasic PRO for PIC32
CHAPTER 4
mikroICD (In-Circuit Debugger)
Introduction
The mikroICD is a highly effective tool for a Real-Time debugging on hardware level. The mikroICD 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.
MikroElektronika
113
mikoBasic PRO for PIC32
If you have appropriate hardware and software for using the mikroICD select mikroICD Debug Build Type before
compiling the project.
Now, compile the project by pressing Ctrl + F9, or by pressing Build Icon on Build Toolbar.
Run the mikroICD by selecting Run › Start Debugger from the drop-down menu or by clicking the Start Debugger
Icon . Starting the Debugger makes more options available: Step Into, Step Over, Run to Cursor, etc. Line that is
to be executed is color highlighted (blue by default). There is also notification about the program execution and it can
be found in the Watch Window (yellow status bar). Note that some functions take more time to execute; execution is
indicated with "Running..." message in the Watch Window Status Bar.
MikroElektronika
114
mikroBasic PRO for PIC32
Function Toolbar
Name Description
Key Icon
Run To Cursor Executes the program until reaching the cursor position. Ctrl + F8
MikroElektronika
115
mikoBasic PRO for PIC32
First you have to write a program. We will show how the mikroICD works using this example:
program Lcd_Test
main:
ADPCFG = 0xFFFF
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 mikroICD. After the mikroICD initialization a
blue active line should appear.
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.
MikroElektronika
117
mikoBasic PRO for PIC32
Step Into [F7], Step Over [F8] and Step Out [Ctrl+F8] are mikroICD debugger functions that are used in stepping
mode. There is also a Real-Time mode supported by the mikroICD. Functions that are used in the Real-Time mode
are Run/Pause Debugger [F6] and Run to cursor [F4]. Pressing F4 executes the code until the program reaches the
cursor position line.
Run(Pause) Debugger [F6] and Toggle Breakpoints [F5] are mikroICD 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.
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 mikroICD 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:
MikroElektronika
119
mikoBasic 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.
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 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 button.
MikroElektronika
120
mikroBasic PRO for PIC32
Also, it is possible to add all variables in the Watch Values Window by clicking button.
To remove a variable from the Watch Values Window, just select the variable that you want to remove and then click
the button, or press the Delete key.
It is possible to remove all variables from the Watch Values Window by clicking button.
You can also expand/collapse complex variables i.e. struct type variables, strings, etc, by clicking the appropriate
button ( or ) beside variable name.
Double clicking a variable or clicking the 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.
An item's value can also be changed by double clicking item's value field and typing the new value directly.
MikroElektronika
121
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.
mikroICD Specific: RAM window content will be written to the MCU before the next instruction execution.
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.
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.
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:
- Reads data from MCU's internal EEPROM memory and loads it up into the EEPROM window.
- Writes data from the EEPROM window into MCU's internal EEPROM memory.
MikroElektronika
123
mikoBasic PRO for PIC32
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.
- 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.
MikroElektronika
124
mikroBasic PRO for PIC32
CHAPTER 5
Software Simulator Overview
MikroElektronika
125
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 simulate operations of the Microchip PIC32 MCUs and assist the users in debugging code written for these
devices.
Upon completion of writing your program, choose Release build Type in the Project Settings window:
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 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
- 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.
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 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 button.
MikroElektronika
127
mikoBasic PRO for PIC32
Also, it is possible to add all variables in the Watch Values Window by clicking button.
To remove a variable from the Watch Values Window, just select the variable that you want to remove and then click
the button, or press the Delete key.
It is possible to remove all variables from the Watch Values Window by clicking button.
You can also expand/collapse complex variables i.e. struct type variables, strings, etc, by clicking the appropriate
button ( or ) beside variable name.
Double clicking a variable or clicking the 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.
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 changed items colored red. The user can edit and
change the values in the RAM window.
mikroICD Specific: RAM window content will be written to the MCU before the next instruction execution.
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.
MikroElektronika
129
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.
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:
- Reads data from MCU's internal EEPROM memory and loads it up into the EEPROM window.
- Writes data from the EEPROM window into MCU's internal EEPROM memory.
MikroElektronika
130
mikroBasic PRO for PIC32
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.
- 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.
MikroElektronika
131
mikoBasic PRO for PIC32
Function Toolbar
Name Description
Key Icon
Run To Cursor Executes the program until reaching the cursor position. Ctrl + F8
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:
MikroElektronika
133
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.
Function recursion is not supported because of no easily-usable stack and limited memory PIC32 Specific
mikroBasic PRO for PIC32 has additional set of keywords that do not belong to the standard Basic language
keywords:
- code
- data
- rx
- sfr
- at
MikroElektronika
134
mikroBasic PRO for PIC32
- sbit
- bit
- iv
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 (Ctrl+Space in the Code Editor).
First one is equal to the name of selected device for the project. For example:
#IFDEF P32MX460F512L
...
#ENDIF
#IFDEF PIC32
...
#ENDIF
MikroElektronika
135
mikoBasic PRO for PIC32
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.B1
To access this bit in your code by its name, you can write something like this:
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 B0, B1, … , B15, or 0, 1, … 15, with 15 being the most significant bit:
In this way, if the target bit changes its position in the register, you cannot be sure that you are invoking the appropriate bit.
This kind of selective access is an intrinsic feature of mikroBasic PRO for PIC32 and can be used anywhere in the code.
Identifiers B0–B15 are not case sensitive and have a specific namespace.
You may override them with your own members B0–B15 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:
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
...
implements
....
end.
In the main program you have to specify to which register this sbit points to, for example:
program MyProgram
...
dim Abit as sbit at PORTB.0 ‘ 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 sfr for declaration
of Abit, because we are pointing it to PORTB which is defined as a sfr variable.
In case we want to declare a bit over a variable which is not defined as sfr, then the keyword sfr is not necessary,
for example:
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.
MikroElektronika
137
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
...
dim 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.
Note:
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 connects the
function with specific interrupt vector. For more information on IVT refer to the PIC32 Family Reference Manual.
Configuring Interrupts
The PIC32MX interrupt controller can be configured to operate in one of two modes:
- Single Vector mode - all interrupt requests will be serviced at one vector address (mode out of reset).
- Multi-Vector mode - interrupt requests will be serviced at the calculated vector address.
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 0x9FC01000E). The exact formula for Single Vector mode is as follows: Single Vector Address =
EBase + 0x200.
In this mode, the CPU vectors to the unique address for each vector number. Each vector is located at a
specific offset, with respect to a base address specified by the EBase register in the CPU.
The individual vector address offset is determined by the following equation: EBase + (Vector_Number x
Vector_Space) + 0x200.
By default, the compiler configures interrupts in the Multi Vector mode, with the EBase address set to
0x9FC01000 and vector spacing of 32.
Configuring the Interrupt operating mode is performed in the Edit Project window.
MikroElektronika
139
mikoBasic PRO for PIC32
Interrupt Priorities
In the Multi Vector Mode, the user is able to assign a group priority and group subpriority level to each of the
interrupt vectors. The user-selectable priority levels range from 1 (the lowest priority) to 7 (the highest).
If an interrupt priority is set to zero, the interrupt vector is disabled for both interrupt and wake-up purposes. Interrupt
vectors with a higher priority level preempt lower priority interrupts.
The subpriority will cause that when two interrupts with the same priority are pending, the interrupt with the highest
subpriority will be handled first. The user-selectable subpriority levels range from 0 (the lowest subpriority) to 3 (the
highest).
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.
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.
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.
MikroElektronika
140
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:
User can explicitly declare starting interrupt routine address using org directive:
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.
MikroElektronika
141
mikoBasic PRO for PIC32
Interrupt Example
Here is a simple example of handling the interrupts from Timer1 (if no other interrupts are allowed):
program Timer1_interrupt
main:
AD1PCFG = 0xFFFF ‘ Initialize AN pins as digital
TRISB = 0 ‘ initialize PORTB as output
LATB = 0xAAAA ‘ Initialize PORTB value
end.
MikroElektronika
142
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 KSEG0 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.
Be careful when using absolute directive, as you may overlap two variables by accident. For example:
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.
‘ Constant 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:
MikroElektronika
143
mikoBasic PRO for PIC32
org directive can be used with main routine too. For example:
program Led_Blinking
Directive orgall
Use the orgall 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.
- Lo
- Hi
- Higher
- Highest
- LoWord
- HiWord
- Inc
- Dec
- Chr
- Ord
- 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
- ClrWdt
- DisableContextSaving
- SetFuncCall
- SetOrg
- DoGetDateTime
- DoGetVersion
- KVA0_TO_KVA1
- KVA1_TO_KVA0
- KVA_TO_PA
- PA_TO_KVA0
- PA_TO_KVA1
- CP0_Get
- CP0_Set
- EnableInterrupts
- DisableInterrupts
MikroElektronika
145
mikoBasic PRO for PIC32
Lo
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.
Parameters - number: input number
Returns Lowest 8 bits (byte) of number, bits 7..0.
Requires Arguments must be variable of scalar type (i.e. Arithmetic Types and Pointers).
Example d = 0x12345678;
tmp = Lo(d); // Equals 0x78
Hi
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.
Parameters - number: input value
Returns Returns next to the lowest byte of number, bits 8..15.
Requires Arguments must be variable of scalar type (i.e. Arithmetic Types and Pointers).
Example d = 0x12345678;
tmp = Hi(d); // Equals 0x56
MikroElektronika
146
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.
Requires Arguments must be variable of scalar type (i.e. Arithmetic Types and Pointers).
Example 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.
Requires Arguments must be variable of scalar type (i.e. Arithmetic Types and Pointers).
Example d = 0x12345678;
tmp = Highest(d); // Equals 0x12
MikroElektronika
147
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 val – it merely
returns 16 bits as found in register.
Parameters:
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 val – it merely
returns 16 bits as found in register.
Parameters:
MikroElektronika
148
mikroBasic PRO for PIC32
Inc
Prototype sub procedure Inc(dim byref par as longint)
Description Increases parameter par by 1.
Parameters - par: value which will be incremented by 1
Returns Nothing.
Requires Nothing.
Example p = 4
Inc(p) ‘ p is now 5
Notes None.
Dec
Prototype sub procedure Inc(dim byref par as longint)
Description Increases parameter par by 1.
Parameters - par: value which will be incremented by 1
Returns Nothing.
Requires Nothing.
Example p = 4
Inc(p) ‘ p is now 3
Notes None.
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.
Parameters - code: input character
Returns Returns a character associated with the specified character code_.
Requires Nothing.
Example c = Chr(10) ‘ returns the linefeed character
Notes None.
MikroElektronika
149
mikoBasic PRO for PIC32
Ord
Prototype sub 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
Returns ASCII code of the character.
Requires Nothing.
Example c = Ord(“A”) ‘ returns 65
Notes None.
SetBit
Prototype sub procedure SetBit(dim byref register_ as word, dim rbit as byte)
Description Function sets the bit rbit of register_. Parameter rbit needs to be a variable or literal with
value 0..15. For more information on register identifiers see Predefined Globals and Constants .
This is an “inline” routine; the code is generated in the place of the call.
Parameters - register_: desired register
- rbit: desired bit
Returns Nothing.
Requires Nothing.
Example SetBit(PORTB, 2) ‘ Set RB2
Notes None.
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
Returns Nothing.
Requires Nothing.
Example ClearBit(PORTC, 7) ‘ Clear RC7
Notes None.
MikroElektronika
150
mikroBasic PRO for PIC32
TestBit
Prototype sub function TestBit(dim register_, rbit as byte) as byte
Description Function tests if the bit rbit of register is set. If set, function returns 1, otherwise returns 0.
Parameter rbit needs to be a variable or literal with value 0..7. See Predefined globals and constants
for more information on register identifiers.
This is an “inline” routine; code is generated in the place of the call, so the call doesn’t count against
the nested call limit.
Parameters - register_: desired register
- rbit: desired bit
Returns If the bit is set, returns 1, otherwise returns 0.
Requires Nothing.
Example flag = TestBit(PORTE, 2) ‘ 1 if RE2 is set, otherwise 0
Notes None.
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
Returns Nothing.
Requires Nothing.
Example Delay_us(1000) ‘ One millisecond pause
Notes None.
MikroElektronika
151
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 “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_ms: delay time in milliseconds. Valid values: constant values, range of applicable constants
depends on the oscillator frequency
Returns Nothing.
Requires Nothing.
Example Delay_ms(1000); /* One second pause */
Notes For generating delays with variable as input parameter use the Vdelay_ms routine.
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.
Parameters Time_ms: delay time in milliseconds
Returns Nothing.
Requires Nothing.
Example pause = 1000
‘ ...
Vdelay_ms(pause) ‘ ~ one second pause
Notes None.
MikroElektronika
152
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
Returns Nothing.
Requires Nothing.
Example pause = 1000
fosc = 10000
Delay_Cyc
Prototype sub procedure Delay_Cyc(dim x, y as word)
Description Creates a delay based on MCU clock. Delay lasts for x*16384 + y MCU clock cycles.
Parameters x: NumberOfCycles divided by 16384
y: remainder of the NumberOfCycles/16384 division
Returns Nothing.
Requires Nothing.
Example Delay_Cyc(1, 10); /* 1x16384 + 10 = 16394 cycles pause */
Notes 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
Prototype sub procedure Delay_Cyc_Long(dim CycNo as word)
Description Creates a delay based on MCU clock. Delay lasts for CycNo MCU clock cycles.
Parameters - CycNo: number of cycles
Returns Nothing.
Requires Nothing.
Example Delay_Cyc_Long(16394); // 16394 cycles pause
Notes 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
153
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.
Parameters None.
Returns Device clock in kHz, rounded to the nearest integer.
Requires Nothing.
Example clk = Clock_kHz();
Notes 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.
Parameters None.
Returns Device clock in MHz, rounded to the nearest integer.
Requires Nothing.
Example clk = Clock_Mhz();
Notes None.
Get_Fosc_kHz
Prototype sub function Get_Fosc_kHz() as longint
Description Function returns device clock in kHz, rounded to the nearest integer.
Parameters None.
Returns Device clock in kHz.
Requires Nothing.
Example clk = Get_Fosc_kHz();
Notes Get_Fosc_kHz is a library function rather than a built-in routine; it is presented in this topic for the
sake of convenience.
MikroElektronika
154
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.
Requires Nothing.
Example dim clk_per_cyc as word
...
clk_per_cyc = Get_Fosc_Per_Cyc()
Notes None.
Reset
Prototype sub procedure Reset()
Description This procedure is equal to assembler instruction reset.
Parameters None.
Returns Nothing.
Requires Nothing.
Example Reset() ‘ Resets the MCU
Notes None.
ClrWdt
Prototype sub procedure ClrWdt()
Description This procedure is equal to assembler instruction clrwdt.
Parameters None.
Returns Nothing.
Requires Nothing.
Example ClrWdt() ‘ Clears WDT
Notes None.
MikroElektronika
155
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.
Returns Nothing.
Requires This routine must be called from main.
Example DisableContextSaving() ‘ instruct the compiler not to automatically perform
context-switching
Notes None.
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 SetFuncCall directive in main will make compiler link specified routines always.
Parameters - FuncName: function name
Returns Nothing.
Requires Nothing.
Example sub procedure first(p, q as byte)
...
SetFuncCall(second) ‘ let linker know that we will call the routine
‘second’
...
end sub
Notes None.
MikroElektronika
156
mikroBasic PRO for PIC32
SetOrg
Prototype sub procedure SetOrg(dim RoutineName as string, dim address as longint)
Description Use the SetOrg() routine to specify the starting address of a routine in ROM.
Parameters - RoutineName: routine name
- address: starting address
Returns Nothing.
Requires This routine must be called from main.
Example SetOrg(UART1_Write, 0x1234)
Notes None.
DoGetDateTime
Prototype sub function DoGetDateTime() as string
Description Use the DoGetDateTime() to get date and time of compilation as string in your code.
Parameters None.
Returns String with date and time when this routine is compiled.
Requires Nothing.
Example str = DoGetDateTime()
Notes None.
DoGetVersion
Prototype sub function DoGetVersion() as string
Description Use the DoGetDateTime() to get date and time of compilation as string in your code.
Parameters None.
Returns String with current compiler version.
Requires Nothing.
Example str = DoGetVersion() ‘ for example, str will take the value of ‘8.2.1.6’
Notes None.
MikroElektronika
157
mikoBasic PRO for PIC32
KVA0_TO_KVA1
Prototype sub function KVA0_TO_KVA1(dim Address as longword) as longword
Description Function converts virtual address from KSEG0 to the virtual address in the KSEG1.
Parameters Desired Virtual address in the KSEG0.
Returns Virtual address in the KSEG1.
Requires Nothing.
Example address = KVA0_TO_KVA1(0x9FC00000)
Notes None.
KVA1_TO_KVA0
Prototype sub function KVA1_TO_KVA0(dim Address as longword) as longword
Description Function converts virtual address from KSEG1 to the virtual address in the KSEG0.
Parameters Desired Virtual address in the KSEG1.
Returns Virtual address in the KSEG0.
Requires Nothing.
Example address = KVA1_TO_KVA0(0xBFC00000)
Notes None.
KVA_TO_PA
Prototype sub function KVA_TO_PA(dim Address as longword) as longword
Description Function converts virtual address from any Kernel segment to the appropriate physical address.
Parameters Desired Virtual address.
Returns Appropriate physical address.
Requires Nothing.
Example address = KVA_TO_PA(0xBFC00000)
Notes None.
MikroElektronika
158
mikroBasic PRO for PIC32
PA_TO_KVA0
Prototype sub function PA_TO_KVA0(dim Address as longword) as longword
Description Function converts physical address to the virtual address in the KSEG0.
Parameters Desired physical address.
Returns Appropriate virtual address in the KSEG0.
Requires Nothing.
Example address = PA_TO_KVA0(0x1D000000)
Notes None.
PA_TO_KVA1
Prototype sub function PA_TO_KVA1(dim Address as longword) as longword
Description Function converts physical address to the virtual address in the KSEG1.
Parameters Appropriate virtual address in the KSEG1.
Returns Virtual address in the KSEG1.
Requires Nothing.
Example address = PA_TO_KVA1(0x1D000000)
Notes None.
CP0_GET
Prototype sub function CP0_GET(dim const register as TCP0REG) 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.
Requires Nothing.
Example dim register_value as longword
register_value = CP0_GET(CP0_CONFIG)
Notes None.
MikroElektronika
159
mikoBasic PRO for PIC32
CP0_SET
Prototype sub procedure CP0_SET(dim const register as TCP0REG, dim Value as
longword)
Description 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.
Returns Nothing.
Requires Nothing.
Example CP0_SET(CP0_CONFIG, 0x1A2C0000);
Notes None.
EnableInterrupts
Prototype sub procedure EnableInterrupts()
Description Function enables interrupts.
Parameters None.
Returns Nothing.
Requires Nothing.
Example EnableInterrupts();
Notes None.
DisableInterrupts
Prototype sub procedure DisableInterrupts()
Description Function disables interrupts.
Parameters None.
Returns Nothing.
Requires Nothing.
Example DisableInterrupts();
Notes None.
Coprocessor Registers
CP0_HWRENA CP0_BADVADDR CP0_COUNT CP0_COMPARE CP0_STATUS
CP0_INTCTL CP0_SRSCTL CP0_SRSMAP CP0_CAUSE CP0_EPC
CP0_PRID CP0_EBASE CP0_CONFIG CP0_CONFIG1 CP0_CONFIG2
CP0_CONFIG3 CP0_DEBUG CP0_TRACECONTROL CP0_TRACECONTROL2 CP0_USERTRACEDATA
MikroElektronika
160
mikroBasic PRO for PIC32
MikroElektronika
161
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 ->
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.
Stack allocation
Temporary registers ("Stacks") are being used more rationally, allowing VERY complex expressions to be evaluated
with a minimum stack consumption.
Related topics: SSA Optimization, PIC32 specifics, mikroBasic PRO for PIC32 specifics, Memory type specifiers
MikroElektronika
162
mikroBasic PRO for PIC32
An SSA-based compiler modifies the program representation so that every time a variable is assigned in the original
program, a new version of the variable is created.
A new version of the variable is distinguished (renamed) by subscripting the variable name with its version number or
an index, so that every definition of each variable in a program becomes unique.
At a joining point of the control flow graph where two or more different definitions of a variable meet, a hypothetical
function 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.
program Example
main:
SSA_Test(5,5)
end.
With SSA enabled, sub procedure SSA_Test this example is consisted of 3 asm instructions:
Without SSA enabled, sub procedure SSA_Test this example is consisted of 5 asm instructions :
- Routines should not contain too many parameters (not more than 4 words).
- Don’t change the value of the parameter in the function body (it is better to use a new local variable).
- If the function1 parameters are passed as function2 parameters, then parameter order should
remain the same:
end sub
- Large amount of nested loops and complex structures as its members should be avoided.
- When writing a code in assembly, keep in mind that there are registers reserved exclusively for
routine parameters.
- Using goto and label statements in nested loops should be avoided.
- Obtaining address of the local variable with the global pointer and using it to alter the variable’s address
should be avoided.
Notes:
- emcl 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
Because of this, user must be very careful when writing asm code as existing values in the working registers
used by SSA optimization can be overwritten.
To avoid this, it is recommended that user includes desired asm code in a separate routine.
Debugging Notes
SSA also influences the code debugging in such a way that the local variables will be available in the Watch Window
only in those parts of the procedure where they have useful value (eg. on entering the procedure, variable isn’t available
until its definition).
Variables can be allocated in one part of the procedure in register W4, and in another part of the procedure in register
W2, if the optimizer estimates that it is better that way. That means that the local variable has no static address.
main:
SSA_Test()
end.
Related topics: Code Optimization, PIC32 Specifics, mikroBasic PRO for PIC32 specifics, Memory type specifiers
MikroElektronika
165
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 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.
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.
- Cache Enabled,
- Prefetch enabled (for executable code and constants),
- Flash waitstates set for specified oscillator frequency,
- Executable code allocated in the KSEG0,
- 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.
MikroElektronika
167
mikoBasic PRO for PIC32
MikroElektronika
168
mikroBasic PRO for PIC32
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:
MikroElektronika
169
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 KSEG0, KSEG1, KSEG2 and
KSEG3.
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 KSEG0 and KSEG1.
The PIC32MX CPU maps the virtual areas of KSEG0 and KSEG1 against the same physical memory area beginning
at physical address 0x00000000.
Because both the KSEG0 and KSEG1 virtual segments point to the same physical memory area, the PIC32MX CPU
can execute instructions from either the KSEG0 or KSEG1 virtual memory segment, depending on the cacheable
status of the application (KSEG0 and USEG-KSEG are cacheable while KSEG1 is not cacheable).
MikroElektronika
170
mikroBasic PRO for PIC32
Each variable may be explicitly assigned to a specific memory space by including a memory type specifier in the
declaration, or implicitly assigned.
- code
- data
- rx (reserved for compiler purposes only)
- sfr
code
Description The code memory type may be used for allocating constants in program memory.
data
Description This memory specifier is used when storing variable to the Data RAM.
rx
Description This memory specifier allows variable to be stored in the working registers space (WREG0-
WREG15).
sfr
Description This memory specifier allows user to access special function registers. It also instructs compiler to
maintain same identifier in source and assembly.
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
MikroElektronika
171
mikoBasic PRO for PIC32
When your program changes the state on a specific pin, for example RB0 in PORTB, the microcontroller first READs
all 8 bits of the PORTB register which represents the states of all 8 pins in PORTB (RB7-RB0).
The microcontroller then stores this data in the MCU. The bit associated with RB that you’ve commanded to MODIFY
is changed, and then the microcontroller WRITEs all 8 bits (RB7-RB0) 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.
PORTB.B0 = 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 RB0 pin.
MikroElektronika
172
mikroBasic PRO for PIC32
MODIFY Data is modified to set the RB0 bit: WRITE PORTB is written with the modified data.
The output driver for RB0 turns on, and the
capacitor starts to charge:
READ PORTB is read: STORE Because the capacitor is still charging, the
voltage at RB0 is still low and reads as a ‘0’
(since we are reading from the pins directly,
not from the PORTB register) :
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
driver for RB0 turns back off:
MikroElektronika
173
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 = 0b00000011.
This problem can be avoided by using LATx register when writing to ports, rather than using PORTx registers.
Writing to a LATx register is equivalent to writing to a PORTx register, but readings from LATx registers return the
data value held in the port latch, regardless of the state of the actual pin.
LATB.B0 = 1;
LATB.B1 = 1;
Actual voltage levels on MCU pins are no longer relevant when using LATx for output
MODIFY Data is modified to set the RB0 bit: WRITE LATB is written with the modified data.
The output driver for RB0 turns on, and the
capacitor starts to charge:
MikroElektronika
174
mikroBasic PRO for PIC32
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
output driver for RB1 turns on, and the output
driver for RB0 remains turned on:
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.
MikroElektronika
175
mikoBasic PRO for PIC32
CHAPTER 8
mikroBasic PRO for PIC32
Language Reference
MikroElektronika
176
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
MikroElektronika
177
mikoBasic PRO for PIC32
- Statements
- Introduction to Statements
- Assignment Statements
- Conditional Statements
- If Statement
- Select Case Statement
- For Statement
- While Statement
- Do Statement
- Jump Statements
- asm Statement
- Directives
- Compiler Directives
- Linker Directives
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
and
Newline 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”
newline character
MikroElektronika
179
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.
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.
- keywords
- identifiers
- constants
- operators
- punctuators (also known as separators)
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.
MikroElektronika
180
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.
In decimal notation, numerals are represented as a sequence of digits (without commas, spaces or dots), with optional
prefix + or - operator to indicate the sign. Values default to positive (6258 is equivalent to +6258).
The dollar-sign prefix ($) or the prefix 0x indicates a hexadecimal numeral (for example, $8F or 0x8F).
The percent-sign prefix (%) indicates a binary numeral (for example, %0101).
11 ‘ decimal literal
$11 ‘ hex literal, equals decimal 17
0x11 ‘ hex literal, equals decimal 17
%11 ‘ binary literal, equals decimal 3
The allowed range of values is imposed by the largest data type in mikroBasic PRO for PIC32 – longword. The
compiler will report an error if the literal exceeds 4294967295 ($FFFFFFFF).
- Decimal integer
- Decimal point
- Decimal fraction
- e or 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 * 10-38 .. ±6.80564774407 * 1038.
0. ‘ = 0.0
-1.23 ‘ = -1.23
23.45e6 ‘ = 23.45 * 10^6
2e-5 ‘ = 2.0 * 10^-5
3E+10 ‘ = 3.0 * 10^10
.09E34 ‘ = 0.09 * 10^34
MikroElektronika
181
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.
Length of string literal is a number of characters it consists of. String is stored internally as the given sequence of
characters plus a final null character. This null character is introduced to terminate the string, it does not count against
the string’s total length.
String literal with nothing in between the quotes (null string) is stored as a single null character.
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: P0, TMR1, T1CON, etc). Probe Code Assistant for specific letters (Ctrl+Space in
Editor) or refer to Predefined Globals and Constants.
- absolute
- abstract
- and
- array
- as
- asm
- assembler
- at
- automated
- bdata
- begin
- bit
- case
- cdecl
- class
- code
- compact
- const
- constructor
- contains
- data
- default
- deprecated
- destructor
- dispid
- dispinterface
- div
- dma
- do
- downto
- dynamic
- end
- except
- export
- exports
- external
- far
- file
- final
- finalization
- finally
- for
MikroElektronika
183
mikroBasic PRO for PIC32
- forward
- goto
- helper
- idata
- if
- ilevel
- implementation
- implements
- in
- index
- inherited
- initialization
- inline
- interface
- io
- is
- iv
- 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
MikroElektronika
184
mikroBasic PRO for PIC32
- 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
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.
Identifiers
Identifiers are arbitrary names of any length given to functions, variables, symbolic constants, user-defined data types
and labels. All these program elements will be referred to as objects throughout the help (don’t be confused with the
meaning of object in object-oriented programming).
Identifiers can contain letters from a to z and A to Z, the underscore character “_” and digits from 0 to 9. First 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.
MikroElektronika
185
mikoBasic PRO for PIC32
Identifier Examples
Here are some valid identifiers:
temperature_V1
Pressure
no_hit
dat2string
SUM3
_vtext
Punctuators
The mikroBasic PRO for PIC32 punctuators (also known as separators) are:
- [ ] – Brackets
- ( ) – Parentheses
- , – Comma
- : – Colon
- Dot
Brackets
Brackets [ ] indicate single and multidimensional array subscripts:
MikroElektronika
186
mikroBasic PRO for PIC32
Parentheses
Parentheses ( ) are used to group expressions, isolate conditional expressions, and indicate function calls and
function 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)
dim i, j, k as word
Colon
Colon (:) is used to indicate a labeled statement:
start: nop
‘...
goto start
Dot
Dot (.) indicates access to a structure member. For example:
person.surname = “Smith”
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.
MikroElektronika
187
mikoBasic PRO for PIC32
Program Organization
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.
When writing code, follow the model presented below. The main module should look like this:
‘********************************************************
‘* Declarations (globals):
‘********************************************************
‘ symbols declarations
symbol ...
‘ 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
‘ functions declarations
sub function function_name(...) as return_type
<local declarations>
...
end sub
‘********************************************************
‘* Program body:
‘********************************************************
main:
‘ write your code here
end.
MikroElektronika
188
mikroBasic PRO for PIC32
‘********************************************************
‘* Interface (globals):
‘********************************************************
‘ 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
‘********************************************************
‘* Implementation:
‘********************************************************
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
MikroElektronika
189
mikoBasic PRO for PIC32
‘ functions declarations
sub function sub_function_name([dim byref] [const] ParamName as [^]type, [dim byref]
[const] ParamName2, ParamName3 as [^]type) 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.
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 distinct
categories of identifiers:
1. Global variables are visible throughout the whole unit, from the place of declaration. Also. they can be
seen in other units, if they are declared above the Implementation section.
2. Local variables, parameters, types, function results - must be unique within the block in which they are
declared.
For example:
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.
- 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 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.
MikroElektronika
191
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 .emcl and .mbas files, in order specified by
search paths.
- If both .mbas and .emcl 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 .emcl, then .mbas file will be recompiled and new .emcl
will be created, overwriting the old .emcl.
- If only the .mbas file is found, the compiler will create the .emcl file and include it in the project;
- If only the .emcl 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, Code 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 implementation 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:
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.
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 separate source code module.
MikroElektronika
193
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
main:
CircleArea() ‘ CircleArea routine call
end.
end.
In the First_Module we will define and declare routine called pi_r_squared (calculates pi multiplied by the radius
squared):
module First_Module
implements
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
implements
MikroElektronika
194
mikroBasic PRO for PIC32
end.
There is no need to declare SFRs explicitly, as mikroBasic PRO for PIC32 automatically declares relevant registers as
global variables of word. For example: W0, 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 declaration part of a program or routine. You can declare any number of constants after
the keyword const:
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.
MikroElektronika
195
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
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 module 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) include
clauses. Check Program Organization for more details. Scope of a symbol is always limited to the file in which it has
been declared.
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:
MikroElektronika
196
mikroBasic PRO for PIC32
‘...
main:
Note: Symbols do not support macro expansion in a way the C preprocessor does.
Functions
A function is declared like this:
function_name represents a function’s name and can be any valid identifier. return_type is a type of return value
and can be any simple type or complex type. Within parentheses, parameter_list is a formal parameter list very
similar to variable declaration. In mikroBasic PRO for PIC, parameters are always passed to a function by the value. To
pass an argument by address, add the keyword byref 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
A function is called by its name, with actual arguments placed in the same sequence as their matching formal parameters.
The compiler is able to coerce mismatching arguments to the proper type according to implicit conversion rules. Upon
a function call, all formal parameters are created as local objects initialized by values of actual arguments. Upon return
from a function, a temporary object is created in the place of the call and it is initialized by the value of the function
result. This means that function call as an operand in complex expression is treated as the function result.
In standard Basic, a function_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.
MikroElektronika
197
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 xn based on input parameters x and n (n > 0):
Procedures
Procedure is declared like this:
procedure_name 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 declarations are optional declaration of variables and/or constants, local for the 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.
MikroElektronika
198
mikroBasic PRO for PIC32
Example
Here’s an example procedure which transforms its input time parameters, preparing them for output on Lcd:
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.
Example:
This example shows how to declare a function which returns a complex type.
program Example
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
‘ |------------------------| |-----|
‘ | |
‘ 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:
MikroElektronika
199
mikoBasic PRO for PIC32
program Volume
main:
Volume = Second(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.
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.
You can assign signed to unsigned or vice versa only using the explicit conversion. Refer to Types Conversions for
more information.
MikroElektronika
201
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.
- 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]
Every element of an array is of type and can be accessed by specifying array name followed by element’s index within
brackets.
main:
‘ Now we can access elements of array variables, for example:
samples[0] = 1
if samples[37] = 0 then
‘ ...
Constant Arrays
Constant array is initialized by assigning it a comma-delimited sequence of values within parentheses. For example:
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
The number of assigned values must not exceed the specified length. Vice versa is possible, when the trailing “excess”
elements will be assigned zeroes.
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:
A variable m is an array of 5 elements, which in turn are arrays of 10 byte each. Thus, we have a matrix of 5x10 elements
where the first element is m[0][0] and last one is 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 a number of characters a string consists of. The string is stored internally as the given
sequence of characters plus a final null character (zero). This appended “stamp” does not count against string’s total
length.
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:
main:
msg1 = “This is some message”
msg2 = “Yet another message”
dim s as string[5]
‘ ...
s = “mik”
‘ s[0] is char literal “m”
‘ s[1] is char literal “i”
‘ s[2] is char literal “k”
‘ s[3] is zero
‘ s[4] is undefined
‘ s[5] is undefined
MikroElektronika
203
mikoBasic PRO for PIC32
Be careful when handling strings in this way, since overwriting the end of a string will cause an unpredictable
behavior.
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:
main:
‘...
‘...
Notes:
- In current version plus operator for concatenating strings will accept at most two operands.
- mikroBasic PRO 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
‘...
p^ = 5
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.
dim ptr1 as ^const byte ‘ ptr1 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 program memory space can also be declared within constant declaration
block (using keyword const):
program const_ptr
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.
MikroElektronika
205
mikoBasic PRO for PIC32
dim ptr1 as ^const byte ‘ ptr1 pointer in data space pointing to a byte in code space
const ptr1 as ^byte ‘ ptr1 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:
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 param1, param2 as byte, dim param3 as word)
as word ‘ First, define the procedural type
sub function Func1(dim p1, 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 = p1 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 = @Func1 ‘ MyPtr now points to Func1
MikroElektronika
206
mikroBasic PRO for PIC32
Sample = MyPtr^(1, 2, 3) ‘ Perform function call via pointer, call Func1, the return
value is 3
MyPtr = @Func2 ‘ MyPtr now points to Func2
Sample = MyPtr^(1, 2, 3) ‘ Perform function call via pointer, call Func2, the return
value is 5
MyPtr = @Func3 ‘ MyPtr now points to Func3
Sample = MyPtr^(1, 2, 3) ‘ Perform function call via pointer, call Func3, the return
value is 0
end.
@ Operator
The @ operator constructs a pointer to its operand. The following rules are applied to @:
Note: If variable X is of array type, the @ operator will return pointer to it’s first basic element, except when the left
side of the statement in which X is used is an array pointer.
In this case, the @ operator will return pointer to array, not to it’s first basic element.
program example
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 = @arr ‘ @ operator will return ^byte
ptr_arr = @arr ‘ @ operator will return ^byte[10]
end.
MikroElektronika
207
mikoBasic PRO for PIC32
Pointer Arithmetic
Pointer arithmetic in the mikroBasic PRO for PIC32 is limited to:
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 =, <>, <, <=, >, and >=.
Results of these operations are the same as if they were used on subscript values of array elements in question:
main:
ptr1 = @a[4]
ptr2 = @a[2]
if (ptr1^ = ptr2^) then ... ‘ if the value pointed to by ptr1 is equal to the value
pointed to by ptr2 ...
if (ptr1^ > ptr2^) then ... ‘ if the value pointed to by ptr1 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 type 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 = @a[0] ‘ ptr is pointer to byte, pointing to a[0]
ptr = ptr + 3 ‘ ptr+3 is a pointer 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.
For example:
dim
i, j, x as byte ‘ variables
ptr1 as ^byte ‘ pointers to byte
ptr2 as ^byte
main
i = 10 ‘ assign value 10 to variable; i is at the address 0x0038
j = 5 ‘ assign value 10 to variable; j is at the address 0x003A
x = ptr1^ + 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 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 subtracting 5 from a pointer to type pushes back the pointer 50
bytes in memory.
MikroElektronika
209
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 = @a[6] ‘ ptr is pointer to byte, pointing to a[6]
ptr = ptr - 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 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
ptr1 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
x = ptr2 - ptr1 ‘ result is equal to the distance between the two pointed addresses;
x = 1 (1 byte)
x = ptr1^ - 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 member1 as type1
‘...
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 structure
Each Dot contains two members: x and y coordinates; memory is allocated when you instantiate the structure, like
this:
dim m, n as Dot
circle1.radius = 3.7
circle1.center.x = 0
circle1.center.y = 0
You can also commit assignments between complex variables, if they are of the same type:
MikroElektronika
211
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 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 → byte/char
byte/char → word
short → integer
short → longint
integer → longint
integral → 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 = $FF
b = a ‘ a is promoted to word, b becomes $00FF
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 = $FF0F
i = j ‘ i becomes $0F, higher byte $FF 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 expression 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(b) ‘ a is 255, not 1
You can’t execute explicit conversion on the operand left of the assignment operator:
Conversions Examples
Here is an example of conversion:
program test
dim a, b, cc as byte
dim dd as word
main:
a = 241
b = 128
cc = a + b ‘ equals 113
cc = word(a + b) ‘ equals 113
dd = a + b ‘ equals 369
ptr = TBytePtr(@arr)
ptr = ^byte(@arr)
end.
MikroElektronika
213
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 typedef keyword assigns synonym to <type_definition>. The synonym needs to be 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 typedef 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:
In the typedef declaration, as in any other declaration, several types can be declared at once. For example:
Here, Pti 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:
MikroElektronika
214
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.
- Arithmetic Operators
- Bitwise Operators
- Boolean Operators
- Relational Operators
Each category has an associativity rule: left-to-right (→), or right-to-left (←). In the absence of parentheses, these rules
resolve the grouping of expressions with operators of equal precedence.
MikroElektronika
215
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 technically bytes, they can be also used as unsigned operands in
arithmetic operations.
Division by Zero
If 0 (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.).
For example:
b = -a
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.
Operator Operation
== equal
<> not equal
> greater than
< less than
>= greater than or equal
<= less than or equal
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 >= bb - 1.0 / cc then ‘ same as: if (aa + 5) >= (bb - (1.0 / cc)) then
dd = My_Function()
end if
MikroElektronika
217
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.
and 0 1 or 0 1 xor 0 1
0 0 0 0 0 1 0 0 1
1 0 1 1 1 1 1 1 0
not 0 1
1 0
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:
‘ because ..
‘ Similarly:
MikroElektronika
218
mikroBasic PRO for PIC32
For example:
dim a as byte
dim b as word
‘ ...
a = $AA
b = $F0F0
b = b and a
‘ a is extended with zeroes; b becomes $00A0
For example:
dim a as byte
dim b as word
‘ ...
a = -12
b = $70FF
b = b and a
With shift left (<<), 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 (>>), 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.
MikroElektronika
219
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 Boolean logic, and return either TRUE
(all ones) or FALSE (zero):
Operator Operation
and logical AND
or logical OR
xor logical exclusive OR (XOR)
not logical negation
Unary Operators
Unary operators are operators that take exactly one argument.
For example:
b = -a
Example:
MikroElektronika
220
mikroBasic PRO for PIC32
Note: Besides these, sizeof and explicit conversion unary operators are supported also.
Sizeof Operator
The prefix unary operator sizeof returns an integer constant that represents the size of memory space (in bytes) used
by its operand (determined by its type, with some exceptions).
The operator sizeof can take either a type identifier or an unary expression as an operand. You cannot use sizeof
with expressions of function type, incomplete types, parenthesized names of such types, or with lvalue that designates
a bit field object.
Thus:
sizeof(byte) ‘ returns 1
sizeof(integer) ‘ returns 2
sizeof(longword) ‘ returns 4
sizeof(float) ‘ 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]
...
j = sizeof(samples[1]) ‘ j = sizeof(integer) = 2
i = sizeof(samples) ‘ i = 10*sizeof(integer) = 20
If the operand is a parameter declared as array type or function type, sizeof gives the size of the pointer. When
applied to structures, sizeof gives the total number of bytes, including any padding. The operator sizeof cannot be
applied to a function.
MikroElektronika
221
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
b as word
c as integer
a * b ‘ word level
a * c ‘ integer level
b * c ‘ integer level
In arithmetic expression left side is considered in the following manner: If the left side size in bytes is greater than higher
operand size, then evaluation is done at one level above higher operand level (to get correct calculations).
Example:
a as longword
b as byte
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
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:
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 and assigns its value to variable. All the rules of implicit conversion are
applied. Variable can be any declared variable or array element, and expression can be any expression.
Do not confuse the assignment with relational operator = which tests for equality. mikroBasic PRO for PIC32 will
interpret the meaning of the character = from the context.
MikroElektronika
223
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 if to implement a conditional statement. The syntax of the if statement has the following form:
if expression then
statements
[else
other statements]
end if
When expression evaluates to true, statements execute. If expression is 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 if on its left:
if expression1 then
if expression2 then
statement1
else
statement2
end if
end if
if expression1 then
if expression2 then
statement1
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 expression1 then
if expression2 then
statement1
end if
else
statement2
end if
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 else 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.
MikroElektronika
225
mikoBasic PRO for PIC32
Also, you can group values together for a match. Simply separate the items by commas:
Nested switch
Note that the select case statements can be nested – values are then assigned to the innermost enclosing
select case statement.
- 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
for statement is:
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 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 statement’s 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 = 0
for i = 0 to 9
s = s + a[i] * b[i]
next i
Endless Loop
The for statement results in an endless loop if final_value equals or exceeds the range of the counter’s 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 scalar product of two vectors, using the while statement:
s = 0
i = 0
while i < n
s = s + a[i] * b[i]
i = i + 1
wend
Probably the easiest way to create an endless loop is to use the statement:
while TRUE
‘ ...
wend
MikroElektronika
227
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:
s = 0
i = 0
do
s = s + a[i] * b[i]
i = i + 1
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 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:
MikroElektronika
228
mikroBasic PRO for PIC32
end if
Delay_ms(1000)
wend
Continue Statement
You can use the continue statement within loops to “skip the cycle”:
- continue statement in the for loop moves program counter to the line with keyword for after incrementing the
counter,
- continue statement in the while loop moves program counter to the line with loop condition (top of the loop),
- continue statement in the do loop moves program counter to the line with loop condition (bottom of the loop).
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.
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 statement and like goto, the use of
return statement is generally discouraged.
MikroElektronika
229
mikoBasic PRO for PIC32
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:
for i = 0 to n
for j = 0 to m
...
if disaster
goto Error
end if
...
next 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
...
label_name:
...
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).
asm
block of assembly instructions
end asm
The only types whose name remains the 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
MikroElektronika
231
mikoBasic PRO for PIC32
program asm_example
main:
myvar = 5
myvar1 = 0xABCD1234
asm
MOV _myvar, w0 ; move myvar to W0
nop
MOV #6, W0 ; move literal 6 to W0
MOV W0, _myvar ; move contents of W0 to myvar
MOV #lo_addr(_myvar), w1 ; retrieve low address word of _myvar and move
it to W1 (0x2678 -> W1)
MOV #hi_addr(_myvar), W1 ; retrieve high address word of _myvar and move
it to W1 (0x0000 -> W1)
MOV #lo_addr(_proc), W0 ; retrieve hi address byte of routine proc and
move it to W0 (0x0001 -> W1)
MOV #lo_addr(_msg), W0 ; retrieve low address word of constant msg and
move it to W0 (0x3652 -> W1)
MOV _myvar1+2, w0 ; accessing hi word of myvar1 variable and move
it to W1 (0xABCD -> W1)
end asm
end.
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.
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 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.
For example:
#DEFINE extended_format
Directives #IFDEF and #IFNDEF are terminated with the #ENDIF directive and can have an optional #ELSE clause:
First, #IFDEF 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. #ENDIF ends the conditional sequence. The result of the
preceding scenario is that only one section of code (possibly empty) is passed on for further processing. The processed
section can contain further conditional clauses, nested to any depth; each #IFDEF must be matched with a closing
#ENDIF.
MikroElektronika
233
mikoBasic PRO for PIC32
Here is an example:
Unlike #IFDEF, #IFNDEF checks if flag is not defined by means of #DEFINE, thus producing the opposite results.
Include Directive #I
The #I parameter directive instructs 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: #I “My file”.
There is one restriction to the use of include files: An include file can’t be specified in the middle of a statement part. In
fact, all statements between the begin and end of a statement part must exist in the same source file.
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 KSEG0 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.
Be careful when using the absolute directive, as you may overlap two variables by accident. For example:
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.
‘ 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:
MikroElektronika
235
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:
org directive can be used with main routine too. For example:
program Led_Blinking
Directive orgall
Use the orgall directive to specify the address above which all routines and constants will be placed. Example:
main:
orgall(0x9D000000) ‘ 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.
MikroElektronika
237
mikoBasic PRO for PIC32
Hardware Libraries
- ADC Library
- CANSPI Library
- Compact Flash Library
- Epson S1D13700 Graphic Lcd Library
- Flash Memory Library
- Graphic Lcd Library
- I²C 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 I²C Library
- Software SPI Library
- Software UART Library
- Sound Library
- SPI Library
- SPI Ethernet Library
- SPI Ethernet ENC24J600 Library
- SPI Graphic Lcd Library
- SPI Lcd Library
- SPI Lcd8 Library
- SPI T6963C Graphic Lcd Library
- T6963C Graphic Lcd Library
- TFT Display Library
- Touch Panel Library
- Touch Panel TFT Library
- UART Library
- USB Library
Miscellaneous Libraries
- Button Library
- C Type Library
- Conversions Library
- Setjmp Library
- String Library
- Time Library
- Trigon Library
- Trigonometry Library
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
- I²C 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 I²C Library
- Software SPI Library
- Software UART Library
- Sound Library
- SPI Library
- SPI Ethernet Library
- SPI Ethernet ENC24J600 Library
- SPI Graphic Lcd Library
- SPI Lcd Library
- SPI Lcd8 Library
- SPI T6963C Graphic Lcd Library
- T6963C Graphic Lcd Library
- TFT Display Library
- Touch Panel Library
- Touch Panel TFT Library
- UART Library
- USB Library
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.
MikroElektronika
239
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.
ADCx_Init_Advanced
Prototype sub procedure ADC1_Init_Advanced(dim Reference as word)
Description This routine configures the internal ADC module to work with user defined settings.
Parameters - Reference: voltage reference used in ADC process.
Returns Nothing.
Requires - The MCU with built-in ADC module.
Example ADC1_Init_Advanced(_ADC_INTERNAL_REF) ‘ set internal reference used
Notes - Not all MCUs support advanced configuration. Please, read the appropriate datasheet before utilizing
this library.
MikroElektronika
240
mikroBasic PRO for PIC32
ADCx_Get_Sample
Prototype sub function ADC1_Get_Sample(dim channel as word) as word
Description The function enables ADC module and reads the specified analog channel input.
Parameters - channel represents the channel from which the analog value is to be acquired.
Returns 10-bit unsigned value from the specified channel.
Requires - The MCU with built-in ADC module.
- Prior to using this routine, ADC module needs to be initialized. See ADCx_Init and ADCx_Init_
Advanced.
- Before using the function, be sure to configure the appropriate TRISx bits to designate pins as
inputs.
Example dim adc_value as word
...
adc_value = ADC1_Get_Sample(10) ‘ read analog value from ADC module
channel 10
Notes - 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.
ADCx_Read
Prototype sub function ADC1_Read(dim channel as word) as word
Description The function initializes, enables ADC module and reads the specified analog channel input.
Parameters - 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.
Example dim adc_value as word
...
adc_value = ADC1_Read(10) ‘ read analog value from ADCmodule channel 10
Notes - This is a standalone routine, so there is no need for a previous initialization of ADC module.
- The function sets the appropriate bit in the ADPCFG registers to enable analog function of the
chosen pin.
- Refer to the appropriate Datasheet for channel-to-pin mapping.
MikroElektronika
241
mikoBasic PRO for PIC32
Library Example
This code snippet reads analog value from the channel 1 and sends readings as a text over UART1.
program Temperature_Sensor
main:
CHECON = 0x32
AD1PCFG = 0xFFF7 ‘ Configure AN8 pin as analog I/O
ADC1_Init() ‘ Initialize ADC
Delay_100ms()
Lcd_Init() ‘ Initialize LCD
Lcd_Cmd(_LCD_CLEAR) ‘ Clear LCD
Lcd_Cmd(_LCD_CURSOR_OFF) ‘ Turn cursor off
Lcd_Out(1, 1, “ Temperature: “)
while(TRUE)
temp = ADC_to_degC() ‘ Convert ADC value to Celsius degrees format
FloatToStr(temp, txt)
Lcd_Chr(2,13,223) ‘ Print degree character, ‘C’ for Centigrades
‘ Different LCD displays have different char
code for degree
Lcd_Chr(2,14,”C”) ‘ If you see greek alpha letter try typing 178
instead of 223
Lcd_Out(2, 5, txt) ‘ Display value on the LCD
Delay_1sec() ‘ 1 second delay
wend
end.
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.
Important:
MikroElektronika
243
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)
Description Sets the CANSPI module to requested mode.
Parameters mode: CANSPI module operation mode. Valid values: CANSPI_OP_MODE constants. See CANSPI_
OP_MODE constants.
WAIT: CANSPI mode switching verification request. If WAIT == 0, the call is non-blocking. The
function does not verify if the CANSPI module is switched to requested mode or not. Caller must
use CANSPIGetOperationMode to verify correct operation mode before performing mode specific
operation. If WAIT != 0, the call is blocking – the function won’t “return” until the requested mode is
set.
Returns Nothing.
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.
Example ‘ set the CANSPI module into configuration mode (wait inside
CANSPISetOperationMode until this mode is set)
CANSPISetOperationMode(_CANSPI_MODE_CONFIG, 0xFF)
Notes None.
MikroElektronika
244
mikroBasic PRO for PIC32
CANSPIGetOperationMode
Prototype sub function CANSPIGetOperationMode() as byte
Description The function returns current operation mode of the CANSPI module. Check CANSPI_OP_MODE
constants or device datasheet for operation mode codes.
Parameters None.
Returns Current operation mode.
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.
Example ‘ check whether the CANSPI module is in Normal mode and if it is do
something.
if (CANSPIGetOperationMode() = _CANSPI_MODE_NORMAL) then
...
end if
Notes None.
CANSPIInit
Prototype sub procedure CANSPIInit(dim SJW, BRP, PHSEG1, PHSEG2, PROPSEG, CANSPI_
CONFIG_FLAGS as char)
Description Initializes the CANSPI module.
SAM, SEG2PHTS, WAKFIL and DBEN bits are set according to CANSPI_CONFIG_FLAGS value.
Parameters - SJW as defined in MCU’s datasheet (CAN Module)
- BRP as defined in MCU’s datasheet (CAN Module)
- PHSEG1 as defined in MCU’s datasheet (CAN Module)
- PHSEG2 as defined in MCU’s datasheet (CAN Module)
- PROPSEG as defined in MCU’s datasheet (CAN Module)
- CANSPI_CONFIG_FLAGS is formed from predefined constants. See CANSPI_CONFIG_FLAGS
constants.
Returns Nothing.
MikroElektronika
245
mikoBasic PRO for PIC32
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.
Example ‘ CANSPI module connections
dim CanSpi_CS as sbit at LATF0_bit
CanSpi_CS_Direction as sbit at TRISF0_bit
CanSpi_Rst as sbit at LATF12_bit
CanSpi_Rst_Direction as sbit at TRISF1_bit
‘ End CANSPI module connections
MikroElektronika
246
mikroBasic PRO for PIC32
CANSPISetBaudRate
Prototype sub procedure CANSPISetBaudRate(dim SJW, BRP, PHSEG1, PHSEG2, PROPSEG,
CANSPI_CONFIG_FLAGS as byte)
Returns 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.
Returns 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.
Example ‘ set required baud rate and sampling rules
dim CANSPI_CONFIG_FLAGS as byte
...
CANSPISetOperationMode(_CANSPI_MODE_CONFIG,0xFF) ‘ 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
CANSPISetBaudRate(1, 1, 3, 3, 1, CANSPI_CONFIG_FLAGS)
Notes None.
MikroElektronika
247
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: CANSPI_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 & _CANSPI_CONFIG_STD_MSG,
- _CANSPI_CONFIG_MATCH_MSG_TYPE & _CANSPI_CONFIG_XTD_MSG.
See CANSPI_CONFIG_FLAGS constants.
Returns 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.
Example ‘ set the appropriate filter mask and message type value
CANSPISetOperationMode(_CANSPI_MODE_CONFIG,0xFF) ‘ set CONFIGURATION
mode (CANSPI1 module must be in config mode for mask settings)
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.
Returns 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.
Example ‘ set the appropriate filter value and message type
CANSPI1SetOperationMode(_CANSPI_MODE_CONFIG,0xFF) ‘ set CONFIGURATION mode
(CANSPI1 module must be in config mode for filter settings)
MikroElektronika
249
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:
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.
Example ‘ 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,0xFF) ‘ set NORMAL mode (CANSPI1
module must be in mode in which receive is possible)
...
rx_flags = 0 ‘ clear message flags
if (msg_rcvd = CANSPIRead(msg_id, data, data_len, rx_flags)) then
...
end if
Notes None.
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
CANSPI_TX_MSG_FLAGS constants.
Returns - 0 if all Transmit Buffers are busy
- 0xFFFF if at least one Transmit Buffer is available
Requires 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.
Example ‘ 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,0xFF) ‘ set NORMAL mode (CANSPI1
must be in mode in which transmission is possible)
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:
MikroElektronika
251
mikoBasic PRO for PIC32
const
_CANSPI_MODE_BITS as byte = $E0 Use this to access opmode bits
_CANSPI_MODE_NORMAL as byte = 0
_CANSPI_MODE_SLEEP as byte = $20
_CANSPI_MODE_LOOP as byte = $40
_CANSPI_MODE_LISTEN as byte = $60
_CANSPI_MODE_CONFIG as byte = $80
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:
const
_CANSPI_CONFIG_DEFAULT as byte = $FF ‘ 11111111
MikroElektronika
252
mikroBasic PRO for PIC32
You may use bitwise and to form config byte out of these values. For example:
CANSPI_TX_MSG_FLAGS Constants
CANSPI_TX_MSG_FLAGS are flags related to transmission of a CANSPI message:
const
_CANSPI_TX_PRIORITY_BITS as byte = $03
_CANSPI_TX_PRIORITY_0 as byte = $FC ‘ XXXXXX00
_CANSPI_TX_PRIORITY_1 as byte = $FD ‘ XXXXXX01
_CANSPI_TX_PRIORITY_2 as byte = $FE ‘ XXXXXX10
_CANSPI_TX_PRIORITY_3 as byte = $FF ‘ XXXXXX11
You may use bitwise and to adjust the appropriate flags. For example:
CANSPI_RX_MSG_FLAGS Constants
CANSPI_RX_MSG_FLAGS are flags related to reception of CANSPI message. If a particular bit is set then corresponding
meaning is TRUE or else it will be FALSE.
MikroElektronika
253
mikoBasic PRO for PIC32
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
You may use bitwise and to adjust the appropriate flags. For example:
CANSPI_MASK Constants
The CANSPI_MASK constants define mask codes. Function CANSPISetMask expects one of these as it’s argument:
const
_CANSPI_MASK_B1 as byte = 0
_CANSPI_MASK_B2 as byte = 1
CANSPI_FILTER Constants
The CANSPI_FILTER constants define filter codes. Functions CANSPISetFilter expects one of these as it’s
argument:
const
_CANSPI_FILTER_B1_F1 as byte = 0
_CANSPI_FILTER_B1_F2 as byte = 1
_CANSPI_FILTER_B2_F1 as byte = 2
_CANSPI_FILTER_B2_F2 as byte = 3
_CANSPI_FILTER_B2_F3 as byte = 4
_CANSPI_FILTER_B2_F4 as byte = 5
MikroElektronika
254
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.
program Can_Spi_1st
main:
CHECON = 0x32
AD1PCFG = 0xFFFF ‘ configure AN pins as digital I/O
Can_Init_Flags = 0 ‘
Can_Send_Flags = 0 ‘ clear flags
Can_Rcv_Flags = 0 ‘
MikroElektronika
255
mikoBasic PRO for PIC32
program Can_Spi_2nd
main:
CHECON = 0x32
AD1PCFG = 0xFFFF ‘ configure AN pins as digital I/O
MikroElektronika
256
mikroBasic PRO for PIC32
Can_Init_Flags = 0 ‘
Can_Send_Flags = 0 ‘ clear flags
Can_Rcv_Flags = 0 ‘
MikroElektronika
257
mikoBasic PRO for PIC32
HW Connection
Example of interfacing CAN transceiver MCP2510 with MCU via SPI interface
MikroElektronika
258
mikroBasic PRO for PIC32
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.
MikroElektronika
259
mikoBasic PRO for PIC32
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
- 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
- Cf_Issue_ID_Command
MikroElektronika
261
mikoBasic PRO for PIC32
Cf_Init
Prototype sub procedure Cf_Init()
Description Initializes ports appropriately for communication with CF card.
Parameters None.
Returns Nothing.
Requires Global variables:
‘Init CF
Cf_Init()
Notes None.
MikroElektronika
262
mikroBasic PRO for PIC32
Cf_Detect
Prototype sub function CF_Detect() as word
Description Checks for presence of CF card by reading the chip detect pin.
Parameters None.
Returns - 1 - if CF card was detected
- 0 - otherwise
Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
Example ‘ Wait until CF card is inserted:
while (Cf_Detect() = 0)
nop
wend
Notes 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.
Parameters None.
Returns Nothing.
Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
Example ‘ enable compact flash
Cf_Enable()
Notes 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
multiple devices.
Parameters None.
Returns Nothing.
Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
Example ‘ disable compact flash
Cf_Disable()
Notes None.
MikroElektronika
263
mikoBasic PRO for PIC32
Cf_Read_Init
Prototype sub procedure Cf_Read_Init(dim address as longword, dim sectcnt as byte)
Description 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.
Returns Nothing.
Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
Example ‘ initialize compact flash for reading from sector 590
Cf_Read_Init(590, 1)
Notes None.
Cf_Read_Byte
Prototype sub function CF_Read_Byte() as byte
Description Reads one byte from Compact Flash sector buffer location currently pointed to by internal read
pointers. These pointers will be autoicremented upon reading.
Parameters None.
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_Write_Init
Prototype sub procedure Cf_Write_Init(dim address as longword, dim sectcnt as word)
Description 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.
Returns Nothing.
Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
Example ‘ initialize compact flash for writing to sector 590
Cf_Write_Init(590, 1)
Notes None.
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.
Returns Nothing.
Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
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.
Returns Nothing.
Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
Example ‘ read sector 22
dim data_ as byte[512]
...
Cf_Read_Sector(22, data_)
Notes None.
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: sector to be written to.
- buffer: data buffer of 512 bytes in length.
Returns Nothing.
Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
Example ‘ write to sector 22
dim data_ as byte[512]
...
Cf_Write_Sector(22, data_)
Notes None.
MikroElektronika
265
mikoBasic PRO for PIC32
Cf_Fat_Init
Prototype sub function Cf_Fat_Init() as word
Description Initializes CF card, reads CF FAT16 boot sector and extracts necessary data needed by the library.
Parameters None.
Returns - 0 - if CF card was detected and successfully initialized
- 1 - if FAT16 boot sector was not found
- 255 - if card was not detected
Requires Nothing.
Example ‘ init the FAT library
if (Cf_Fat_Init() = 0) then
...
end if
Notes None.
Cf_Fat_QuickFormat
Prototype sub function Cf_Fat_QuickFormat(dim byref cf_fat_label as string[11]) as
word
Description 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.
Returns - 0 - if CF card was detected, successfully formated and initialized
- 1 - if FAT16 format was unsuccessful
- 255 - if card was not detected
Requires Nothing.
Example ‘ format and initialize the FAT library
if ( Cf_Fat_QuickFormat(“mikroE”) = 0) then
...
end if
Notes - This routine can be used instead or in conjunction with Cf_Fat_Init routine.
- If CF card already contains a valid boot sector, it will remain unchanged (except volume label field)
and only FAT and ROOT tables will be erased. Also, the new volume label will be set.
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” -> “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” -> 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:
Bit Mask Description
0 0x01 Read Only
1 0x02 Hidden
2 0x04 System
3 0x08 Volume Label
4 0x10 Subdirectory
5 0x20 Archive
6 0x40 Device (internal use only, never found on disk)
File creation flag. If the file does not exist and this flag is
7 0x80
set, a new file with specified name will be created.
MikroElektronika
267
mikoBasic PRO for PIC32
Cf_Fat_Reset
Prototype sub procedure Cf_Fat_Reset(dim byref size as longword)
Description 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.
Returns Nothing.
Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
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.
Parameters - bdata: buffer to store read byte to. Upon this function execution read byte is returned through this
parameter.
Returns Nothing.
Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
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.
Parameters None.
Returns Nothing.
Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
Cf_Fat_Append
Prototype sub procedure Cf_Fat_Append()
Description Opens currently assigned file for appending. Upon this function execution file pointers will be positioned
after the last byte in the file, so any subsequent file writing operation will start from there.
Parameters None.
Returns Nothing.
Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
Cf_Fat_Delete
Prototype sub procedure Cf_Fat_Delete()
Description Deletes currently assigned file from CF card.
Parameters None.
Returns Nothing.
Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
MikroElektronika
269
mikoBasic PRO for PIC32
Cf_Fat_Write
Prototype sub procedure Cf_Fat_Write(dim byref fdata as byte[512], dim data_len as
word)
Description Writes requested number of bytes to currently assigned file opened for writing.
Parameters - fdata: data to be written.
- data_len: number of bytes to be written.
Returns Nothing.
Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
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
- day: day attribute. Valid values: 1-31
- hours: hours attribute. Valid values: 0-23
- mins: minutes attribute. Valid values: 0-59
- seconds: seconds attribute. Valid values: 0-59
Returns Nothing.
Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
MikroElektronika
270
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)
Description Reads time/date attributes of currently assigned file.
Parameters - year: buffer to store year attribute to. Upon function execution year attribute is returned through this
parameter.
- month: buffer to store month attribute to. Upon function execution month attribute is returned through
this parameter.
- day: buffer to store day attribute to. Upon function execution day attribute is returned through this
parameter.
- hours: buffer to store hours attribute to. Upon function execution hours attribute is returned through
this parameter.
- mins: buffer to store minutes attribute to. Upon function execution minutes attribute is returned
through this parameter.
Returns Nothing.
Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
Cf_Fat_Get_File_Date_Modified
Prototype sub procedure Cf_Fat_Get_File_Date_Modified(dim byref year as word, dim byref
month, day, hours, mins as byte)
Description Retrieves the last modification date/time of the currently assigned file.
Parameters - year: buffer to store year of modification attribute to. Upon function execution year of modification
attribute is returned through this parameter.
- month: buffer to store month of modification attribute to. Upon function execution month of modification
attribute is returned through this parameter.
- day: buffer to store day of modification attribute to. Upon function execution day of modification
attribute is returned through this parameter.
- hours: buffer to store hours of modification attribute to. Upon function execution hours of modification
attribute is returned through this parameter.
- mins: buffer to store minutes of modification attribute to. Upon function execution minutes of
modification attribute is returned through this parameter.
Returns Nothing.
Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
MikroElektronika
271
mikoBasic PRO for PIC32
Cf_Fat_Get_File_Size
Prototype sub function Cf_Fat_Get_File_Size() as longword
Description This function reads size of currently assigned file in bytes.
Parameters None.
Returns Size of the currently assigned file in bytes.
Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
Notes None.
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_attr 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” -> “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” -> 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
272
mikroBasic PRO for PIC32
Parameters
Bit Mask Description
0 0x01 Read Only
1 0x02 Hidden
2 0x04 System
3 0x08 Volume Label
4 0x10 Subdirectory
5 0x20 Archive
6 0x40 Device (internal use only, never found on disk)
7 0x80 Not used
Returns - Number of the start sector for the newly created swap file, if there was enough free space on CF
card to create file of required size.
- 0 - otherwise.
Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
Example ‘ Try to create a swap file with archive atribute, whose size will be at
least 1000 sectors.
‘ If it succeeds, it sends the No. of start sector over UART
dim size as longword
...
size = Cf_Fat_Get_Swap_File(1000, “mikroE.txt”, 0x20)
if (size <> 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 Cf_Fat16 library. These are:
MikroElektronika
273
mikoBasic PRO for PIC32
program CF_Fat16_Test
dim
‘ set compact flash pinout
Cf_Data_Port as byte at PORTE
const LINE_LEN = 37
dim
err_txt as string[20]
file_contents as string[LINE_LEN]
character as byte
loop1, 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
MikroElektronika
274
mikroBasic PRO for PIC32
‘-------------- 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 > 0
Cf_Fat_Read(character)
UART1_Write(character) ‘ Write data to USART
Dec(size)
wend
MikroElektronika
275
mikoBasic PRO for PIC32
end sub
‘-------------- 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)
MikroElektronika
276
mikroBasic PRO for PIC32
Delay_ms(1000)
UART1_Write(0x55)
end if
end sub
‘-------------- 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
end sub
MikroElektronika
277
mikoBasic PRO for PIC32
HW Connection
MikroElektronika
278
mikroBasic PRO for PIC32
The S1D13700 Glcd is capable of displaying both text and graphics on an LCD panel. The S1D13700 Glcd allows
layered text and graphics, scrolling of the display in any direction, and partitioning of the display into multiple screens.
It includes 32K bytes of embedded SRAM display memory which is used to store text, character codes, and bit-mapped
graphics.
The S1D13700 Glcd 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.
MikroElektronika
279
mikoBasic PRO for PIC32
Library Routines
- S1D13700_Init
- S1D13700_Write_Command
- S1D13700_Write_Parameter
- S1D13700_Read_Parameter
- S1D13700_Fill
- S1D13700_GrFill
- S1D13700_TxtFill
- S1D13700_Display_GrLayer
- S1D13700_Display_TxtLayer
- S1D13700_Set_Cursor
- S1D13700_Display_Cursor
- S1D13700_Write_Char
- S1D13700_Write_Text
- S1D13700_Dot
- S1D13700_Line
- S1D13700_H_Line
- S1D13700_V_Line
- S1D13700_Rectangle
- S1D13700_Box
- S1D13700_Rectangle_Round_Edges
- S1D13700_Rectangle_Round_Edges_Fill
- S1D13700_Circle
- S1D13700_Circle_Fill
- S1D13700_Image
- S1D13700_PartialImage
MikroElektronika
280
mikroBasic PRO for PIC32
S1D13700_Init
Prototype sub procedure S1D13700_Init(dim width as word, dim height as word)
Returns Nothing.
Description Initializes S1D13700 Graphic Lcd controller.
Parameters:
MikroElektronika
281
mikoBasic PRO for PIC32
S1D13700_Write_Command
Prototype sub procedure S1D13700_Write_Command(dim command as byte)
Returns Nothing.
Description Writes a command to S1D13700 controller.
Parameters:
Value Description
S1D13700_SYSTEM_SET General system settings.
S1D13700_POWER_SAVE Enter into power saving mode.
S1D13700_DISP_ON Turn the display on.
S1D13700_DISP_OFF Turn the display off.
S1D13700_SCROLL Setup text and graphics address regions.
Cursor moves right after write to display
S1D13700_CS_RIGHT
memory.
Cursor moves left after write to display
S1D13700_CS_LEFT
memory.
Cursor moves up after write to display
S1D13700_CS_UP
memory.
Cursor moves down after write to display
S1D13700_CS_DOWN
memory.
S1D13700_OVLAY Configure how layers overlay.
S1D13700_CGRAM_ADR Configure character generator RAM address.
S1D13700_HDOT_SCR Set horizontal scroll rate.
S1D13700_CSRW Set the cursor address.
S1D13700_CSRR Read the cursor address.
Selects the gray scale depth, in bits-per-pixel
S1D13700_GRAYSCALE
(bpp).
S1D13700_MEMWRITE Write to display memory.
S1D13700_MEMREAD Read from display memory.
MikroElektronika
282
mikroBasic PRO for PIC32
S1D13700_Write_Parameter
Prototype sub procedure S1D13700_Write_Parameter(dim parameter as byte)
Returns Nothing.
Description Writes a parameter to S1D13700 controller.
Parameters:
S1D13700_Read_Parameter
Prototype sub function S1D13700_Read_Parameter() as byte
Returns Nothing.
Description Reads a parameter from GLCD port.
Requires Glcd module needs to be initialized. See the S1D13700_Init routine.
Example parameter = S1D13700_Read_Parameter()
S1D13700_Fill
Prototype sub procedure S1D13700_Fill(dim d as byte, dim start as word, dim len as
word)
Returns Nothing.
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.
Requires Glcd module needs to be initialized. See the S1D13700_Init routine.
Example ‘ from the starting address of 0x3000, fill the memory block size of 0x7FFF
with 0x20
S1D13700_Fill(0x20, 0x3000, 0x7FFF)
MikroElektronika
283
mikoBasic PRO for PIC32
S1D13700_GrFill
Prototype sub procedure S1D13700_GrFill(dim d as byte)
Returns Nothing.
Description Fill graphic layer with appropriate value (0 to clear).
Parameters:
S1D13700_TxtFill
Prototype sub procedure S1D13700_TxtFill(dim d as byte)
Returns Nothing.
Description Fill current text panel with appropriate value (0 to clear).
Parameters:
S1D13700_Display_GrLayer
Prototype <sub procedure S1D13700_Display_GrLayer(dim mode as byte)
Returns Nothing.
Description Display selected graphic layer.
Parameters:
Value Description
S1D13700_LAYER_OFF Turn off graphic layer.
S1D13700_LAYER_ON Turn on graphic layer.
S1D13700_LAYER_FLASH_2Hz Turn on graphic layer and flash it at the rate of 2 Hz.
S1D13700_LAYER_FLASH_16Hz Turn on graphic layer and flash it at the rate of 16 Hz.
MikroElektronika
284
mikroBasic PRO for PIC32
S1D13700_Display_TxtLayer
Prototype sub procedure S1D13700_Display_TxtLayer(dim mode as byte)
Returns Nothing.
Description Display selected text layer.
Parameters:
Value Description
S1D13700_LAYER_OFF Turn off graphic layer.
S1D13700_LAYER_ON Turn on graphic layer.
S1D13700_LAYER_FLASH_2Hz Turn on graphic layer and flash it at the rate of 2 Hz.
S1D13700_LAYER_FLASH_16Hz Turn on graphic layer and flash it at the rate of 16 Hz.
S1D13700_Set_Cursor
Prototype sub procedure S1D13700_Set_Cursor(dim width as byte, dim height as byte,
dim mode as byte)
Returns Nothing.
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:
Value Description
S1D13700_CURSOR_UNDERSCORE Set cursor shape - underscore.
S1D13700_CURSOR_BLOCK Set cursor shape - block.
MikroElektronika
285
mikoBasic PRO for PIC32
S1D13700_Display_Cursor
Prototype sub procedure S1D13700_Display_Cursor(dim mode as byte)
Returns Nothing.
Description Displays cursor.
Parameters:
Value Description
S1D13700_CURSOR_OFF Turn off graphic layer.
S1D13700_CURSOR_ON Turn on graphic layer.
S1D13700_CURSOR_FLASH_2Hz Turn on graphic layer and flash it at the rate of 2 Hz.
S1D13700_CURSOR_FLASH_16Hz Turn on graphic layer and flash it at the rate of 16 Hz.
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)
Returns 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:
Value Description
In the OR-Mode, text and graphics can be displayed and the data is
logically “OR-ed”.
S1D13700_OVERLAY_OR
This is the most common way of combining text and graphics, for
example labels on buttons.
In this mode, the text and graphics data are combined via the logical
S1D13700_OVERLAY_XOR
“exclusive OR”.
The text and graphic data shown on display are combined via the logical
S1D13700_OVERLAY_AND
“AND function”.
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)
Returns Nothing.
Description Writes text in the current text panel of Glcd at coordinates (x, y).
Parameters:
Value Description
In the OR-Mode, text and graphics can be displayed and the data is
logically “OR-ed”.
S1D13700_OVERLAY_OR
This is the most common way of combining text and graphics, for
example labels on buttons.
In this mode, the text and graphics data are combined via the logical
S1D13700_OVERLAY_XOR
“exclusive OR”.
The text and graphic data shown on display are combined via the logical
S1D13700_OVERLAY_AND
“AND function”.
S1D13700_Dot
Prototype sub procedure S1D13700_Dot(dim x as word, dim y as word, dim color as
byte)
Returns Nothing.
Description Draws a dot in the current graphic panel of Glcd at coordinates (x, y).
Parameters:
MikroElektronika
287
mikoBasic PRO for PIC32
S1D13700_Line
Prototype sub procedure S1D13700_Line(dim x0, y0, x1, y1 as word, dim pcolor as
byte)
Returns Nothing.
Description Draws a line from (x0, y0) to (x1, y1).
Parameters:
Value Description
S1D13700_BLACK Black color.
S1D13700_WHITE White color.
S1D13700_H_Line
Prototype sub procedure S1D13700_H_Line(dim x_start, x_end, y_pos as word, dim color
as byte)
Returns Nothing.
Description Draws a horizontal line.
Parameters:
Value Description
S1D13700_BLACK Black color.
S1D13700_WHITE White color.
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 byte)
Returns Nothing.
Description Draws a horizontal line.
Parameters:
Value Description
S1D13700_BLACK Black color.
S1D13700_WHITE White color.
S1D13700_Rectangle
Prototype sub procedure S1D13700_Rectangle(dim x0, y0, x1, y1 as word, dim pcolor as
byte)
Returns Nothing.
Description Draws a rectangle on Glcd.
Parameters:
Value Description
S1D13700_BLACK Black color.
S1D13700_WHITE White color.
MikroElektronika
289
mikoBasic PRO for PIC32
S1D13700_Box
Prototype sub procedure S1D13700_Box(dim x0, y0, x1, y1 as word, dim pcolor as byte)
Returns Nothing.
Description Draws a rectangle on Glcd.
Parameters:
Value Description
S1D13700_BLACK Black color.
S1D13700_WHITE White color.
S1D13700_Rectangle_Round_Edges
Prototype void S1D13700_Rectangle_Round_Edges(unsigned int x_upper_left, unsigned int
y_upper_left, unsigned int x_bottom_right, unsigned int y_bottom_right,
unsigned short round_radius, unsigned short color);
Returns Nothing.
Description Draws a rounded edge rectangle on Glcd.
Parameters:
Value Description
S1D13700_BLACK Black color.
S1D13700_WHITE White color.
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)
Returns Nothing.
Description Draws a filled rounded edge rectangle on Glcd.
Parameters:
Value Description
S1D13700_BLACK Black color.
S1D13700_WHITE White color.
S1D13700_Circle
Prototype sub procedure S1D13700_Circle(dim x_center as word, dim y_center as word,
dim radius as word, dim color as byte)
Returns Nothing.
Description Draws a circle on Glcd.
Parameters:
Value Description
S1D13700_BLACK Black color.
S1D13700_WHITE White color.
MikroElektronika
291
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)
Returns Nothing.
Description Draws a filled circle on Glcd.
Parameters:
Value Description
S1D13700_BLACK Black color.
S1D13700_WHITE White color.
S1D13700_Image
Prototype sub procedure S1D13700_Image(dim image as ^const byte)
Returns Nothing.
Description Displays bitmap on Glcd.
Parameters:
MikroElektronika
292
mikroBasic PRO for PIC32
S1D13700_PartialImage
Prototype sub procedure S1D13700_PartialImage(dim x_left, y_top, width, height,
picture_width, picture_height as word, dim image as ^const byte)
Returns Nothing.
Description Displays a partial area of the image on a desired location.
Parameters:
MikroElektronika
293
mikoBasic PRO for PIC32
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 ՠ512 = 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:
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
Returns Nothing.
Requires Nothing.
Example
Notes None.
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: address of the FLASH memory word
- rdata: data to be written
Returns Nothing.
Requires Nothing.
Example
Notes 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
Returns Nothing.
Requires Nothing.
Example
Notes None.
MikroElektronika
295
mikoBasic PRO for PIC32
For creating a custom set of Glcd images use Glcd Bitmap Editor Tool.
MikroElektronika
296
mikroBasic PRO for PIC32
MikroElektronika
297
mikoBasic PRO for PIC32
Library Routines
Basic routines:
- Glcd_Init
- Glcd_Set_Side
- Glcd_Set_X
- Glcd_Set_Page
- Glcd_Read_Data
- Glcd_Write_Data
Advanced routines:
- Glcd_Fill
- Glcd_Dot
- Glcd_Line
- Glcd_V_Line
- Glcd_H_Line
- Glcd_Rectangle
- Glcd_Rectangle_Round_Edges
- Glcd_Rectangle_Round_Edges_Fill
- Glcd_Box
- Glcd_Circle
- Glcd_Circle_Fill
- Glcd_Set_Font
- Glcd_Write_Char
- Glcd_Write_Text
- Glcd_Image
- Glcd_PartialImage
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 <0:7>).
Parameters None.
Returns Nothing.
Requires Global variables:
MikroElektronika
298
mikroBasic PRO for PIC32
...
Glcd_Init()
Notes None.
MikroElektronika
299
mikoBasic PRO for PIC32
Glcd_Set_Side
Prototype sub procedure Glcd_Set_Side(dim x_pos as byte)
Description Selects Glcd side. Refer to the Glcd datasheet for detailed explanation.
Parameters - x_pos: Specifies position on x-axis of the Glcd. Valid values: 0..127. Values from 0 to 63 specify the
left side, values from 64 to 127 specify the right side of the Glcd.
Returns Nothing.
Requires Glcd needs to be initialized, see Glcd_Init routine.
Example The following two lines are equivalent, and both of them select the left side of Glcd:
Glcd_Select_Side(0);
Glcd_Select_Side(10);
Notes For side, x axis and page layout explanation see schematic at the bottom of this page.
Glcd_Set_X
Prototype sub procedure Glcd_Set_X(dim x_pos as byte)
Description Sets x-axis position to x_pos dots from the left border of Glcd within the selected side.
Parameters - x_pos: position on x-axis. Valid values: 0..63
Returns Nothing.
Requires Glcd needs to be initialized, see Glcd_Init routine.
Example Glcd_Set_X(25);
Notes For side, x axis and page layout explanation see schematic at the bottom of this page.
Glcd_Set_Page
Prototype sub procedure Glcd_Set_Page(dim page as byte)
Description Selects page of the Glcd.
Parameters - page: page number. Valid values: 0..7
Returns Nothing.
Requires Glcd needs to be initialized, see Glcd_Init routine.
Example Glcd_Set_Page(5)
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
Prototype sub function Glcd_Read_Data() as byte
Description Reads data from from the current location of Glcd memory and moves to the next location.
Parameters None.
Returns One byte from Glcd memory, formatted as a word (16-bit).
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.
Example dim data_ as byte
...
Glcd_Read_Data()
data_ = Glcd_Read_Data()
Notes 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)
Returns Nothing.
Description Writes one byte to the current location in Glcd memory and moves to the next location.
Parameters:
Glcd side, x-axis position and page should be set first. See functions Glcd_Set_Side, Glcd_Set_X,
and Glcd_Set_Page.
Example dim data_ as byte
...
Glcd_Write_Data(data_)
MikroElektronika
301
mikoBasic PRO for PIC32
Glcd_Fill
Prototype sub procedure Glcd_Fill(dim pattern as byte)
Description Fills Glcd memory with the byte pattern.
Glcd_Dot
Prototype sub procedure Glcd_Dot(dim x_pos, y_pos, color as byte)
Description 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: 0 clears dot, 1 puts a dot, and 2 inverts dot state.
Returns Nothing.
Requires Glcd needs to be initialized, see Glcd_Init routine.
Example ‘ 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)
Description Draws a line on Glcd.
Parameters - x_start: x coordinate of the line start. Valid values: 0..127
- y_start: y coordinate of the line start. Valid values: 0..63
- x_end: x coordinate of the line end. Valid values: 0..127
- y_end: y coordinate of the line end. Valid values: 0..63
- color: color parameter. Valid values: 0..2
The parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot.
Returns Nothing.
Requires Glcd needs to be initialized, see Glcd_Init routine.
Example ‘ Draw a line between dots (0,0) and (20,30)
Glcd_Line(0, 0, 20, 30, 1)
Notes None.
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.
Returns Nothing.
Requires Glcd needs to be initialized, see Glcd_Init routine.
Example ‘ Draw a vertical line between dots (10,5) and (10,25)
Glcd_V_Line(5, 25, 10, 1)
Notes 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_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.
Returns Nothing.
Requires Glcd needs to be initialized, see Glcd_Init routine.
Example ‘ Draw a horizontal line between dots (10,20) and (50,20)
Glcd_H_Line(10, 50, 20, 1)
Notes None.
MikroElektronika
303
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)
Description 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: 0 white, 1 black, and 2 inverts
each dot.
Returns Nothing.
Requires Glcd needs to be initialized, see Glcd_Init routine.
Example ‘ Draw a rectangle between dots (5,5) and (40,40)
Glcd_Rectangle(5, 5, 40, 40, 1)
Notes None.
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)
Description 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.
Returns Nothing.
Requires Glcd needs to be initialized, see Glcd_Init routine.
Example ‘ Draw a rounded edge rectangle between dots (5,5) and (40,40) with the
radius of 12
Glcd_Rectangle_Round_Edges(5, 5, 40, 40, 12, 1)
Notes None.
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)
Description 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.
Returns Nothing.
Requires Glcd needs to be initialized, see Glcd_Init routine.
Example ‘ 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, 40, 40, 12, 1)
Notes None.
Glcd_Box
Prototype sub procedure Glcd_Box(dim x_upper_left, y_upper_left, x_bottom_right, y_
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: 0 white, 1 black, and 2 inverts each dot.
Returns Nothing.
Requires Glcd needs to be initialized, see Glcd_Init routine.
Example ‘ Draw a box between dots (5,15) and (20,40)
Glcd_Box(5, 15, 20, 40, 1)
Notes None.
MikroElektronika
305
mikoBasic PRO for PIC32
Glcd_Circle
Prototype sub procedure Glcd_Circle(dim x_center, y_center, radius as integer, dim
color as byte)
Description Draws a circle on Glcd.1
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.
Returns Nothing.
Requires Glcd needs to be initialized, see Glcd_Init routine.
Example ‘ Draw a circle with center in (50,50) and radius=10
Glcd_Circle(50, 50, 10, 1)
Notes None.
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)
Description 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
Returns Nothing.
Requires Glcd needs to be initialized, see Glcd_Init routine.
Example ‘ Draw a circle with center in (50,50) and radius=10
Glcd_Circle_Fill(50, 50, 10, 1)
Notes None.
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)
Description 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 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.
- Font_Glcd_System3x5
- Font_Glcd_System5x7
- Font_Glcd_5x7
- Font_Glcd_Character8x7
For the sake of the backward compatibility, these fonts are supported also:
MikroElektronika
307
mikoBasic PRO for PIC32
Glcd_Write_Char
Prototype sub procedure Glcd_Write_Char(dim character, x_pos, page_num, color as
byte)
Description Prints character on the Glcd.
Parameters - character: character to be written
- x_pos: character starting position on x-axis. Valid values: 0..(127-FontWidth)
- page_num: the number of the page on which character will be written. Valid values: 0..7
- color: color parameter. Valid values: 0..2
The parameter color determines the color of the character: 0 white, 1 black, and 2 inverts each dot.
Returns Nothing.
Requires Glcd needs to be initialized, see Glcd_Init routine. Use Glcd_Set_Font to specify the font for display; if
no font is specified, then default Font_Glcd_System5x7 font supplied with the library will be used.
Example ‘ Write character ‘C’ on the position 10 inside the page 2:
Glcd_Write_Char(‘C’, 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 Glcd_Write_Text(dim byref text as string, dim x_pos, page_num,
color as byte)
Description Prints text on Glcd.
Parameters - text: text to be written
- x_pos: text starting position on x-axis.
- page_num: the number of the page on which text will be written. Valid values: 0..7
- color: color parameter. Valid values: 0..2
The parameter color determines the color of the text: 0 white, 1 black, and 2 inverts each dot.
Returns Nothing.
Requires Glcd needs to be initialized, see Glcd_Init routine. Use Glcd_Set_Font to specify the font for display; if
no font is specified, then default Font_Glcd_System5x7 font supplied with the library will be used.
Example ‘ Write text “Hello world!” on the position 10 inside the page 2:
Glcd_Write_Text(“Hello world!”, 10, 2, 1)
Notes 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 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).
Returns Nothing.
Requires Glcd needs to be initialized, see Glcd_Init routine.
Example ‘ Draw image my_image on Glcd
Glcd_Image(my_image)
Notes 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_PartialImage
Prototype sub procedure Glcd_PartialImage(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).
Returns Nothing.
Requires Glcd needs to be initialized, see Glcd_Init routine.
Example ‘ Draws a 10x15 part of the image starting from the upper left corner on the
coordinate (10,12). Original image size is 16x32.
Glcd_PartialImage(10, 12, 10, 15, 16, 32, @image)
Notes 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.
MikroElektronika
309
mikoBasic PRO for PIC32
I²C Library
The I²C 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 I²C mode.
Important:
- I²C library routines require you to specify the module you want to use. To select the desired I²C module, simply
change the letter x in the routine prototype for a number from 1 to 3.
- Number of I²C modules per MCU differs from chip to chip. Please, read the appropriate datasheet before utilizing
this library.
Library Routines
- I2Cx_Init
- I2Cx_Init_Advanced
- I2Cx_Start
- I2Cx_Restart
- I2Cx_Is_Idle
- I2Cx_Read
- I2Cx_Write
- I2Cx_Stop
I2Cx_Init
Prototype sub procedure I2Cx_Init(dim scl as longint)
Description This function configures and initializes the desired I²C 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 I²C module is:
As per the I²C standard, SCL clock may be 100 kHz or 400 kHz. However, the user can specify any
clock rate up to 1 MHz.
Parameters - scl: requested serial clock rate.
Returns Nothing.
Requires MCU with the I²C module.
Example ‘ Initialize the I2C1 module with clock_rate=100000
I2C1_Init(100000)
Notes - Refer to the MCU’s datasheet for correct values of the scl in respect with Fosc.
- I²C library routines require you to specify the module you want to use. To select the desired I²C
module, simply change the letter x in the routine prototype for a number from 1 to 3.
- Number of I²C modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
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 I²C module using Peripheral Bus Clock and default
initialization settings.
As per the I²C standard, SCL clock may be 100 kHz or 400 kHz. However, the user can specify any
clock rate up to 1 MHz.
Parameters - Fclk_Khz: Peripheral Bus Clock frequency in kHz.
- scl: requested serial clock rate.
Returns Nothing.
Requires MCU with the I²C module.
Example
Notes - I²C library routines require you to specify the module you want to use. To select the desired I²C
module, simply change the letter x in the routine prototype for a number from 1 to 3.
- Number of I²C modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
I2Cx_Start
Prototype sub procedure I2Cx_Start()
Description Determines if the I²C bus is free and issues START signal.
Parameters None.
Returns Nothing.
Requires MCU with at least one I²C module.
Used I²C module must be initialized before using this function. See I2Cx_Init routine.
Example ‘ Issue START signal
I2C1_Start()
Notes - I²C library routines require you to specify the module you want to use. To select the desired I²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.
MikroElektronika
311
mikoBasic PRO for PIC32
I2Cx_Restart
Prototype sub procedure I2Cx_Restart()
Description Issues repeated START signal.
Parameters None.
Returns Nothing.
Requires MCU with at least one I²C module.
Used I²C module must be initialized before using this function. See I2Cx_Init routine.
Example ‘ Issue RESTART signal
I2C1_Restart()
Notes - I²C library routines require you to specify the module you want to use. To select the desired I²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.
I2Cx_Is_Idle
Prototype sub function I2Cx_Is_Idle() as word
Description Waits for the I²C bus to become free. This is a blocking function.
Parameters None.
Returns - 0 if I²C bus is free.
- 1 if I²C bus is not free.
Requires MCU with at least one I²C module.
Used I²C module must be initialized before using this function. See I2Cx_Init routine.
Example dim data_ as byte
...
if I2C1_Is_Idle() then
I2C1_Write(data_)
end if
...
Notes - I²C library routines require you to specify the module you want to use. To select the desired I²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.
MikroElektronika
312
mikroBasic PRO for PIC32
I2Cx_Read
Prototype sub function I2Cx_Read(dim ack as word) as byte
Description Reads a byte from the I²C bus.
Parameters - ack: acknowledge signal parameter. If the ack = 0, acknowledge signal will be sent after reading,
otherwise the not acknowledge signal will be sent.
Returns Received data.
Requires MCU with at least one I²C module.
Used I²C module must be initialized before using this function. See I2Cx_Init routine.
Also, START signal needs to be issued in order to use this function. See I2Cx_Start.
Example dim take as byte
...
‘ Read data and send the not_acknowledge signal
take = I2C1_Read(1)
Notes - I²C library routines require you to specify the module you want to use. To select the desired I²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.
I2Cx_Write
Prototype sub function I2Cx_Write(dim data_ as byte) as word
Description Sends data byte via the I²C bus.
Parameters - data_: data to be sent
Returns - 0 if there were no errors.
- 1 if write collision was detected on the I²C bus.
Requires MCU with at least one I²C module.
Used 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.
Example dim data_ as byte
error as word
...
error = I2C1_Write(data_)
error = I2C1_Write(0xA3)
Notes - I²C library routines require you to specify the module you want to use. To select the desired I²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.
MikroElektronika
313
mikoBasic PRO for PIC32
I2Cx_Stop
Prototype sub procedure I2Cx_Stop()
Description Issues STOP signal.
Parameters None.
Returns Nothing.
Requires MCU with at least one I²C module.
Used I²C module must be initialized before using this function. See I2Cx_Init routine.
Example ‘ Issue STOP signal
I2C1_Stop()
Notes - I²C library routines require you to specify the module you want to use. To select the desired I²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.
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.
program I2C_Simple
main:
program I2C_Simple
dim i, b as char
MikroElektronika
314
mikroBasic PRO for PIC32
I2C2_Stop()
end sub
main:
CHECON = 0x30
AD1PCFG = 0xFFFFFFFF
MikroElektronika
315
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.
Library Routines
- Keypad_Init
- Keypad_Key_Press
- Keypad_Key_Click
Keypad_Init
Prototype sub procedure Keypad_Init()
Description Initializes given port for working with keypad.
Parameters None.
Returns Nothing.
Requires Global variable:
MikroElektronika
316
mikroBasic PRO for PIC32
Keypad_Key_Press
Prototype sub function Keypad_Key_Press() as word
Description Reads the key from keypad when key gets pressed.
Parameters None.
Returns The code of a pressed key (1..16).
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.
Returns The code of a clicked key (1..16).
MikroElektronika
317
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.
program Keypad_Test
dim kp, oldstate as byte
txt as char[6]
main:
CHECON = 0x32
AD1PCFG = 0xFFFF
oldstate = 0
UART1_Init(19200)
Delay_ms(10)
Keypad_Init() ‘ Initialize Keypad
while TRUE
kp = 0 ‘ Reset key code variable
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 ‘ 8
case 11
kp = 57 ‘ 9
case 12
kp = 67 ‘ C
case 13
kp = 42 ‘ *
case 14
kp = 48 ‘ 0
case 15
kp = 35 ‘ #
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
MikroElektronika
319
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 Routines
- Lcd_Init
- Lcd_Out
- Lcd_Out_Cp
- Lcd_Chr
- Lcd_Chr_Cp
- Lcd_Cmd
MikroElektronika
320
mikroBasic PRO for PIC32
Lcd_Init
Prototype sub procedure Lcd_Init()
Description Initializes Lcd module.
Parameters None.
Returns Nothing.
Requires Global variables:
MikroElektronika
321
mikoBasic PRO for PIC32
Lcd_Out
Prototype sub procedure Lcd_Out(dim row, column as word, dim byref text as string)
Description Prints text on Lcd starting from specified position. Both string variables and literals can be passed as
a text.
Parameters - row: starting position row number
- column: starting position column number
- text: text to be written
Returns Nothing.
Requires The Lcd module needs to be initialized. See Lcd_Init routine.
Example ‘ Write text “Hello!” on Lcd starting from row 1, column 3:
Lcd_Out(1, 3, “Hello!”)
Notes None
Lcd_Out_Cp
Prototype sub procedure Lcd_Out_Cp(dim byref text as string)
Returns Nothing.
Description Prints text on Lcd at current cursor position. Both string variables and literals can be passed as a
text.
Parameters - text: text to be written
Requires The Lcd module needs to be initialized. See Lcd_Init routine.
Example ‘ Write text “Here!” at current cursor position:
Lcd_Out_Cp(“Here!”)
Notes None
Lcd_Chr
Prototype sub procedure Lcd_Chr(dim row, column as word, dim out_char as byte)
Description 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
Returns Nothing.
Requires The Lcd module needs to be initialized. See Lcd_Init routine.
Example ‘ Write character “i” at row 2, column 3:
Lcd_Chr(2, 3, “i”)
Notes None
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
Returns Nothing.
Requires The Lcd module needs to be initialized. See Lcd_Init routine.
Example ‘ Write character “e” at current cursor position:
Lcd_Chr_Cp(“e”)
Notes None
Lcd_Cmd
Prototype sub procedure Lcd_Cmd(dim out_char as byte)
Description Sends command to Lcd.
Parameters - out_char: command to be sent
Returns Nothing.
Requires The Lcd module needs to be initialized. See Lcd_Init table.
Example ‘ Clear Lcd display:
Lcd_Cmd(_LCD_CLEAR)
Notes Predefined constants can be passed to the function, see Available Lcd Commands.
MikroElektronika
323
mikoBasic PRO for PIC32
Library Example
The following code demonstrates usage of the Lcd Library routines:
main:
CHECON = 0x32
AD1PCFG = 0xFFFF ‘ Configure AN pins as digital I/O
txt1 = “mikroElektronika”
txt2 = “LV32MX v6”
txt3 = “Lcd4bit”
txt4 = “example”
‘ Moving text
for i = 0 to 3 ‘ Move text to the right 4 times
MikroElektronika
324
mikroBasic PRO for PIC32
Lcd_Cmd(_LCD_SHIFT_RIGHT)
Move_Delay()
next i
Lcd HW connection
MikroElektronika
325
mikoBasic PRO for PIC32
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.
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.
Parameters None.
Returns - 0 - if initialization and synchronization were successful.
- 1 - upon unsuccessful synchronization.
- 255 - upon user abort.
Requires Global variables:
MikroElektronika
327
mikoBasic PRO for PIC32
Man_Receive
Prototype sub function Man_Receive(dim byref error as word) as byte
Description The function extracts one byte from incoming signal.
Parameters - error: error flag. If signal format does not match the expected, the error flag will be set
to non-zero.
Returns A byte read from the incoming signal.
Requires To use this function, the user must prepare the MCU for receiving. See Man_Receive_Init routines.
Example dim data_, error as word
...
error = 0
data_ = 0
data_ = Man_Receive(error)
if (error <> 0) then
‘ error handling
end if
Notes None.
Man_Send_Init
Prototype sub procedure Man_Send_Init()
Description The function configures Transmitter pin.
Parameters None.
Returns Nothing.
Requires Global variables:
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
Returns Nothing.
Requires To use this function, the user must prepare the MCU for sending. See Man_Send_Init routine.
Example dim msg as byte
...
Man_Send(msg)
Notes Baud rate used is 500 bps.
Man_Synchro
Prototype sub function Man_Synchro() as word
Description Measures half of the manchester bit length with 10us resolution.
Parameters None.
Returns 0 - if synchronization was not successful.
Half of the manchester bit length, given in multiples of 10us - upon successful synchronization.
Requires To use this function, you must first prepare the MCU for receiving. See Man_Receive_Init.
Example dim man__half_bit_len as word
...
man__half_bit_len = Man_Synchro()
Notes None.
MikroElektronika
329
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.
Parameters None.
Returns Nothing.
Requires Nothing.
Example dim data1, error, counter as byte
main:
...
if (Man_Receive_Init() = 0)
...
end if
...
data1 = Man_Receive(@error)
T1IE_bit = 0 ‘ Disable Timer1 interrupts
end.
Notes 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 code for the Manchester receiver, it shows how to use the Manchester Library for receiving data:
main:
ErrorCount = 0
counter = 0
CHECON = 0x32
AD1PCFG = 0xFFFF ‘ Configure AN pins as digital I/O
Lcd_Init() ‘ Initialize LCD
Lcd_Cmd(_LCD_CLEAR) ‘ Clear LCD display
MikroElektronika
331
mikoBasic PRO for PIC32
do
temp = Man_Receive(error_flag) ‘ Attempt byte receive
if (error_flag <> 0) then ‘ If error occured
Lcd_Chr_CP(“?”) ‘ Write question mark on LCD
Inc(ErrorCount) ‘ Update error counter
if (ErrorCount > 20) then ‘ In case of multiple errors
temp = Man_Synchro() ‘ Try to synchronize again
‘Man_Receive_Init() ‘ Alternative, try to Initialize Receiver again
ErrorCount = 0 ‘ Reset error counter
end if
else ‘ No error occured
if (temp <> 0x0E) then ‘ If “End” byte was received(see Transmitter example)
‘ do not write anymore received byte on Lcd
Lcd_Chr_CP(temp) ‘ else write character on Lcd
Inc(counter) ‘ Counts how many chars have been written on Lcd
if counter = 25 then ‘ If there were more then 25 characters
‘ synchronization is off
Lcd_Cmd(_LCD_CLEAR) ‘ Clear the Lcd of garbled communication
temp = Man_Synchro() ‘ Try to synchronize again
end if
else
counter = 0 ‘ reset counter
end if
Delay_ms(25)
end if
loop until ( temp = 0x0E )
wend ‘ If “End” byte was received exit do loop
end.
The following code is code for the Manchester transmitter, it shows how to use the Manchester Library for transmitting
data:
main:
s1 = “mikroElektronika”
CHECON = 0x32
AD1PCFG = 0xFFFF ‘ Configure AN pins as digital I/O
MikroElektronika
332
mikroBasic PRO for PIC32
Connection Example
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
Prototype sub procedure Heap_Init()
Description Sets Heap size.
Parameters None.
Returns Nothing.
Requires Nothing.
Example const HEAP_SIZE = 3000 ‘ declare Heap size
Heap_Init() ‘ set Heap size
Notes None.
GetMem
Prototype sub procedure GetMem(dim byref P as ^longword, dim WantedSize as word)
Description Fetches memory from the memory heap.
Parameters - WantedSize: pointer to the fetched memory
- WantedSize: size in bytes of the dynamic variable to allocate
Returns Returns a pointer to the fetched memory (of “WantedSize” bytes) in P if success; Otherwise 0 (no free
blocks of memory are large enough).
Requires Nothing.
Example GetMem(ptr,20*sizeof(PBuffer)) ‘ ptr will point to a memory block where
PBuffer is allocated
Notes None.
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 assigned 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.
Returns Nothing.
Requires Nothing.
Example FreeMem(ptr,20*sizeof(PBuffer)) ‘ ptr will point to a memory block where
PBuffer is allocated
Notes None.
MM_LargestFreeMemBlock
Prototype sub function MM_LargestFreeMemBlock() as word
Description This sub function is used to determine largest available free memory block for the Heap.
Parameters None.
Returns Returns, after defragmentation of the freelist the size (in bytes) of the largest free block of contiguous
memory on the heap.
Requires Nothing.
Example dim block as word
...
block = MM_LargestFreeMemBlock()
Notes None.
MM_TotalFreeMemSize
Prototype sub function MM_TotalFreeMemSize() as word
Description This sub function is used to determine total free memory size on the heap.
Parameters None.
Returns Returns the size (in bytes) of the total free memory on the heap.
Requires Nothing.
Example dim total as word
...
total = MM_TotalFreeMemSize()
Notes None.
MikroElektronika
335
mikoBasic PRO for PIC32
Important:
- Routines for file handling can be used only with FAT16 file system.
- Library functions create and read files from the root directory only.
- Library functions populate both FAT1 and FAT2 tables when writing to files, but the file data is being read from the
FAT1 table only; i.e. there is no recovery if the FAT1 table gets corrupted.
- If MMC/SD card has Master Boot Record (MBR), the library will work with the first available primary (logical)
partition that has non-zero size. If MMC/SD card has Volume Boot Record (i.e. there is only one logical partition and
no MBRs), the library works with entire card as a single partition. For more information on MBR, physical and logical
drives, primary/secondary partitions and partition tables, please consult other resources, e.g. Wikipedia and similar.
- Before write operation, make sure you don’t overwrite boot or FAT sector as it could make your card on PC or digital
camera unreadable. Drive mapping tools, such as Winhex, can be of a great assistance.
- Library uses SPI module for communication. The user must initialize the appropriate SPI module before using the
MMC Library.
- For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by using the SPI_Set_
Active() function. See the SPI Library functions.
The SPI module has to be initialized through SPIx_Init_Advanced routine with the following parameters:
- SPI Master
- 8bit mode
- secondary prescaler 1
- primary prescaler 64
- Slave Select disabled
- data sampled in the middle of data output time
- clock idle high
- Serial output data changes on transition from active clock state to idle clock state
Tip: Once the MMC/SD card is initialized, SPI module can be reinitialized at higher a speed. See the Mmc_Init and
Mmc_Fat_Init routines.
MikroElektronika
336
mikroBasic PRO for PIC32
Library Routines
- Mmc_Init
- Mmc_Read_Sector
- Mmc_Write_Sector
- Mmc_Read_Cid
- Mmc_Read_Csd
- 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
MikroElektronika
337
mikoBasic PRO for PIC32
Mmc_Init
Prototype sub function Mmc_Init() as word
Description Initializes MMC through hardware SPI interface.
Global variables:
Notes None.
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
Description The function reads one sector (512 bytes) from MMC card.
Parameters - sector: MMC/SD card sector to be read.
- dbuff: buffer of minimum 512 bytes in length for data storage.
Returns - 0 - if reading was successful
- 1 - if an error occurred
Requires MMC/SD card must be initialized. See Mmc_Init.
Example ‘ read sector 510 of the MMC/SD card
dim error as word
sectorNo as longword
dataBuffer as byte[512]
...
sectorNo = 510
error = Mmc_Read_Sector(sectorNo, dataBuffer)
Notes None.
Mmc_Write_Sector
Prototype sub function Mmc_Write_Sector(dim sector as longword, dim byref data as
byte[512]) as word
Description The function writes 512 bytes of data to one MMC card sector.
Parameters - sector: MMC/SD card sector to be written to.
- dbuff: data to be written (buffer of minimum 512 bytes in length).
Returns - 0 - if writing was successful
- 1 - if there was an error in sending write command
- 2 - if there was an error in writing (data rejected)
Requires MMC/SD card must be initialized. See Mmc_Init.
Example ‘ write to sector 510 of the MMC/SD card
dim error as word
sectorNo as longword
dataBuffer as byte[512]
...
sectorNo = 510
error = Mmc_Write_Sector(sectorNo, dataBuffer)
Notes None.
MikroElektronika
339
mikoBasic PRO for PIC32
Mmc_Read_Cid
Prototype sub function Mmc_Read_Cid(dim byref data_cid as byte[16]) as byte
Description The function reads 16-byte CID register.
Parameters - data_cid: buffer of minimum 16 bytes in length for storing CID register content.
Returns - 0 - if CID register was read successfully
- 1 - if there was an error while reading
Requires MMC/SD card must be initialized. See Mmc_Init.
Example dim error as word
dataBuffer as byte[512]
...
error = Mmc_Read_Cid(dataBuffer)
Notes None.
Mmc_Read_Csd
Prototype sub function Mmc_Read_Csd(dim byref data_csd as byte[16]) as word
Description The function reads 16-byte CSD register.
Parameters - data_csd: buffer of minimum 16 bytes in length for storing CSD register content.
Returns - 0 - if CSD register was read successfully
- 1 - if there was an error while reading
Requires MMC/SD card must be initialized. See Mmc_Init.
Example dim error as word
dataBuffer as byte[512]
...
error = Mmc_Read_Csd(dataBuffer)
Notes None.
MikroElektronika
340
mikroBasic PRO for PIC32
Mmc_Fat_Init
Prototype sub function Mmc_Fat_Init() as word
Description Initializes MMC/SD card, reads MMC/SD FAT16 boot sector and extracts necessary data needed by
the library.
Parameters None.
Returns - 0 - if MMC/SD card was detected and successfully initialized
- 1 - if FAT16 boot sector was not found
- 255 - if MMC/SD card was not detected
Requires Global variables:
The appropriate hardware SPI module must be previously initialized. See the SPIx_Init, SPIx_Init_
Advanced routines.
Example ‘ MMC module connections
dim Mmc_Chip_Select as sbit sfr at LATF0_bit
dim Mmc_Chip_Select_Direction as sbit sfr at TRISF0_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
Mmc_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)
MikroElektronika
341
mikoBasic PRO for PIC32
Mmc_Fat_QuickFormat
Prototype sub function Mmc_Fat_QuickFormat(dim byref mmc_fat_label as string[11]) as
word
Description Formats to FAT16 and initializes MMC/SD card.
Parameters - mmc_fat_label: volume label (11 characters in length). If less than 11 characters are provided, the
label will be padded with spaces. If null string is passed volume will not be labeled
Returns - 0 - if MMC/SD card was detected, successfully formated and initialized
- 1 - if FAT16 format was unseccessful
- 255 - if MMC/SD card was not detected
Requires The appropriate hardware SPI module must be previously initialized.
Example ‘ 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
Mmc_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)
Notes 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.
MikroElektronika
342
mikroBasic PRO for PIC32
Mmc_Fat_Assign
Prototype 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 of the file that should be assigned for file operations. File name should be in DOS 8.3
(file_name.extension) format. The file name and extension will be automatically padded with spaces
by the library if they have less than length required (i.e. “mikro.tx” -> “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” -> 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:
Bit Mask Description
0 0x01 Read Only
1 0x02 Hidden
2 0x04 System
3 0x08 Volume Label
4 0x10 Subdirectory
5 0x20 Archive
6 0x40 Device (internal use only, never found on disk)
File creation flag. If file does not exist and this flag is set, a
7 0x80
new file with specified name will be created.
Returns - 1 - if file already exists or file does not exist but a new file is created.
- 0 - if file does not exist and no new file is created.
Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
Example ‘ create file with archive attribut if it does not already exist
Mmc_Fat_Assign(“MIKRO007.TXT”,0xA0)
Notes Long File Names (LFN) are not supported.
MikroElektronika
343
mikoBasic PRO for PIC32
Mmc_Fat_Reset
Prototype sub procedure Mmc_Fat_Reset(dim byref size as longword)
Description 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.
Returns Nothing.
Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
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.
Parameters - bdata: buffer to store read byte to. Upon this function execution read byte is returned through this
parameter.
Returns Nothing.
Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
MikroElektronika
344
mikroBasic PRO for PIC32
Mmc_Fat_Rewrite
Prototype sub procedure Mmc_Fat_Rewrite()
Description Opens the currently assigned file for writing. If the file is not empty its content will be erased.
Parameters None.
Returns Nothing.
Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
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.
Parameters None.
Returns Nothing.
Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
Mmc_Fat_Delete
Prototype sub procedure Mmc_Fat_Delete()
Description Deletes currently assigned file from MMC/SD card.
Parameters None.
Returns Nothing.
Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
MikroElektronika
345
mikoBasic PRO for PIC32
Mmc_Fat_Write
Prototype sub procedure Mmc_Fat_Write(dim byref fdata as byte[512], dim data_len as
word)
Description 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.
Returns Nothing.
Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
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
- day: day attribute. Valid values: 1-31
- hours: hours attribute. Valid values: 0-23
- mins: minutes attribute. Valid values: 0-59
- seconds: seconds attribute. Valid values: 0-59
Returns Nothing.
Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
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 byref hours as byte, dim byref mins as
byte)
Description Reads time/date attributes of the currently assigned file.
Parameters - year: buffer to store year attribute to. Upon function execution year attribute is returned through this
parameter.
- month: buffer to store month attribute to. Upon function execution month attribute is returned through
this parameter.
- day: buffer to store day attribute to. Upon function execution day attribute is returned through this
parameter.
- hours: buffer to store hours attribute to. Upon function execution hours attribute is returned through
this parameter.
- mins: buffer to store minutes attribute to. Upon function execution minutes attribute is returned
through this parameter.
Returns Nothing.
Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
Notes None.
MikroElektronika
347
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 store year attribute to. Upon function execution year attribute is returned through this
parameter.
- month: buffer to store month attribute to. Upon function execution month attribute is returned through
this parameter.
- day: buffer to store day attribute to. Upon function execution day attribute is returned through this
parameter.
- hours: buffer to store hours attribute to. Upon function execution hours attribute is returned through
this parameter.
- mins: buffer to store minutes attribute to. Upon function execution minutes attribute is returned
through this parameter.
Returns Nothing.
Requires The file must be assigned, see Mmc_Fat_Assign.
Example 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
Prototype sub function Mmc_Fat_Get_File_Size() as longword
Description This function reads size of the currently assigned file in bytes.
Parameters None.
Returns This function returns size of active file (in bytes).
Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
Notes None.
MikroElektronika
348
mikroBasic PRO for PIC32
Mmc_Fat_Get_Swap_File
Prototype sub function Mmc_Fat_Get_Swap_File(dim sectors_cnt as longword, dim byref
filename as string[11], dim file_attr as byte) as longword
Description This function is used to create a swap file of predefined name and size on the MMC/SD media. If a
file with specified name already exists on the media, search for consecutive sectors will ignore sectors
occupied by this file. Therefore, it is recommended to erase such file if it already exists before calling
this function. If it is not erased and there is still enough space for a new swap file, this function will
delete it after allocating new memory space for a new swap file.
The purpose of the 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.
Parameters - sectors_cnt: number of consecutive sectors that user wants the swap file to have.
- filename: name of the file that should be assigned for file operations. File name should be in DOS 8.3
(file_name.extension) format. The file name and extension will be automatically padded with spaces
by the library if they have less than length required (i.e. “mikro.tx” -> “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” -> 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:
Returns 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.
Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
MikroElektronika
349
mikoBasic PRO for PIC32
Example ‘-------------- 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 <> 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 library. These
are:
program MMC_FAT_Test
const LINE_LEN = 43
dim
FAT_TXT as string[20]
file_contents as string[LINE_LEN]
character as byte
loop_, loop2 as byte
size as longint
buffer as byte[512]
MikroElektronika
350
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
MikroElektronika
351
mikoBasic PRO for PIC32
‘-------------- 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 > 0
Mmc_Fat_Read(character)
UART1_Write(character) ‘ Write data to UART
Dec(size)
wend
end sub
‘-------------- 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”
if Mmc_Fat_Assign(filename, 0) <> 0 then
‘--- file has been found - get its date
Mmc_Fat_Get_File_Date(year, month_, day, hour_, minute_)
UART1_Write_Text(“ created: “)
WordToStr(year, outstr)
UART1_Write_Text(outstr)
ByteToStr(month_ , outstr)
UART1_Write_Text(outstr)
WordToStr(day, outstr)
UART1_Write_Text(outstr)
WordToStr(hour_, outstr)
UART1_Write_Text(outstr)
WordToStr(minute_, 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)
‘-------------- 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
CHECON = 0x32
AD1PCFG = 0xFFFF ‘ initialize AN pins as digital
‘ Initialize UART1 module
UART1_Init(56000)
MikroElektronika
353
mikoBasic PRO for PIC32
Delay_ms(10)
#IFDEF COMPLETE_EXAMPLE
M_Create_New_File()
M_Create_Multiple_Files()
M_Open_File_Rewrite()
M_Open_File_Append()
M_Open_File_Read()
M_Delete_File()
M_Test_File_Exist()
M_Create_Swap_File()
#ENDIF
UART_Write_Line(“Test End.”)
else
UART_Write_Line(fat_txt)‘ Note: Mmc_Fat_Init tries to initialize a card more than once.
‘ If card is not present, initialization may last
longer (depending on clock speed)
end if
end.
HW Connection
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.
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
Prototype sub function Ow_Reset(dim byref port as word, dim pin as word) as word
Description Issues OneWire reset signal for DS18x20.
Parameters - port: OneWire bus port
- pin: OneWire bus pin
Returns - 0 if the device is present
- 1 if the device is not present
Requires Devices compliant with the Dallas OneWire protocol.
Example ‘ Issue Reset signal on One-Wire Bus connected to pin RF6
Ow_Reset(PORTF, 6)
Notes None.
MikroElektronika
355
mikoBasic PRO for PIC32
Ow_Read
Prototype sub function Ow_Read(dim byref port as word, dim pin as word) as byte
Description 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.
Requires Devices compliant with the Dallas OneWire protocol.
Example ‘ Read a byte from the One-Wire Bus connected to pin RF6
dim read_data as byte
...
read_data = Ow_Read(PORTF, 6)
Notes None.
Ow_Write
Prototype sub procedure Ow_Write(dim byref port as word, dim pin, data_ as word)
Description Writes one byte of data via the OneWire bus.
Parameters - port: OneWire bus port
- pin: OneWire bus pin
- data_: data to be written
Returns Nothing.
Requires Devices compliant with the Dallas OneWire protocol.
Example ‘ Send a byte to the One-Wire Bus connected to pin RF6
Ow_Write(PORTF, 6, 0xCC)
Notes None.
MikroElektronika
356
mikroBasic PRO for PIC32
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 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
- Expander_Set_DirectionPortB
- Expander_Set_DirectionPortAB
- Expander_Set_PullUpsPortA
- Expander_Set_PullUpsPortB
- Expander_Set_PullUpsPortAB
MikroElektronika
357
mikoBasic PRO for PIC32
Expander_Init
Prototype sub procedure Expander_Init(dim ModuleAddress as byte)
Description Initializes Port Expander using SPI communication.
...
SPI1_Init() ‘ initialize SPI module
Expander_Init(0) ‘ initialize Port Expander
Notes None.
MikroElektronika
358
mikroBasic PRO for PIC32
Expander_Init_Advanced
Prototype sub procedure Expander_Init_Advanced(dim byref rstPort, rstPin, haen as
byte)p>
Description Initializes Port Expander using SPI communication.
Parameters - rstPort: Port Expander’s reset port
- rstPin: Port Expander’s reset pin
- haen: Port Expander’s hardware address
Returns Nothing.
Requires - SPExpanderCS: Chip Select line
- SPExpanderRST: Reset line
- SPExpanderCS_Direction: Direction of the Chip Select pin
- SPExpanderRST_Direction: Direction of the Reset pin
...
‘ If Port Expander Library uses SPI1 module
SPI1_Init() ‘ initialize SPI module
Expander_Init_Advanced(PORTB, 0, 0) ‘ initialize Port Expander
Notes None.
MikroElektronika
359
mikoBasic PRO for PIC32
Expander_Read_Byte
Prototype sub function Expander_Read_Byte(dim ModuleAddress, RegAddress as byte) as
byte
Description The function reads byte from Port Expander.
Parameters - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
- RegAddress: Port Expander’s internal register address
Returns Byte read.
Requires Port Expander must be initialized. See Expander_Init.
Example ‘ Read a byte from Port Expander’s register
dim read_data as byte
...
read_data = Expander_Read_Byte(0,1)
Notes None.
Expander_Write_Byte
Prototype sub procedure Expander_Write_Byte(dim ModuleAddress, RegAddress, Data as
byte)
Description 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
- Data: data to be written
Returns Byte read.
Requires Port Expander must be initialized. See Expander_Init.
Example ‘ Write a byte to the Port Expander’s register
Expander_Write_Byte(0,1,$FF)
Notes None.
Expander_Read_PortA
Prototype sub function Expander_Read_PortA(dim ModuleAddress as byte) as byte
Description The function reads byte from Port Expander’s PortA.
Parameters - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
Returns Byte read.
Requires Port Expander must be initialized. See Expander_Init.
MikroElektronika
360
mikroBasic PRO for PIC32
Expander_Read_PortB
Prototype sub function Expander_Read_PortB(dim ModuleAddress as byte) as byte
Description The function reads byte from Port Expander’s PortB.
Parameters - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
Returns Byte read.
Requires Port Expander must be initialized. See Expander_Init.
Expander_Read_PortAB
Prototype 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.
Parameters - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
Returns Word read.
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.
Example ‘ 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)
Notes None.
MikroElektronika
361
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’s PortA.
Parameters - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
- Data: data to be written
Returns Nothing.
Requires Port Expander must be initialized. See Expander_Init.
...
Expander_Set_DirectionPortA(0,$00) ‘ set expander’s porta to be output
...
Expander_Write_PortA(0, $AA)
Notes None.
Expander_Write_PortB
Prototype sub procedure Expander_Write_PortB(dim ModuleAddress, Data as byte)
Description The function writes byte to Port Expander’s PortB.
Parameters - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
- Data: data to be written
Returns Nothing.
Requires Port Expander must be initialized. See Expander_Init.
...
Expander_Set_DirectionPortB(0,$00) ‘ set expander’s portb to be output
...
Expander_Write_PortB(0,$55)
Notes None.
MikroElektronika
362
mikroBasic PRO for PIC32
Expander_Write_PortAB
Prototype sub procedure Expander_Write_PortAB(dim ModuleAddress as byte, dim Data as
word)
Description The function writes word to Port Expander’s ports.
Parameters - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page
- Data: data to be written. Data to be written to PortA are passed in Data’s higher byte. Data to be
written to PortB are passed in Data’s lower byte
Returns Nothing.
Requires 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.
Example ‘ 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)
Notes None.
Expander_Set_DirectionPortA
Prototype sub procedure Expander_Set_DirectionPortA(dim ModuleAddress, Data as byte)
Description The function sets Port Expander’s PortA direction.
Parameters - 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.
Returns Nothing.
Requires Port Expander must be initialized. See Expander_Init.
Example ‘ Set Port Expander’s PORTA to be output
Expander_Set_DirectionPortA(0,$00)
Notes None.
MikroElektronika
363
mikoBasic PRO for PIC32
Expander_Set_DirectionPortB
Prototype sub procedure Expander_Set_DirectionPortB(dim ModuleAddress, Data as byte)
Description The function sets Port Expander’s PortB direction.
Parameters - ModuleAddress: 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.
Returns Nothing.
Requires Port Expander must be initialized. See Expander_Init.
Example ‘ Set Port Expander’s PORTB to be input
Expander_Set_DirectionPortB(0,$FF)
Notes None.
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 - ModuleAddress: 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.
Returns Nothing.
Requires Port Expander must be initialized. See Expander_Init.
Example ‘ Set Port Expander’s PORTA to be output and PORTB to be input
Expander_Set_DirectionPortAB(0,$00FF)
Notes None.
Expander_Set_PullUpsPortA
Prototype sub procedure Expander_Set_PullUpsPortA(dim ModuleAddress, Data as byte)
Description The function sets Port Expander’s PortA pull up/down resistors.
Parameters - ModuleAddress: 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.
Returns Nothing.
Requires Port Expander must be initialized. See Expander_Init.
Example ‘ Set Port Expander’s PORTA pull-up resistors
Expander_Set_PullUpsPortA(0, $FF)
Notes None.
MikroElektronika
364
mikroBasic PRO for PIC32
Expander_Set_PullUpsPortB
Prototype sub procedure Expander_Set_PullUpsPortB(dim ModuleAddress, Data as byte)
Description The function sets Port Expander’s PortB pull up/down resistors.
Parameters - ModuleAddress: 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.
Returns Nothing.
Requires Port Expander must be initialized. See Expander_Init.
Example ‘ Set Port Expander’s PORTB pull-up resistors
Expander_Set_PullUpsPortB(0, 0xFF)
Notes None.
Expander_Set_PullUpsPortAB
Prototype sub procedure Expander_Set_PullUpsPortAB(dim ModuleAddress as byte, dim
PullUps as word)
Description The function sets Port Expander’s PortA and PortB pull up/down resistors.
Parameters - ModuleAddress: 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 PullUps’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.
Returns Nothing.
Requires Port Expander must be initialized. See Expander_Init.
Example ‘ Set Port Expander’s PORTA and PORTB pull-up resistors
Expander_Set_PullUpsPortAB(0, $FFFF)
Notes None.
MikroElektronika
365
mikoBasic PRO for PIC32
Library Example
The example demonstrates how to communicate with Port Expander MCP23S17. Note that Port Expander pins A2 A1
A0 are connected to GND so Port Expander Hardware Address is 0.
program PortExpander
main:
counter = 0
CHECON = 0x32
AD1PCFG = 0xFFFF ‘ Configure AN pins as digital
TRISB = 0x00
LATB = 0xFF
end.
MikroElektronika
366
mikroBasic PRO for PIC32
HW Connection
MikroElektronika
367
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.
Library Routines
- Ps2_Config
- Ps2_Key_Read
MikroElektronika
368
mikroBasic PRO for PIC32
Ps2_Config
Prototype sub procedure Ps2_Config()
Description Initializes the MCU for work with the PS/2 keyboard.
Parameters None.
Returns Nothing.
Requires Global variables:
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
Description The function retrieves information on key pressed.
Parameters - value: holds the value of the key pressed. For characters, numerals, punctuation marks, and space
value will store the appropriate ASCII code. Routine “recognizes” the function of Shift and Caps Lock,
and behaves appropriately. For special function keys see Special Function Keys Table.
- special: is a flag for special function keys (F1, Enter, Esc, etc). If key pressed is one of these,
special will be set to 1, otherwise 0.
- pressed: is set to 1 if the key is pressed, and 0 if it is released.
Returns - 1 if reading of a key from the keyboard was successful
- 0 if no key was pressed
Requires PS/2 keyboard needs to be initialized. See Ps2_Config routine.
Example 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)
Notes None.
MikroElektronika
369
mikoBasic PRO for PIC32
MikroElektronika
370
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.
program PS2_Example
main:
CHECON = 0x32
AD1PCFG = 0xFFFF ‘ Configure AN pins as digital I/O
MikroElektronika
371
mikoBasic PRO for PIC32
HW 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.
Library Routines
- PWM_Init
- PWM_Init_Advanced
- PWM_Set_Duty
- 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
Description Initializes the PWM module with duty ratio 0.
Parameters - freq_hz: PWM frequency in Hz (refer to device datasheet for correct values in respect with Fosc)
- enable_channel_x: number of PWM channel to be initialized. Refer to MCU’s datasheet for
available PWM channels
- timer_prescale: timer prescaler parameter. Valid values: 1, 8, 64, and 256
- use_timer_x: timer to be used with the PWM module. Valid values: 2 (Timer2) and 3 (Timer3)
Returns - 0xFFFF - if timer settings are not valid
- otherwise returns calculated timer period
Requires MCU must have the HW PWM Module.
Example ‘ Initializes the PWM module at 5KHz, channel 1, no clock prescale, timer2
:
dim pwm_period1 as word
...
pwm_period1 = PWM_Init(5000, 1, 0, 2)
Notes Number of available PWM channels depends on MCU. Refer to MCU datasheet for details.
PWM_Init_Advanced
Prototype 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
Description Initializes the PWM module with duty ratio 0.
Parameters - freq_hz: PWM frequency in Hz
- Fpb_kHz: Peripheral Bus Clock frequency in kHz.
- enable_channel_x: number of PWM channel to be initialized. Refer to MCU’s datasheet for
available PWM channels
- timer_prescale: timer prescaler parameter. Valid values: 1, 8, 64, and 256
use_timer_x: timer to be used with the PWM module. Valid values: 2 (Timer2) and 3 (Timer3)
Returns - 0xFFFF - if timer settings are not valid
- otherwise returns calculated timer period
Requires MCU must have the HW PWM Module.
Example
Notes Number of available PWM channels depends on MCU. Refer to MCU datasheet for details.
MikroElektronika
373
mikoBasic PRO for PIC32
PWM_Set_Duty
Prototype sub procedure PWM_Set_Duty(dim duty, channel as word)
Description 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.
Returns Nothing.
Requires MCU must have the HW PWM Module.
PWM_Start
Prototype sub procedure PWM_Start(dim enable_channel_x as byte)
Description Starts PWM at requested channel.
Parameters - enable_channel_x: number of PWM channel
Returns Nothing.
Requires MCU must have the HW PWM Module.
PWM channel must be properly configured. See the PWM_Init and PWM_Set_Duty routines.
Example ‘ start PWM at channel 1
PWM_Start(1)
Notes Number of available PWM channels depends on MCU. Refer to MCU datasheet for details.
PWM_Stop
Prototype sub procedure PWM_Stop(dim disable_channel_x as byte)
Description Stops PWM at requested channel.
Parameters - disable_channel_x: number of PWM channel
Returns Nothing.
Requires MCU must have the HW PWM Module.
Example ‘ stop PWM at channel 1
PWM_Stop(1)
Notes Number of available PWM channels depends on MCU. Refer to MCU datasheet for details.
MikroElektronika
374
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
program Pwm_Demo
dim current_duty, old_duty, current_duty1, old_duty1 as word
pwm_period1, pwm_period2 as word
main:
InitMain()
current_duty = 100 ‘ initial value for current_duty
current_duty1 = 100 ‘ initial value for current_duty1
pwm_period1 = PWM_Init(5000 , 1, 1, 2)
pwm_period2 = PWM_Init(10000, 2, 1, 3)
PWM_Start(1)
PWM_Start(2)
MikroElektronika
375
mikoBasic PRO for PIC32
HW Connection
PWM demonstration
MikroElektronika
376
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 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:
Important:
- The library uses the UART module for communication. The user must initialize the appropriate UART module before
using the RS-485 Library.
- For MCUs with multiple UART modules it is possible to initialize them and then switch by using the UART_Set_Active
routine.
MikroElektronika
377
mikoBasic PRO for PIC32
Library Routines
- RS485Master_Init
- RS485Master_Receive
- RS485Master_Send
- RS485Slave_Init
- RS485Slave_Receive
- RS485Slave_Send
RS485Master_Init
Prototype sub procedure RS485Master_Init()
Description Initializes MCU as a Master for RS-485 communication.
Parameters None.
Returns Nothing.
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.
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_buffer[3]: number of message bytes received, 1–3
- data_buffer[4]: is set to 255 when message is received
- data_buffer[5]: is set to 255 if error has occurred
- 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.
Returns Nothing.
Requires MCU must be initialized as a Master for RS-485 communication. See RS485Master_Init.
Example dim msg as byte[8]
...
RS485Master_Receive(msg)
Notes None
RS485Master_Send
Prototype sub procedure RS485Master_Send(dim byref buffer as byte[20], dim datalen as
byte, dim address as byte)
Description Sends message to Slave(s). Message format can be found at the bottom of this page.
Parameters - data_buffer: data to be sent
- datalen: number of bytes for transmition. Valid values: 0...3.
- slave_address: Slave(s) address
Returns Nothing.
Requires MCU must be initialized as a Master for RS-485 communication. See RS485Master_Init.
It is the user’s responsibility to ensure (by protocol) that only one device sends data via 485 bus at a
time.
Example dim msg as byte[8]
...
‘ send 3 bytes of data to slave with address 0x12
RS485Master_Send(msg, 3, 0x12)
Notes None
MikroElektronika
379
mikoBasic PRO for PIC32
RS485Slave_Init
Prototype sub procedure RS485Slave_Init(dim slave_address as byte)
Description Initializes MCU as a Slave for RS-485 communication.
Parameters - Slave_address: Slave address
Returns Nothing.
Requires Global variables:
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:
The routine automatically adjusts data[4] and data[5] upon every received message. These flags
need to be cleared by software.
Returns Nothing.
Requires MCU must be initialized as a Slave for RS-485 communication. See RS485Slave_Init.
Example dim msg as byte[8]
...
RS485Slave_Read(msg)
Notes None
RS485Slave_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: 0...3.
Returns 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.
Example dim msg as byte[8]
...
‘ send 2 bytes of data to the Master
RS485Slave_Send(msg, 2)
Notes None
MikroElektronika
381
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 (0xAA) 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.
program RS485_Master_Example
‘ Interrupt routine
sub procedure interrupt() iv IVT_UART_2 ilevel 7 ics ICS_SRS
RS485Master_Receive(dat)
U2RXIF_bit = 0 ‘ ensure interrupt not pending
end sub
main:
cnt = 0
CHECON = 0x32
AD1PCFG = 0xFFFF
PORTB = 0
PORTD = 0
TRISB = 0
TRISD = 0
dat[0] = 0xAA
dat[1] = 0xF0
dat[2] = 0x0F
dat[4] = 0 ‘ ensure that message received flag is 0
dat[5] = 0 ‘ ensure that error flag is 0
dat[6] = 0
MikroElektronika
382
mikroBasic PRO for PIC32
RS485Master_Send(dat,1,160)
program RS485_Slave_Example
‘ 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
MikroElektronika
383
mikoBasic PRO for PIC32
main:
CHECON = 0x32
AD1PCFG = 0xFFFF
TRISB = 0
TRISD = 0
PORTB = 0
PORTD = 0
dat[0] = 0xAA
dat[1] = 0xF0
dat[2] = 0x0F
dat[4] = 0 ‘ ensure that message received flag is 0
dat[5] = 0 ‘ ensure that error flag is 0
dat[6] = 0
while (TRUE)
if (dat[5] <> 0) then ‘ if an error detected, signal it by
PORTD = 0xAA ‘ setting portd to 0xAA
dat[5] = 0
end if
if (dat[4] <> 0) then ‘ upon completed valid message receive
dat[4] = 0 ‘ data[4] is set to 0xFF
j = dat[3]
MikroElektronika
384
mikroBasic PRO for PIC32
HW Connection
Example of interfacing PC to PIC32 MCU via RS485 bus with LTC485 as RS-485 transceiver
MikroElektronika
385
mikoBasic PRO for PIC32
PACKAGE:
--------
_START_BYTE 0x96
ADDRESS
DATALEN
[DATA1] ‘ if exists
[DATA2] ‘ if exists
[DATA3] ‘ if exists
CRC
_STOP_BYTE 0xA9
DATALEN bits
------------
bit7 = 1 MASTER SENDS
0 SLAVE SENDS
bit6 = 1 ADDRESS WAS XORed with 1, IT WAS EQUAL TO _START_BYTE or _STOP_BYTE
0 ADDRESS UNCHANGED
bit5 = 0 FIXED
bit4 = 1 DATA3 (if exists) WAS XORed with 1, IT WAS EQUAL TO _START_BYTE or _STOP_
BYTE
0 DATA3 (if exists) UNCHANGED
bit3 = 1 DATA2 (if exists) WAS XORed with 1, IT WAS EQUAL TO _START_BYTE or _STOP_
BYTE
0 DATA2 (if exists) UNCHANGED
bit2 = 1 DATA1 (if exists) WAS XORed with 1, IT WAS EQUAL TO _START_BYTE or _STOP_
BYTE
0 DATA1 (if exists) UNCHANGED
bit1bit0 = 0 to 3 NUMBER OF DATA BYTES SEND
CRC generation :
----------------
crc_send = datalen xor address
crc_send = crc_send xor data[0] ‘ if exists
crc_send = crc_send xor data[1] ‘ if exists
crc_send = crc_send xor data[2] ‘ if exists
crc_send = crc_send not crc_send
if ((crc_send = START_BYTE) or (crc_send = STOP_BYTE)) then
crc_send = crc_send + 1
end if
NOTE: DATALEN<4..0> can not take the START_BYTE<4..0> or STOP_BYTE<4..0> values.
MikroElektronika
386
mikroBasic PRO for PIC32
Important:
- This library implements time-based activities, so interrupts need to be disabled when using Software I²C.
- All Software I²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 may also be required.
- Every Software I²C library routine has its own counterpart in Hardware I²C library, except I2C_Repeated_Start.
Soft_I2C_Start is used instead of I2C_Repeated_Start.
- Working clock frequency of the Software I²C is 20kHz.
Library Routines
- Soft_I2C_Init
- Soft_I2C_Start
- Soft_I2C_Read
- Soft_I2C_Write
- Soft_I2C_Stop
- Soft_I2C_Break
MikroElektronika
387
mikoBasic PRO for PIC32
Soft_I2C_Init
Prototype sub procedure Soft_I2C_Init()
Description Configures the software I²C module.
Parameters None.
Returns Nothing.
Requires Global variables:
Soft_I2C_Start
Prototype sub procedure Soft_I2C_Start()
Description Determines if the I²C bus is free and issues START signal.
Parameters None.
Returns Nothing.
Requires Software I²C must be configured before using this function. See Soft_I2C_Init routine.
Example ‘ Issue START signal
Soft_I2C_Start()
Notes None
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 I²C must be configured before using this function. See Soft_I2C_Init routine.
Also, START signal needs to be issued in order to use this function. See Soft_I2C_Start routine.
Example dim take as byte
...
‘ Read data and send the not_acknowledge signal
take = Soft_I2C_Read(0)
Notes None
Soft_I2C_Write
Prototype sub function Soft_I2C_Write(dim data_ as byte) as byte
Description Sends data byte via the I²C bus.
Parameters - data_: data to be sent
Returns - 0 if there were no errors.
- 1 if write collision was detected on the I²C bus.
Requires Soft I²C must be configured before using this function. See Soft_I2C_Init routine.
Also, START signal needs to be issued in order to use this function. See Soft_I2C_Start routine.
Example dim data_, error as byte
...
error = Soft_I2C_Write(data_)
error = Soft_I2C_Write($A3)
Notes None
Soft_I2C_Stop
Prototype sub procedure Soft_I2C_Stop()
Description Issues STOP signal.
Parameters None.
Returns Nothing.
Requires Soft I²C must be configured before using this function. See Soft_I2C_Init routine.
Example ‘ Issue STOP signal
Soft_I2C_Stop()
Notes None
MikroElektronika
389
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.
Parameters None.
Returns Nothing.
Requires Nothing.
Example dim data1, error, counter as byte
main:
...
Notes Interrupts should be disabled before using Software I²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.
program RTC_Read
dim seconds, minutes, hours, day, month_, year as byte ‘ Global date/time variables
MikroElektronika
391
mikoBasic PRO for PIC32
seconds = ((seconds and 0xF0) >> 4)*10 + (seconds and 0x0F) ‘ Transform seconds
minutes = ((minutes and 0xF0) >> 4)*10 + (minutes and 0x0F) ‘ Transform months
hours = ((hours and 0xF0) >> 4)*10 + (hours and 0x0F) ‘ Transform hours
year = (day and 0xC0) >> 6 ‘ Transform year
day = ((day and 0x30) >> 4)*10 + (day and 0x0F) ‘ Transform day
month_ = ((month_ and 0x10) >> 4)*10 + (month_ and 0x0F) ‘ Transform month
end sub
Delay_ms(1000)
MikroElektronika
392
mikroBasic PRO for PIC32
Library configuration:
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.
Library Routines
- Soft_SPI_Init
- Soft_SPI_Read
- Soft_SPI_Write
MikroElektronika
393
mikoBasic PRO for PIC32
Soft_SPI_Init
Prototype sub procedure Soft_SPI_Init()
Description Routine initializes the software SPI module.
Parameters None.
Returns Nothing.
Requires Global variables:
Notes None.
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.
Parameters - sdata: data to be sent.
Returns Byte received via the SPI bus.
Requires Soft SPI must be initialized before using this function. See Soft_SPI_Init routine.
Example 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)
Notes None.
Soft_SPI_Write
Prototype sub procedure Soft_SPI_Write(dim data_ as byte)
Description This routine sends one byte via the Software SPI bus.
Parameters - sdata: data to be sent.
Returns Nothing.
Requires Soft SPI must be initialized before using this function. See Soft_SPI_Init.
Example ‘ Write a byte to the Soft SPI bus
Soft_SPI_Write($AA)
Notes None
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.
MikroElektronika
395
mikoBasic PRO for PIC32
main:
CHECON = 0x32
AD1PCFG = 0xFFFF ‘ Configure AN pins as digital
InitMain() ‘ Perform main initialization
MikroElektronika
396
mikroBasic PRO for PIC32
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
Returns - 2 - error, requested baud rate is too low
- 1 - error, requested baud rate is too high
- 0 - successful initialization
Requires Nothing.
Example This will initialize software UART and establish the communication at 9600 bps:
MikroElektronika
397
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
Returns Byte received via UART.
Requires Software UART must be initialized before using this function. See the Soft_UART_Init routine.
Example dim data_ as byte
error as word
...
‘ wait until data is received
do
data_ = Soft_UART_Read(error)
loop until (error = 0)
Notes 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)
Description This routine sends one byte via the Software UART bus.
Parameters - udata: data to be sent.
Returns Nothing.
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.
Example dim some_byte as byte
...
some_byte = $0A
‘ Write a byte via Soft UART
Soft_UART_Write(some_byte)
Notes 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.
Parameters None.
Returns Nothing.
Requires Nothing.
Example dim data1, error, counter as byte
main:
...
Notes The Software UART library implements time-based activities, so interrupts need to be disabled when
using it.
MikroElektronika
399
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 › USART Terminal or simply click the USART Terminal Icon .
program Soft_UART
main:
CHECON = 0x32
AD1PCFG = 0xFFFF ‘ Configure AN pins as digital I/O
for counter = “z” to “A” step-1 ‘ Send bytes from “z” downto “A”
Soft_UART_Write(counter)
Delay_ms(100)
next counter
MikroElektronika
400
mikroBasic 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)
Description Configures the appropriate MCU pin for sound generation.
Parameters - snd_port: sound output port address
- snd_pin: sound output pin
Returns Nothing.
Requires Nothing.
Example ‘ Initialize the pin RD3 for playing sound
Sound_Init(PORTD, 3)
Notes None.
Sound_Play
Prototype sub procedure Sound_Play(dim freq_in_hz, duration_ms as word)
Description 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)
Returns Nothing.
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.
Example ‘ Play sound of 1KHz in duration of 100ms
Sound_Play(1000, 100)
Notes None.
MikroElektronika
401
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.
program Sound
main:
CHECON = 0x32
AD1PCFG = 0xFFFF ‘ Configure AN pins as digital I/O
MikroElektronika
402
mikroBasic PRO for PIC32
Sound_Init(PORTD, 3)
Sound_Play(880, 1000)
MikroElektronika
403
mikoBasic PRO for PIC32
HW Connection
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_Active function (both SPI modules have
to be previously initialized).
Library Routines
- SPIx_Init
- SPIx_Init_Advanced
- SPIx_Read
- SPIx_Write
- SPI_Set_Active
MikroElektronika
405
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.
Returns Nothing.
Requires MCU must have the SPI1 module.
Example ‘ Initialize the SPI1 module with default settings
SPI1_Init()
Notes 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
406
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)
Description Configures and initializes the SPI module with user defined settings.
Parameters Parameters master_mode, data_mode, clock_divider, slave_select, data_sample,
clock_idle and determine the working mode for SPI.
The master_mode parameter determines the working mode for SPI module.
Master/Slave mode
Description Predefined library const
Master mode _SPI_MASTER
Slave mode _SPI_SLAVE
The parameter data_mode the data length mode, which can be 8-bits (per transmitions cycle), 16-bits
or 32-bits.
The parameter clock_divider determines the value of the SPI clock speed. Used only in the Master
Mode.
Clock Divider Value
Valid values from 2 to 1024
The parameter slave_select determines whether the Slave Select (SS) pin is used in communication.
Valid in the Slave Mode only.
The parameter data_sample determines the sample moment (phase) of input data.
MikroElektronika
407
mikoBasic PRO for PIC32
Parameters The parameter clock_idle determines the behaviour of the SPI clock (CLK) line in IDLE phase.
Clock Polarity
Description Predefined library const
IDLE state is Lo, ACTIVE state is Hi _SPI_CLK_IDLE_LOW
IDLE 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
Description Predefined library const
Data is valid on ACTIVE-to-IDLE transition _SPI_ACTIVE_2_IDLE
Data is valid on IDLE-to-ACTIVE transition _SPI_IDLE_2_ACTIVE
Returns Nothing.
Requires MCU must have the SPI module.
Example ‘ Set SPI1 to the Master Mode, data length is 16-bit, clock = Fcy (no clock
scaling), data sampled in the middle of interval, clock IDLE state high and
data transmitted at low to high clock edge:
SPI1_Init_Advanced(_SPI_MASTER, _SPI_16_BIT, 1, _SPI_SS_DISABLE, _SPI_DATA_
SAMPLE_MIDDLE, _SPI_CLK_IDLE_HIGH, _SPI_ACTIVE_2_IDLE)
Notes 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 - data_out: dummy data for clock generation (see device Datasheet for SPI modules implementation
details)
Returns Received data.
Requires Routine requires at least one SPI module.
Used SPI module must be initialized before using this function. See the SPIx_Init and SPIx_Init_
Advanced routines.
Example ‘ read a byte from the SPI bus
dim take, buffer as byte
...
take = SPI1_Read(buffer)
Notes SPI library routines require you to specify the module you want to use. To select the desired SPI
module, simply change the letter x in the routine prototype for a number from 1 to 3.
Number of SPI modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
SPIx_Write
Prototype sub procedure SPIx_Write(dim data_out as word)
Description Writes one word or byte (depending on mode set by init routines) via the SPI bus.
Parameters - data_out: data to be sent
Returns Nothing.
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.
Example ‘ write a byte to the SPI bus
dim buffer as byte
...
SPI1_Write(buffer)
Notes 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
409
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:
Used SPI module must be initialized before using this function. See the SPIx_Init and SPIx_Init_
Advanced routines.
Example SPI_Set_Active(@SPI1_Read, @SPI1_Write) ‘ Sets the SPI1 module active
Notes Number of SPI modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
Library Example
The code demonstrates how to use SPI library functions for communication between SPI2 module of the MCU and
MCP4921 DAC chip.
program Sound
MikroElektronika
410
mikroBasic PRO for PIC32
main:
CHECON = 0x32
AD1PCFG = 0xFFFF ‘ Configure AN pins as digital I/O
Sound_Init(PORTD, 3)
Sound_Play(880, 1000)
HW Connection
SPI HW connection
MikroElektronika
412
mikroBasic PRO for PIC32
The ENC28J60 meets all of the IEEE 802.3 specifications. It incorporates a number of packet filtering schemes to limit
incoming packets. It also provides an internal DMA module for fast data throughput and hardware 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 (ENC28J60). 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.
- IPv4 protocol.
- ARP requests.
- ICMP echo requests.
- UDP requests.
- TCP requests (no stack, no packet reconstruction).
- ARP client with cache.
- DNS client.
- UDP client.
- DHCP client.
- packet fragmentation is NOT supported.
Important:
- Global library variable SPI_Ethernet_userTimerSec is used to keep track of time for all client implementations
(ARP, DNS, UDP and DHCP). It is user responsibility to increment this variable each second in it’s code if any of the
clients is used.
- For advanced users there is __EthEnc28j60Private.mbas unit in Uses folder of the compiler with description of
all routines and global variables, relevant to the user, implemented in the SPI Ethernet Library.
- The appropriate 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.
MikroElektronika
413
mikoBasic PRO for PIC32
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_getIpAddress
- SPI_Ethernet_getGwIpAddress
- SPI_Ethernet_getDnsIpAddress
- SPI_Ethernet_getIpMask
- 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 ENC28J60 controller. This function is internaly splited into 2
parts to help linker when coming short of memory.
ENC28J60 controller settings (parameters not mentioned here are set to default):
MikroElektronika
415
mikoBasic PRO for PIC32
The SPI module needs to be initialized. See the SPIx_Init and SPIx_Init_Advanced routines.
Example ‘ mE ehternet NIC pinout
dim SPI_Ethernet_RST as sbit at LATF0_bit
dim SPI_Ethernet_CS as sbit at LATF1_bit
dim SPI_Ethernet_RST_Direction as sbit at TRISF0_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
myIpAddr[0] = 192
myIpAddr[1] = 168
myIpAddr[2] = 20
myIpAddr[3] = 60
SPI1_Init()
SPI_Ethernet_Init(myMacAddr, myIpAddr, SPI_Ethernet_FULLDUPLEX)
Notes None.
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 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 ENC28J60 module. The ENC28J60 module
should be properly cofigured by the means of SPI_Ethernet_Init routine.
Parameters - enFlt: network traffic/receive filter flags. Each bit corresponds to the appropriate network traffic/
receive filter:
Returns Nothing.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example SPI_Ethernet_Enable(_SPI_Ethernet_CRC or _SPI_Ethernet_UNICAST) ‘ enable
CRC checking and Unicast traffic
Notes Advanced filtering available in the ENC28J60 module such as Pattern Match, Magic Packet
and Hash Table can not be enabled by this routine. Additionaly, all filters, except CRC, enabled
with this routine will work in OR mode, which means that packet will be received if any of the enabled
filters accepts it.
This routine will change receive filter configuration on-the-fly. It will not, in any way, mess with enabling/
disabling receive/transmit logic or any other part of the ENC28J60 module. The ENC28J60 module
should be properly cofigured by the means of SPI_Ethernet_Init routine.
MikroElektronika
417
mikoBasic PRO for PIC32
SPI_Ethernet_Disable
Prototype sub procedure SPI_Ethernet_Disable(dim disFlt as byte)
Description This is MAC module routine. This routine disables appropriate network traffic on the ENC28J60
module by the means of it’s receive filters (unicast, multicast, broadcast, crc). Specific type of network
traffic will be disabled if a corresponding bit of this routine’s input parameter is set. Therefore, more
than one type of network traffic can be disabled at the same time. For this purpose, predefined library
constants (see the table below) can be ORed to form appropriate input value.
Parameters - disFlt: network traffic/receive filter flags. Each bit corresponds to the appropriate network traffic/
receive filter:
Returns Nothing.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example SPI_Ethernet_Disable(_SPI_Ethernet_CRC or _SPI_Ethernet_UNICAST) ‘ disable
CRC checking and Unicast traffic
Notes 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 ENC28J60 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:
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).
Parameters - v: value to store
Returns Nothing.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example dim data as byte
...
SPI_Ethernet_putByte(data) ‘ put an byte into ENC28J60 buffer
Notes None.
MikroElektronika
419
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 ENC28J60 RAM starting from
current ENC28J60 write pointer (EWRPT) location.
Parameters - ptr: RAM buffer containing bytes to be written into ENC28J60 RAM.
- n: number of bytes to be written.
Returns Nothing.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example dim
buffer as byte[17]
...
buffer = “mikroElektronika”
...
SPI_Ethernet_putBytes(buffer, 16) ‘ put an RAM array into ENC28J60
buffer
Notes None.
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 ENC28J60 RAM starting
from current ENC28J60 write pointer (EWRPT) location.
Parameters - ptr: const buffer containing bytes to be written into ENC28J60 RAM.
- n: number of bytes to be written.
Returns Nothing.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example const
buffer as byte[17]
...
buffer = “mikroElektronika”
...
SPI_Ethernet_putConstBytes(buffer, 16) ‘ put a const array into ENC28J60 buffer
Notes None.
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 ENC28J60 RAM
starting from current ENC28J60 write pointer (EWRPT) location.
Parameters - ptr: string to be written into ENC28J60 RAM.
Returns Number of bytes written into ENC28J60 RAM.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example dim
buffer as string[16]
...
buffer = “mikroElektronika”
...
SPI_Ethernet_putString(buffer) ‘ put a RAM string into ENC28J60 buffer
Notes None.
MikroElektronika
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 ENC28J60
RAM starting from current ENC28J60 write pointer (EWRPT) location.
Parameters - ptr: const string to be written into ENC28J60 RAM.
Returns Number of bytes written into ENC28J60 RAM.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example const
buffer as string[16]
...
buffer = “mikroElektronika”
...
SPI_Ethernet_putConstString(buffer) ‘ put a const string into ENC28J60 buffer
Notes None.
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).
Parameters None.
Returns Byte read from ENC28J60 RAM.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example dim buffer as byte<>
...
buffer = SPI_Ethernet_getByte() ‘ read a byte from ENC28J60 buffer
Notes None.
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 ENC28J60 RAM starting from
given address. If value of 0xFFFF is passed as the address parameter, the reading will start from
current ENC28J60 read pointer (ERDPT) location.
Parameters - ptr: buffer for storing bytes read from ENC28J60 RAM.
- addr: ENC28J60 RAM start address. Valid values: 0..8192.
- n: number of bytes to be read.
Returns Nothing.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example dim
buffer as byte[16]
...
SPI_Ethernet_getBytes(buffer, 0x100, 16) ‘ read 16 bytes, starting from
address 0x100
Notes None.
MikroElektronika
421
mikoBasic PRO for PIC32
SPI_Ethernet_UserTCP
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.
- reqLength: TCP request data field length.
- flags: structure consisted of two bit fields :
structure TEthPktFlags
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
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 bit fields :
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
Returns - 0 - there should not be a reply to the request.
- Length of UDP reply data field - otherwise.
Requires 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.
Notes The function source code is provided with appropriate example projects. The code should be adjusted
by the user to achieve desired reply.
MikroElektronika
423
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 - TCPHandler: TCP request handler
- UDPHandler: UDP request handler.
Returns Nothing.
Requires SPI_Ethernet_UserTCP and SPI_Ethernet_UserUDP have to be previously defined.
Example SPI_Ethernet_setUserHandlers(@SPI_Ethernet_UserTCP, @SPI_Ethernet_UserUDP)
Notes Since all libraries are built for SSA, SSA restrictions regarding function pointers dictate that modules
that use SPI_Ethernet_setUserHandlers must also be built for SSA.
SPI_Ethernet_getIpAddress
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
address.
Parameters None.
Returns Pointer to the global variable holding IP address.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example dim
ipAddr as byte[4] ‘ user IP address buffer
...
memcpy(ipAddr, SPI_Ethernet_getIpAddress(), 4) ‘ fetch IP address
Notes 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!
Ethernet_getGwIpAddress
Prototype sub function SPI_Ethernet_getGwIpAddress() as word
Description This routine should be used when DHCP server is present on the network to fetch assigned gateway
IP address.
Parameters None.
Returns Pointer to the global variable holding gateway IP address.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example dim
gwIpAddr as byte[4] ‘ user gateway IP address buffer
...
memcpy(gwIpAddr, SPI_Ethernet_getGwIpAddress(), 4) ‘ fetch gateway IP
address
Notes 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
424
mikroBasic PRO for PIC32
SPI_Ethernet_getDnsIpAddress
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.
Parameters None.
Returns Pointer to the global variable holding DNS IP address.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example dim
dnsIpAddr as byte[4] ‘ user DNS IP address buffer
...
memcpy(dnsIpAddr, SPI_Ethernet_getDnsIpAddress(), 4) ‘ fetch DNS server
address
Notes 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_getIpMask
Prototype sub function SPI_Ethernet_getIpMask() as word
Description This routine should be used when DHCP server is present on the network to fetch assigned IP subnet
mask.
Parameters None.
Returns Pointer to the global variable holding IP subnet mask.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
MikroElektronika
425
mikoBasic PRO for PIC32
SPI_Ethernet_confNetwork
Prototype sub procedure SPI_Ethernet_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.
- gwIpAddr gateway IP address.
- dnsIpAddr: DNS IP address.
Returns Nothing.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example dim
ipMask as byte[4] ‘ network mask (for example : 255.255.255.0)
gwIpAddr as byte[4] ‘ gateway (router) IP address
dnsIpAddr as byte[4] ‘ DNS server IP address
...
gwIpAddr[0] = 192
gwIpAddr[1] = 168
gwIpAddr[2] = 20
gwIpAddr[3] = 6
dnsIpAddr[0] = 192
dnsIpAddr[1] = 168
dnsIpAddr[2] = 20
dnsIpAddr[3] = 100
ipMask[0] = 255
ipMask[1] = 255
ipMask[2] = 255
ipMask[3] = 0
...
SPI_Ethernet_confNetwork(ipMask, gwIpAddr, dnsIpAddr) ‘ set network
configuration parameters
Notes 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 3 entries. For ARP cash structure refer to “eth_enc28j60LibDef.mbas” file
in the compiler’s Uses folder.
Parameters - ip: IP address to be resolved.
- tmax: time in seconds to wait for an reply.
Returns - MAC address behind the IP address - the requested IP address was resolved.
- 0 - otherwise.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example dim
IpAddr as byte[4] ‘ IP address
...
IpAddr[0] = 192
IpAddr[0] = 168
IpAddr[0] = 1
IpAddr[0] = 1
...
SPI_Ethernet_arpResolve(IpAddr, 5) ‘ get MAC address behind the above IP
address, wait 5 secs for the response
Notes 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
Description This is UDP module routine. It sends an UDP packet on the network.
Parameters - destIP: 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.
Returns - 1 - UDP packet was sent successfully.
- 0 - otherwise.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example dim
IpAddr as byte[4] ‘ remote IP address
...
IpAddr[0] = 192
IpAddr[0] = 168
IpAddr[0] = 1
IpAddr[0] = 1
...
SPI_Ethernet_sendUDP(IpAddr, 10001, 10001, “Hello”, 5) ‘ send Hello
message to the above IP address, from UDP port 10001 to UDP port 10001
Notes None.
MikroElektronika
427
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.
Returns - pointer to the location holding the IP address - the requested host name was resolved.
- 0 - otherwise.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example 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)
Notes 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
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.
UDP port 68 is used as DHCP client port and UDP port 67 is used as DHCP server port.
Parameters - tmax: time in seconds to wait for an reply.
Returns - 1 - network parameters were obtained successfully.
- 0 - otherwise.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example ...
SPI_Ethernet_initDHCP(5) ‘ get network configuration from DHCP server, wait
5 sec for the response
...
Notes 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 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.
Parameters None
Returns - 0 - lease time has not expired yet.
- 1 - lease time has expired, it’s time to renew it.
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example while true
...
if(SPI_Ethernet_doDHCPLeaseTime() <> 0) then
... ‘ it’s time to renew the IP address lease
end if
wend
Notes None.
MikroElektronika
429
mikoBasic PRO for PIC32
SPI_Ethernet_renewDHCP
Prototype sub function SPI_Ethernet_renewDHCP(dim tmax as byte) as byte
Description This is DHCP module routine. It sends IP address lease time renewal request to DHCP server.
Parameters - tmax: time in seconds to wait for an reply.
Returns - 1 - upon success (lease time was renewed).
- 0 - otherwise (renewal request timed out).
Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
Example 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
end if
...
wend
Notes None.
Library Example
This code shows how to use the Ethernet mini library:
- returns the request in upper char with a header made of remote host IP & port number
- the board will reply to HTTP requests on port 80, GET method with pathnames :
program HTTP_Demo
‘ ***********************************
‘ * RAM variables
‘ *
MikroElektronika
430
mikroBasic PRO for PIC32
‘ ************************************************************
‘ * 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”+chr(10)+chr(10) ‘ TEXT MIME type
const httpMethod as string[5] = “GET /”
‘ *
‘ * web page, splited into 2 parts :
‘ * when coming short of ROM, fragmented data is handled more efficiently by linker
‘ *
‘ * this HTML page calls the boards to get its status, and builds itself with
javascript
‘ *
const indexPage as string[766] =
“<meta http-equiv=” + Chr(34) + “refresh” + Chr(34) + “ content=”
+ Chr(34) + “3;url=http://192.168.20.60” + Chr(34) + “>” +
“<HTML><HEAD></HEAD><BODY>”+
“<h1>PIC32 + ENC28J60 Mini Web Server</h1>”+
“<a href=/>Reload</a>”+
“<script src=/s></script>”+
“<table><tr><td valign=top><table border=1 style=”+chr(34)+”font-
size:20px ;font-family: terminal ;”+chr(34)+”> “+
“<tr><th colspan=2>ADC</th></tr>”+
“<tr><td>AN0</td><td><script>document.write(AN0)</script></td></tr>”+
“<tr><td>AN1</td><td><script>document.write(AN1)</script></td></tr>”+
“</table></td><td><table border=1 style=”+chr(34)+”font-size:20px
;font-family: terminal ;”+chr(34)+”> “+
“<tr><th colspan=2>PORTB</th></tr>”+
“<script>”+
“var str,i;”+
“str=”+chr(34)+chr(34)+”; “+
“for(i=2;i<10;i++)”+
“{str+=”+chr(34)+”<tr><td bgcolor=pink>BUTTON
#”+chr(34)+”+i+”+chr(34)+”</td>”+chr(34)+”; “+
“if(PORTB&(1<<i)){str+=”+chr(34)+”<td bgcolor=red>ON”+chr(34)+”;}”+
“else {str+=”+chr(34)+”<td bgcolor=#cccccc>OFF”+chr(34)+”;}”+
“str+=”+chr(34)+”</td></tr>”+chr(34)+”;}”+
“document.write(str) ;”+
“</script>”
MikroElektronika
431
mikoBasic PRO for PIC32
‘ *******************************************
‘ * user defined functions
‘ *
‘ *
‘ * this function is called by the library
‘ * the user accesses to the HTTP request by successive calls to Spi_Ethernet_
getByte()
‘ * the user puts data in the transmit buffer by successive calls to Spi_Ethernet_
putByte()
‘ * the function must return the length in bytes of the HTTP reply, or 0 if nothing to
transmit
‘ *
‘ * if you don’t need to reply to HTTP requests,
‘ * just define this function with a return(0) as single statement
‘ *
‘ *
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
txt as string[11]
result = 0
MikroElektronika
432
mikroBasic PRO for PIC32
‘ 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[i] = 0
MikroElektronika
433
mikoBasic PRO for PIC32
‘ *
‘ * this function is called by the library
‘ * the user accesses to the UDP request by successive calls to Spi_Ethernet_getByte()
‘ * the user puts data in the transmit buffer by successive calls to Spi_Ethernet_
putByte()
‘ * the function must return the length in bytes of the UDP reply, or 0 if nothing to
transmit
‘ *
MikroElektronika
434
mikroBasic PRO for PIC32
dyna[11] = “.”
byteToStr(remoteHost[3], txt) ‘ second
dyna[12] = txt[0]
dyna[13] = txt[1]
dyna[14] = txt[2]
‘ the total length of the request is the length of the dynamic string plus the text of
the request
result = 28 + reqLength
‘ then puts the request string converted into upper char into the transmit buffer
while(reqLength <> 0)
Spi_Ethernet_putByte(Spi_Ethernet_getByte())
reqLength = reqLength - 1
MikroElektronika
435
mikoBasic PRO for PIC32
wend
main:
CHECON = 0x32
AD1PCFG = 0xFFFC ‘ all digital but RB1(AN1) and RB0 (AN0)
PORTB = 0
TRISB = 0xFFFF ‘ set PORTB as input for buttons and adc
PORTD = 0
TRISD = 0 ‘ set PORTD as output
ADC1_Init()
httpCounter = 0
‘ set IP address
myIpAddr[0] = 192
myIpAddr[1] = 168
myIpAddr[2] = 20
myIpAddr[3] = 60
MikroElektronika
436
mikroBasic PRO for PIC32
‘ *
‘ * starts ENC28J60 with :
‘ * reset bit on PORTC.B0
‘ * CS bit on PORTC.B1
‘ * my MAC & IP address
‘ * full duplex
‘ *
‘ *
‘ * add your stuff here if needed
‘ * SPI_Ethernet_doPacket() must be called as often as possible
‘ * otherwise packets could be lost
‘ *
wend
end.
HW Connection
MikroElektronika
437
mikoBasic PRO for PIC32
The ENC24J600 meets all of the IEEE 802.3 specifications applicable to 10Base-T and 100Base-TX Ethernet. It
incorporates a number of packet filtering schemes to limit incoming packets. It also provides an internal, 16-bit wide
DMA module for fast data throughput and hardware assisted IP checksum calculations. Communication with the host
controller is implemented via two interrupt pins and the SPI, with data rates of 10/100 Mb/s. Two dedicated pins are
used for LED link and network activity indication.
This library is designed to simplify handling of the underlying hardware (ENC24J600). It works with any PIC32 with
integrated SPI and more than 4 Kb ROM memory. 38 to 40 MHz clock is recommended to get from 8 to 10 Mhz SPI
clock, otherwise PIC32 should be clocked by ENC24J600 clock output due to its silicon bug in SPI hardware. If you try
lower PIC32 clock speed, there might be board hang or miss some requests.
- IPv4 protocol.
- ARP requests.
- ICMP echo requests.
- UDP requests.
- TCP requests (no stack, no packet reconstruction).
- ARP client with cache.
- DNS client.
- UDP client.
- DHCP client.
- packet fragmentation is NOT supported.
Important:
- Global library variable SPI_Ethernet_24j600_userTimerSec is used to keep track of time for all client
implementations (ARP, DNS, UDP and DHCP). It is user responsibility to increment this variable each second in it’s
code if any of the clients is used.
- For advanced users there is __EthEnc24j600Private.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.
- For MCUs with multiple SPI modules it is possible to initialize them and then switch by using the SPI_Set_
Active()routine.
MikroElektronika
438
mikroBasic PRO for PIC32
MikroElektronika
439
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_getIpAddress
- SPI_Ethernet_24j600_getGwIpAddress
- SPI_Ethernet_24j600_getDnsIpAddress
- SPI_Ethernet_24j600_getIpMask
- 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 sub procedure SPI_Ethernet_24j600_Init(dim mac as ^byte, dim ip as ^byte,
dim fullDuplex as byte)
Description 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):
Note:
- 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.
MikroElektronika
441
mikoBasic PRO for PIC32
Returns Nothing.
Requires Global variables:
The SPI module needs to be initialized. See the SPIx_Init and SPIx_Init_Advanced routines.
Example ‘ mE ehternet NIC pinout
dim SPI_Ethernet_24j600_CS as sbit at LATF1_bit
dim SPI_Ethernet_24j600_CS_Direction as sbit at TRISF1_bit
‘ end mE ehternet NIC pinout
myIpAddr[0] = 192
myIpAddr[1] = 168
myIpAddr[2] = 20
myIpAddr[3] = 60
SPI1_Init()
SPI_Ethernet_24j600_Init(myMacAddr, myIpAddr, SPI_Ethernet_24j600_MANUAL_
NEGOTIATION and SPI_Ethernet_24j600_FULLDUPLEX and SPI_Ethernet_24j600_
SPD100)
Notes None.
MikroElektronika
442
mikroBasic PRO for PIC32
SPI_Ethernet_24j600_Enable
Prototype sub procedure SPI_Ethernet_24j600_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 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 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 ENC24J600 module
should be properly cofigured by the means of SPI_Ethernet_24j600_Init routine.
Parameters - enFlt: network traffic/receive filter flags. Each bit corresponds to the appropriate network traffic/
receive filter:
Returns Nothing.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example SPI_Ethernet_24j600_Enable(_SPI_Ethernet_24j600_CRC or _SPI_Ethernet_24j600_
UNICAST) ‘ enable CRC checking and Unicast traffic
Notes 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 ENC24J600 module
should be properly cofigured by the means of SPI_Ethernet_24j600_Init routine.
MikroElektronika
443
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 ENC24J600
module by the means of it’s receive filters (unicast, multicast, broadcast, crc). Specific type of network
traffic will be disabled if a corresponding bit of this routine’s input parameter is set. Therefore, more
than one type of network traffic can be disabled at the same time. For this purpose, predefined library
constants (see the table below) can be ORed to form appropriate input value.
Parameters - disFlt: network traffic/receive filter flags. Each bit corresponds to the appropriate network traffic/
receive filter:
Returns Nothing.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example SPI_Ethernet_24j600_Disable(_SPI_Ethernet_24j600_CRC or _SPI_
Ethernet_24j600_UNICAST) ‘ disable CRC checking and Unicast traffic
Notes 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 ENC24J600 module. The ENC24J600 module
should be properly cofigured by the means of SPI_Ethernet_24j600_Init routine.
MikroElektronika
444
mikroBasic PRO for PIC32
SPI_Ethernet_24j600_doPacket
Prototype sub function SPI_Ethernet_24j600_doPacket() as byte
Description This is MAC module routine. It processes next received packet if such exists. Packets are processed
in the following manner:
SPI_Ethernet_24j600_putByte
Prototype sub procedure SPI_Ethernet_24j600_putByte(dim v as byte)
Description This is MAC module routine. It stores one byte to address pointed by the current ENC24J600 write
pointer (EWRPT).
Parameters - v: value to store
Returns Nothing.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example dim data as byte
...
SPI_Ethernet_24j600_putByte(data) ‘ put an byte into ENC24J600 buffer
Notes None.
MikroElektronika
445
mikoBasic PRO for PIC32
SPI_Ethernet_24j600_putBytes
Prototype sub procedure SPI_Ethernet_24j600_putBytes(dim ptr as ^byte, dim n as
word)
Description This is MAC module routine. It stores requested number of bytes into ENC24J600 RAM starting from
current ENC24J600 write pointer (EWRPT) location.
Parameters - ptr: RAM buffer containing bytes to be written into ENC24J600 RAM.
- n: number of bytes to be written.
Returns Nothing.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example dim
buffer as byte[17]
...
buffer = “mikroElektronika”
...
SPI_Ethernet_24j600_putBytes(buffer, 16) ‘ put an RAM array into ENC24J600
buffer
Notes None.
SPI_Ethernet_24j600_putConstBytes
Prototype sub procedure SPI_Ethernet_24j600_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 ENC24J600 write pointer (EWRPT) location.
Parameters - ptr: const buffer containing bytes to be written into ENC24J600 RAM.
- n: number of bytes to be written.
Returns Nothing.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example const
buffer as byte[17]
...
buffer = “mikroElektronika”
...
SPI_Ethernet_24j600_putConstBytes(buffer, 16) ‘ put a const array into
ENC24J600 buffer
Notes None.
MikroElektronika
446
mikroBasic PRO for PIC32
SPI_Ethernet_24j600_putString
Prototype sub function SPI_Ethernet_24j600_putString(dim ptr as ^byte) as word
Description This is MAC module routine. It stores whole string (excluding null termination) into ENC24J600 RAM
starting from current ENC24J600 write pointer (EWRPT) location.
Parameters - ptr: string to be written into ENC24J600 RAM.
Returns Number of bytes written into ENC24J600 RAM.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example dim
buffer as string[16]
...
buffer = “mikroElektronika”
...
SPI_Ethernet_24j600_putString(buffer) ‘ put a RAM string into ENC24J600
buffer
Notes None.
SPI_Ethernet_24j600_putConstString
Prototype sub function SPI_Ethernet_24j600_putConstString(const ptr as ^byte) as word
Description This is MAC module routine. It stores whole const string (excluding null termination) into ENC24J600
RAM starting from current ENC24J600 write pointer (EWRPT) location.
Parameters - ptr: const string to be written into ENC24J600 RAM.
Returns Number of bytes written into ENC24J600 RAM.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example const
buffer as string[16]
...
buffer = “mikroElektronika”
...
SPI_Ethernet_24j600_putConstString(buffer) ‘ put a const string into
ENC24J600 buffer
Notes None.
SPI_Ethernet_24j600_getByte
Prototype sub function SPI_Ethernet_24j600_getByte() as byte
Description This is MAC module routine. It fetches a byte from address pointed to by current ENC24J600 read
pointer (ERDPT).
Parameters None.
Returns Byte read from ENC24J600 RAM.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example dim buffer as byte<>
...
buffer = SPI_Ethernet_24j600_getByte() ‘ read a byte from ENC24J600 buffer
Notes None.
MikroElektronika
447
mikoBasic PRO for PIC32
SPI_Ethernet_24j600_getBytes
Prototype sub procedure SPI_Ethernet_24j600_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 ENC24J600 RAM starting from
given address. If value of 0xFFFF 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 ENC24J600 RAM.
- addr: ENC24J600 RAM start address. Valid values: 0..8192.
- n: number of bytes to be read.
Returns Nothing.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example dim
buffer as byte[16]
...
SPI_Ethernet_24j600_getBytes(buffer, 0x100, 16) ‘ read 16 bytes, starting
from address 0x100
Notes None.
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_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 :
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
Returns - 0 - there should not be a reply to the request.
- Length of TCP reply data field - otherwise.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example This function is internally called by the library and should not be called by the user’s code.
Notes 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_24j600_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 by the library. The user accesses to the UDP request
by using some of the SPI_Ethernet_24j600_get routines. The user puts data in the transmit buffer by
using some of the SPI_Ethernet_24j600_put routines. The function must return the length in bytes of
the UDP reply, or 0 if nothing to transmit. If you don’t need to reply to the UDP requests, just define this
function with a return(0) as single statement.
Parameters - remoteHost: client’s IP address.
- remotePort: client’s port.
- localPort: port to which the request is sent.
- reqLength: UDP request data field length.
- flags: structure consisted of two bit fields :
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
Returns - 0 - there should not be a reply to the request.
- Length of UDP reply data field - otherwise.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example This function is internally called by the library and should not be called by the user’s code.
Notes The function source code is provided with appropriate example projects. The code should be adjusted
by the user to achieve desired reply.
MikroElektronika
449
mikoBasic PRO for PIC32
SPI_Ethernet_24j600_setUserHandlers
Prototype sub procedure SPI_Ethernet_24j600_setUserHandlers(dim TCPHandler as ^TSPI_
Ethernet_24j600_UserTCP, dim UDPHandler as ^TSPI_Ethernet_24j600_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 request handler.
Returns Nothing.
Requires SPI_Ethernet_24j600_UserTCP and SPI_Ethernet_24j600_UserUDP have to be previously defined.
Example SPI_Ethernet_24j600_setUserHandlers(@SPI_Ethernet_24j600_UserTCP, @SPI_
Ethernet_24j600_UserUDP)
Notes 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_getIpAddress
Prototype sub function SPI_Ethernet_24j600_getIpAddress() as word
Description This routine should be used when DHCP server is present on the network to fetch assigned IP
address.
Parameters None.
Returns Pointer to the global variable holding IP address.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example dim
ipAddr as byte[4] ‘ user IP address buffer
...
memcpy(ipAddr, SPI_Ethernet_24j600_getIpAddress(), 4) ‘ fetch IP address
Notes 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_Ethernet_24j600_getGwIpAddress
Prototype sub function SPI_Ethernet_24j600_getGwIpAddress() as word
Description This routine should be used when DHCP server is present on the network to fetch assigned gateway
IP address.
Parameters None.
Returns Pointer to the global variable holding gateway IP address.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example dim
gwIpAddr as byte[4] ‘ user gateway IP address buffer
...
memcpy(gwIpAddr, SPI_Ethernet_24j600_getGwIpAddress(), 4) ‘ fetch gateway
IP address
Notes 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_getDnsIpAddress
Prototype sub function SPI_Ethernet_24j600_getDnsIpAddress() as word
Description This routine should be used when DHCP server is present on the network to fetch assigned DNS IP
address.
Parameters None.
Returns Pointer to the global variable holding DNS IP address.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example dim
dnsIpAddr as byte[4] ‘ user DNS IP address buffer
...
memcpy(dnsIpAddr, SPI_Ethernet_24j600_getDnsIpAddress(), 4) ‘ fetch DNS
server address
Notes 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
451
mikoBasic PRO for PIC32
SPI_Ethernet_24j600_getIpMask
Prototype sub function SPI_Ethernet_24j600_getIpMask() as word
Description This routine should be used when DHCP server is present on the network to fetch assigned DNS IP address.
Parameters None.
Returns Pointer to the global variable holding IP subnet mask.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
SPI_Ethernet_24j600_confNetwork
Prototype sub procedure SPI_Ethernet_24j600_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.
- gwIpAddr gateway IP address.
- dnsIpAddr: DNS IP address.
Returns Nothing.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example dim
ipMask as byte[4] ‘ network mask (for example : 255.255.255.0)
gwIpAddr as byte[4] ‘ gateway (router) IP address
dnsIpAddr as byte[4] ‘ DNS server IP address
...
gwIpAddr[0] = 192
gwIpAddr[1] = 168
gwIpAddr[2] = 20
gwIpAddr[3] = 6
dnsIpAddr[0] = 192
dnsIpAddr[1] = 168
dnsIpAddr[2] = 20
dnsIpAddr[3] = 100
ipMask[0] = 255
ipMask[1] = 255
ipMask[2] = 255
ipMask[3] = 0
...
SPI_Ethernet_24j600_confNetwork(ipMask, gwIpAddr, dnsIpAddr) ‘ set network
configuration parameters
Notes 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
452
mikroBasic PRO for PIC32
SPI_Ethernet_24j600_arpResolve
Prototype sub function SPI_Ethernet_24j600_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.
Returns - MAC address behind the IP address - the requested IP address was resolved.
- 0 - otherwise.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example dim
IpAddr as byte[4] ‘ IP address
...
IpAddr[0] = 192
IpAddr[0] = 168
IpAddr[0] = 1
IpAddr[0] = 1
...
SPI_Ethernet_24j600_arpResolve(IpAddr, 5) ‘ get MAC address behind the
above IP address, wait 5 secs for the response
Notes The Ethernet services are not stopped while this routine waits for ARP reply. The incoming packets will
be processed normaly during this time.
SPI_Ethernet_24j600_sendUDP
Prototype sub function SPI_Ethernet_24j600_sendUDP(dim byref destIP as byte[4], dim
sourcePort, destPort as word, dim pkt as ^byte, dim pktLen as word) as
byte
Description This is UDP module routine. It sends an UDP packet on the network.
Parameters - destIP: 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.
Returns - 1 - UDP packet was sent successfully.
- 0 - otherwise.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example dim
IpAddr as byte[4] ‘ remote IP address
...
IpAddr[0] = 192
IpAddr[0] = 168
IpAddr[0] = 1
IpAddr[0] = 1
...
SPI_Ethernet_24j600_sendUDP(IpAddr, 10001, 10001, “Hello”, 5) ‘ send Hello
message to the above IP address, from UDP port 10001 to UDP port 10001
Notes None.
MikroElektronika
453
mikoBasic PRO for PIC32
SPI_Ethernet_24j600_dnsResolve
Prototype sub function SPI_Ethernet_24j600_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.
Returns - pointer to the location holding the IP address - the requested host name was resolved.
- 0 - otherwise.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example 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_24j600_dnsResolve(“swisstime.ethz.
ch”, 5), 4)
Notes 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_24j600_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.
UDP port 68 is used as DHCP client port and UDP port 67 is used as DHCP server port.
Parameters - tmax: time in seconds to wait for an reply.
Returns - 1 - network parameters were obtained successfully.
- 0 - otherwise.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example ...
SPI_Ethernet_24j600_initDHCP(5) ‘ get network configuration from DHCP
server, wait 5 sec for the response
...
Notes The Ethernet services are not stopped while this routine waits for DNS reply. The incoming packets will
be processed normaly during this time.
MikroElektronika
455
mikoBasic PRO for PIC32
SPI_Ethernet_24j600_doDHCPLeaseTime
Prototype sub function SPI_Ethernet_24j600_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.
Parameters None.
Returns - 0 - lease time has not expired yet.
- 1 - lease time has expired, it’s time to renew it.
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example while true
...
if(SPI_Ethernet_24j600_doDHCPLeaseTime() <> 0) then
... ‘ it’s time to renew the IP address lease
end if
wend
Notes None.
SPI_Ethernet_24j600_renewDHCP
Prototype sub function SPI_Ethernet_24j600_renewDHCP(dim tmax as byte) as byte
Description This is DHCP module routine. It sends IP address lease time renewal request to DHCP server.
Parameters - tmax: time in seconds to wait for an reply.
Returns - 1 - upon success (lease time was renewed).
- 0 - otherwise (renewal request timed out).
Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
Example while true
...
if(SPI_Ethernet_24j600_doDHCPLeaseTime() <> 0) then
SPI_Ethernet_24j600_renewDHCP(5) ‘ it’s time to renew the IP address
lease, with 5 secs for a reply
end if
...
wend
Notes None.
MikroElektronika
456
mikroBasic PRO for PIC32
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.
External dependencies are the same as Port Expander Library external dependencies.
Library Routines
Basic routines:
- SPI_Glcd_Init
- SPI_Glcd_Set_Side
- SPI_Glcd_Set_Page
- SPI_Glcd_Set_X
- SPI_Glcd_Read_Data
- SPI_Glcd_Write_Data
Advanced routines:
- SPI_Glcd_Fill
- SPI_Glcd_Dot
- SPI_Glcd_Line
- SPI_Glcd_V_Line
- SPI_Glcd_H_Line
MikroElektronika
457
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_PartialImage
SPI_Glcd_Init
Prototype sub procedure SPI_Glcd_Init()
Description Initializes the Glcd module via SPI interface.
Parameters - DeviceAddress: SPI expander hardware address, see schematic at the bottom of this page
Returns Nothing.
Requires Global variables:
The SPI module needs to be initialized. See SPIx_Init and SPIx_Init_Advanced routines.
Example ‘ Port Expander module connections
dim SPExpanderRST as sbit at LATF0_bit
SPExpanderCS as sbit at LATF1_bit
SPExpanderRST_Direction as sbit at TRISF0_bit
SPExpanderCS_Direction as sbit at TRISF1_bit
‘ End Port Expander module connections
...
‘ If Port Expander Library uses SPI1 module :
SPI1_Init() ‘ Initialize SPI module used with PortExpander
SPI_Glcd_Init(0)
Notes None.
MikroElektronika
458
mikroBasic PRO for PIC32
SPI_Glcd_Set_Side
Prototype sub procedure SPI_Glcd_Set_Side(dim x_pos as byte)
Description 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.
Returns Nothing.
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
Example The following two lines are equivalent, and both of them select the left side of Glcd:
SPI_Glcd_Set_Side(0);
SPI_Glcd_Set_Side(10);
Notes For side, x axis and page layout explanation see schematic at the bottom of this page.
SPI_Glcd_Set_Page
Prototype sub procedure SPI_Glcd_Set_Page(dim page as byte)
Description Selects page of Glcd.
Returns - page: page number. Valid values: 0..7
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
Example SPI_Glcd_Set_Page(5);
Notes For side, x axis and page layout explanation see schematic at the bottom of this page.
SPI_Glcd_Set_X
Prototype sub procedure SPI_Glcd_Set_X(dim x_pos as byte)
Description Sets x-axis position to x_pos dots from the left border of Glcd within the selected side.
Parameters - x_pos: position on x-axis. Valid values: 0..63
Returns Nothing.
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
Example SPI_Glcd_Set_X(25);
Notes For side, x axis and page layout explanation see schematic at the bottom of this page.
MikroElektronika
459
mikoBasic PRO for PIC32
SPI_Glcd_Read_Data
Prototype sub function SPI_Glcd_Read_Data() as byte
Description Reads data from the current location of Glcd memory and moves to the next location.
Returns 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.
Example dim data_ as byte
...
data_ = SPI_Glcd_Read_Data()
Notes None.
SPI_Glcd_Write_Data
Prototype sub procedure SPI_Glcd_Write_Data(dim data_ as byte)
Description Writes one byte to the current location in Glcd memory and moves to the next location.
Parameters - data_: data to be written
Returns Nothing.
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.
Example dim data_ as byte
...
SPI_Glcd_Write_Data(data_)
Notes None.
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_Glcd_Fill(0).
To fill the screen completely, use SPI_Glcd_Fill(0xFF).
Parameters - pattern: byte to fill Glcd memory with
Returns Nothing.
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
Example ‘ Clear screen
SPI_Glcd_Fill(0)
Notes None.
SPI_Glcd_Dot
Prototype sub procedure SPI_Glcd_Dot(dim x_pos, y_pos, color as byte)
The parameter color determines the dot state: 0 clears dot, 1 puts a dot, and 2 inverts dot state.
Returns Nothing.
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
Example ‘ Invert the dot in the upper left corner
SPI_Glcd_Dot(0, 0, 2)
Notes For x and y axis layout explanation see schematic at the bottom of this page.
MikroElektronika
461
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.
Returns Nothing.
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
Example ‘ Draw a line between dots (0,0) and (20,30)
SPI_Glcd_Line(0, 0, 20, 30, 1)
Notes None.
SPI_Glcd_V_Line
Prototype sub procedure SPI_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
Parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot.
Returns Nothing.
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
Example ‘ Draw a vertical line between dots (10,5) and (10,25)
SPI_Glcd_V_Line(5, 25, 10, 1)
Notes None.
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)
Description Draws a horizontal line on Glcd.
Parameters - x_start: x coordinate of the line start. Valid values: 0..127
- x_end: x coordinate of the line end. Valid values: 0..127
- y_pos: y coordinate of horizontal line. Valid values: 0..63
- color: color parameter. Valid values: 0..2
The parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot.
Returns Nothing.
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
Example ‘ Draw a horizontal line between dots (10,20) and (50,20)
SPI_Glcd_H_Line(10, 50, 20, 1)
Notes None.
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)
Description 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: 0 white, 1 black, and 2 inverts
each dot.
Returns Nothing.
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
Example ‘ Draw a rectangle between dots (5,5) and (40,40)
SPI_Glcd_Rectangle(5, 5, 40, 40, 1)
Notes None.
MikroElektronika
463
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)
Description 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.
Returns Nothing.
Requires Glcd needs to be initialized, see SPI_Glcd_Init routine.
Example ‘ Draw a rounded edge rectangle between dots (5,5) and (40,40) with the
radius of 12
SPI_Glcd_Rectangle_Round_Edges(5, 5, 40, 40, 12, 1)
Notes None.
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)
Description 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.
Returns Nothing.
Requires Glcd needs to be initialized, see SPI_Glcd_Init routine.
Example ‘ Draws a filled rounded edge rectangle between dots (5,5) and (40,40) with
the radius of 12
SPI_Glcd_Rectangle_Round_Edges_Fill(5, 5, 40, 40, 12, 1)
Notes None.
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)
Description 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.
Returns Nothing.
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
Example ‘ Draw a box between dots (5,15) and (20,40)
SPI_Glcd_Box(5, 15, 20, 40, 1)
Notes None.
SPI_Glcd_Circle
Prototype sub procedure SPI_Glcd_Circle(dim x_center, y_center, radius as integer,
dim color as byte)
Description Draws a circle on Glcd.
Parameters - x_center: x coordinate of the circle center. Valid values: 0..127
- y_center: y coordinate of the circle center. Valid values: 0..63
- radius: radius size
- color: color parameter. Valid values: 0..2
The parameter color determines the color of the circle line: 0 white, 1 black, and 2 inverts each dot.
Returns Nothing.
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
Example ‘ Draw a circle with center in (50,50) and radius=10
SPI_Glcd_Circle(50, 50, 10, 1)
Notes None.
MikroElektronika
465
mikoBasic PRO for PIC32
SPI_Glcd_Circle_FIll
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)
Description 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.
Returns Nothing.
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
Example ‘ Draw a circle with center in (50,50) and radius=10
SPI_Glcd_Circle_Fill(50, 50, 10, 1)
Notes None.
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)
Description Sets font that will be used with SPI_Glcd_Write_Char and SPI_Glcd_Write_Text routines.
Parameters None.
Returns - activeFont: font to be set. Needs to be formatted as an array of char
- aFontWidth: width of the font characters in dots.
- aFontHeight: height of the font characters in dots.
- aFontOffs: number that represents difference between the 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.
- Font_Glcd_System3x5
- Font_Glcd_System5x7
- Font_Glcd_5x7
- Font_Glcd_Character8x7
For the sake of the backward compatibility, these fonts are supported also:
MikroElektronika
467
mikoBasic PRO for PIC32
SPI_Glcd_Write_Char
Prototype sub procedure SPI_Glcd_Write_Char(dim chr1, x_pos, page_num, color as
byte)
Description 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.
Returns Nothing.
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.
Example ‘ Write character ‘C’ on the position 10 inside the page 2:
SPI_Glcd_Write_Char(“C”, 10, 2, 1)
Notes For x axis and page layout explanation see schematic at the bottom of this page.
SPI_Glcd_Write_Text
Prototype sub procedure SPI_Glcd_Write_Text(dim byref text as char[40], dim x_pos,
page_num, color as byte)
Description Prints text on Glcd.
Parameters - text: text to be written
- x_pos: text starting position on x-axis.
- page_num: the number of the page on which text will be written. Valid values: 0..7
- color: color parameter. Valid values: 0..2
The parameter color determines the color of the text: 0 white, 1 black, and 2 inverts each dot.
Returns Nothing.
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.
Example ‘ Write text “Hello world!” on the position 10 inside the page 2:
SPI_Glcd_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(dim byref const image as byte)
Description Displays bitmap on Glcd.
Parameters - image: image to be displayed. Bitmap array can be located in both code and RAM memory (due to
the mikroBasic PRO for PIC32 pointer to const and pointer to RAM equivalency).
Returns Nothing.
Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
Example SPI_Glcd_Image(@my_image)
Notes 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.
SPI_Glcd_PartialImage
Prototype sub procedure SPI_T6963C_PartialImage(dim x_left, y_top, width, height,
picture_width, picture_height as word, const image as ^byte)
Notes 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.
MikroElektronika
469
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.
program SPI_Glcd
main:
CHECON = 0x32
AD1PCFG = 0xFFFF ‘ Configure AN pins as digital
while TRUE
SPI_Glcd_Image(@truck_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_PartialImage(24,16,68,30,128,64,@truck_bmp)
Delay_ms(500)
SPI_Glcd_PartialImage(56,34,68,30,128,64,@truck_bmp)
Delay2s() Delay2s()
SPI_Glcd_Fill(0x00) ‘ Clear GLCD
MikroElektronika
470
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
Delay2S()
MikroElektronika
471
mikoBasic PRO for PIC32
HW Connection
MikroElektronika
472
mikroBasic PRO for PIC32
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 mikroElektronika’s Serial Lcd Adapter Board pinout, see schematic at the
bottom of this page for details.
External dependencies are the same as Port Expander Library external dependencies.
Library Routines
- SPI_Lcd_Config
- SPI_Lcd_Out
- SPI_Lcd_Out_Cp
- SPI_Lcd_Chr
- SPI_Lcd_Chr_Cp
- SPI_Lcd_Cmd
MikroElektronika
473
mikoBasic PRO for PIC32
SPI_Lcd_Config
Prototype sub procedure SPI_Lcd_Config(dim DeviceAddress as byte)
Description Initializes the Lcd module via SPI interface.
Parameters - DeviceAddress: SPI expander hardware address, see schematic at the bottom of this page
Returns Nothing.
Requires Global variables:
The SPI module needs to be initialized. See SPIx_Init and SPIx_Init_Advanced routines.
Example ‘ Port Expander module connections
dim SPExpanderRST as sbit at LATF0_bit
SPExpanderCS as sbit at LATF1_bit
SPExpanderRST_Direction as sbit at TRISF0_bit
SPExpanderCS_Direction as sbit at TRISF1_bit
‘ End Port Expander module connections
...
‘ If Port Expander Library uses SPI1 module
SPI1_Init() ‘ Initialize SPI module used with PortExpander
SPI_Lcd_Config(0) ‘ initialize lcd over spi interface
Notes None.
SPI_Lcd_Out
Prototype sub procedure SPI_Lcd_Out(dim row, column as byte, dim byref text as
string)
Description Prints text on the Lcd starting from specified position. Both string variables and literals can be passed
as a text.
Parameters - row: starting position row number
- column: starting position column number
- text: text to be written
Returns Nothing.
Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd_Config routine.
Example ‘ Write text “Hello!” on Lcd starting from row 1, column 3:
SPI_Lcd_Out(1, 3, “Hello!”)
Notes None.
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)
Description Prints text on the Lcd starting from specified position. Both string variables and literals can be passed
as a text.
Parameters - text: text to be written
Returns Nothing.
Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd_Config routine.
Example ‘ Write text “Here!” at current cursor position:
SPI_Lcd_Out_CP(“Here!”)
Notes 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
Returns Nothing.
Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd_Config routine.
Example // Write character “i” at row 2, column 3:
SPI_Lcd_Chr(2, 3, ‘i’);
Notes None.
SPI_Lcd_Chr_Cp
Prototype sub procedure SPI_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
character.
Parameters - Out_Char: character to be written
Returns Nothing.
Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd_Config routine.
Example ‘ Write character “e” at current cursor position:
SPI_Lcd_Chr_Cp(“e”)
Notes None.
MikroElektronika
475
mikoBasic PRO for PIC32
SPI_Lcd_Cmd
Prototype sub procedure SPI_Lcd_Cmd(dim out_char as byte)
Description Sends command to Lcd.
Parameters - out_char: command to be sent
Returns Nothing.
Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd_Config routine.
Example ‘ Clear Lcd display:
SPI_Lcd_Cmd(_LCD_CLEAR)
Notes Predefined constants can be passed to the routine, see Available SPI Lcd Commands.
MikroElektronika
476
mikroBasic PRO for PIC32
Library Example
Use SPI_Lcd_Init for default pin settings (see the first figure below).
MikroElektronika
477
mikoBasic PRO for PIC32
MikroElektronika
478
mikroBasic PRO for PIC32
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 Lcd8 Library.
- For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by using the SPI_Set_
Active() routine. See the SPI Library functions.
- This Library is designed to work with the mikroElektronika’s Serial Lcd/Glcd Adapter Board pinout, see schematic at
the bottom of this page for details.
External dependencies are the same as Port Expander Library external dependencies.
Library Routines
- SPI_Lcd8_Config
- SPI_Lcd8_Out
- SPI_Lcd8_Out_Cp
- SPI_Lcd8_Chr
- SPI_Lcd8_Chr_Cp
- SPI_Lcd8_Cmd
MikroElektronika
479
mikoBasic PRO for PIC32
SPI_Lcd8_Config
Prototype sub procedure SPI_Lcd8_Config(dim DeviceAddress as byte)
Description Initializes the Lcd module via SPI interface.
Parameters - DeviceAddress: SPI expander hardware address, see schematic at the bottom of this page
Returns Nothing.
Requires Global variables:
The SPI module needs to be initialized. See SPIx_Init and SPIx_Init_Advanced routines.
Example ‘ Port Expander module connections
dim SPExpanderRST as sbit at LATF0_bit
SPExpanderCS as sbit at LATF1_bit
SPExpanderRST_Direction as sbit at TRISF0_bit
SPExpanderCS_Direction as sbit at TRISF1_bit
‘ End Port Expander module connections
...
SPI1_Init() ‘ Initialize SPI interface
SPI_Lcd8_Config(0) ‘ Intialize Lcd in 8bit mode via spi
Notes None.
SPI_Lcd8_Out
Prototype sub procedure SPI_Lcd8_Out(dim row, column as byte, dim byref text as
string)
Description Prints text on Lcd starting from specified position. Both string variables and literals can be passed as
a text.
Parameters - row: starting position row number
- column: starting position column number
- text: text to be written
Returns Nothing.
Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd8_Config routine.
Example ‘ Write text “Hello!” on Lcd starting from row 1, column 3:
SPI_Lcd8_Out(1, 3, “Hello!”)
Notes None.
MikroElektronika
480
mikroBasic PRO for PIC32
SPI_Lcd8_Out_Cp
Prototype sub procedure SPI_Lcd8_Out_CP(dim byref text as string)
Description Prints text on Lcd at current cursor position. Both string variables and literals can be passed as a
text.
Parameters - text: text to be written
Returns Nothing.
Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd8_Config routine.
Example ‘ Write text “Here!” at current cursor position:
SPI_Lcd8_Out_Cp(“Here!”)
Notes None.
SPI_Lcd8_Chr
Prototype sub procedure SPI_Lcd8_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
Returns Nothing.
Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd8_Config routine.
Notes None.
SPI_Lcd8_Chr_Cp
Prototype sub procedure SPI_Lcd8_Chr_CP(dim out_char as byte)
Description Prints character on Lcd at current cursor position. Both variables and literals can be passed as
character.
Parameters - out_char: character to be written
Returns Nothing.
Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd8_Config routine.
Example Print “e” at current cursor position:
Notes None.
MikroElektronika
481
mikoBasic PRO for PIC32
SPI_Lcd8_Cmd
Prototype sub procedure SPI_Lcd8_Cmd(dim out_char as byte)
Description Sends command to Lcd.
Parameters - out_char: command to be sent
Returns Nothing.
Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd8_Config routine.
Example ‘ Clear Lcd display:
SPI_Lcd8_Cmd(_LCD_CLEAR)
Notes Predefined constants can be passed to the routine, see Available SPI Lcd8 Commands.
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.
program Spi_Lcd8
main:
CHECON = 0x32
AD1PCFG = 0xFFFF ‘ Configure AN pins as digital
text = “mikroElektronika”
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
MikroElektronika
483
mikoBasic PRO for PIC32
MikroElektronika
484
mikroBasic PRO for PIC32
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:
External dependencies are the same as Port Expander Library external dependencies.
MikroElektronika
485
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_PartialImage
- 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 byte, dim wr, rd, cd, rst as byte)
+---------------------+ /\
+ GRAPHICS PANEL #0 + |
+ + |
+ + |
+ + |
+---------------------+ | PANEL 0
+ TEXT PANEL #0 + |
+ + \/
+---------------------+ /\
+ GRAPHICS PANEL #1 + |
+ + |
+ + |
+ + |
+---------------------+ | PANEL 1
+ TEXT PANEL #1 + |
+ + |
+---------------------+ \/
The SPI module needs to be initialized. See the SPIx_Init and SPIx_Init_Advanced routines.
MikroElektronika
487
mikoBasic PRO for PIC32
Notes None.
SPI_T6963C_writeData
Prototype sub procedure SPI_T6963C_writeData(dim data_ as byte)
Description Writes data to T6963C controller via SPI interface.
Parameters - data_: data to be written
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example SPI_T6963C_writeData(data_)
Notes None.
SPI_T6963C_writeCommand
Prototype sub procedure SPI_T6963C_writeCommand(dim data_ as byte)
Description Writes command to T6963C controller via SPI interface.
Parameters - data_: command to be written
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example SPI_T6963C_writeCommand(SPI_T6963C_CURSOR_POINTER_SET)
Notes None.
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
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example SPI_T6963C_setPtr(SPI_T6963C_grHomeAddr + start, SPI_T6963C_ADDRESS_
POINTER_SET)
Notes None.
SPI_T6963C_waitReady
Prototype sub procedure SPI_T6963C_waitReady()
Description Pools the status byte, and loops until Toshiba Glcd module is ready.
Parameters None.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example SPI_T6963C_waitReady()
Notes None.
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
- len: length of the memory block in bytes
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example SPI_T6963C_fill(0x33,0x00FF,0x000F)
Notes None.
MikroElektronika
489
mikoBasic PRO for PIC32
SPI_T6963C_dot
Prototype sub procedure SPI_T6963C_dot(dim x, y as integer, dim color as byte)
Description Draws a dot in the current graphic panel of Glcd at coordinates (x, y).
SPI_T6963C_write_char
Prototype sub procedure SPI_T6963C_write_char(dim c, x, y, mode as byte)
Description 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:
SPI_T6963C_ROM_MODE_OR,
SPI_T6963C_ROM_MODE_XOR,
SPI_T6963C_ROM_MODE_AND and
SPI_T6963C_ROM_MODE_TEXT
- OR Mode: In the OR-Mode, text and graphics can be displayed and the data is logically “OR-ed”. This
is the most common way of combining text and graphics for example labels on buttons.
- XOR-Mode: In this mode, the text and graphics data are combined via the logical “exclusive OR”.
This can be useful to display text in negative mode, i.e. white text on black background.
- AND-Mode: The text and graphic data shown on display are combined via the logical “AND
function”.
- TEXT-Mode: This option is only available when displaying just a text. The Text Attribute values are
stored in the graphic area of display memory.
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)
Description Writes text in the current text panel of Glcd at coordinates (x, y).
Parameters - str: text to be written
- x: text position on x-axis
- 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
- 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.
MikroElektronika
491
mikoBasic PRO for PIC32
SPI_T6963C_line
Prototype sub procedure SPI_T6963C_line(dim x0, y0, x1, y1 as integer, dim pcolor as
byte)
Description Draws a line from (x0, y0) to (x1, y1).
Parameters - x0: x coordinate of the line start
- y0: y coordinate of the line end
- x1: x coordinate of the line start
- y1: y coordinate of the line end
- pcolor: color parameter. Valid values: SPI_T6963C_BLACK and SPI_T6963C_WHITE
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example SPI_T6963C_line(0, 0, 239, 127, SPI_T6963C_WHITE)
Notes None.
SPI_T6963C_rectangle
Prototype sub procedure SPI_T6963C_rectangle(dim x0, y0, x1, y1 as integer, 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: SPI_T6963C_BLACK and SPI_T6963C_WHITE
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example SPI_T6963C_rectangle(20, 20, 219, 107, SPI_T6963C_WHITE)
Notes None.
MikroElektronika
492
mikroBasic PRO for PIC32
SPI_T6963C_rectangle_round_edges
Prototype sub procedure SPI_T6963C_rectangle_round_edges(dim x0 as integer, dim y0 as
integer, dim x1 as integer, dim y1 as integer, dim radius as integer, dim
pcolor as byte)
Description 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
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example SPI_T6963C_rectangle_round_edges(20, 20, 219, 107, 12, SPI_T6963C_WHITE)
Notes None.
SPI_T6963C_rectangle_round_edges_fill
Prototype sub procedure SPI_T6963C_rectangle_round_edges_fill(dim x0 as integer, dim
y0 as integer, dim x1 as integer, dim y1 as integer, dim radius as integer,
dim pcolor as byte)
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example SPI_T6963C_rectangle_round_edges_fill(20, 20, 219, 107, 12, SPI_T6963C_
WHITE)
Notes None.
MikroElektronika
493
mikoBasic PRO for PIC32
SPI_T6963C_box
Prototype sub procedure SPI_T6963C_box(dim x0, y0, x1, y1 as integer, dim pcolor as
byte)
Description 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
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example SPI_T6963C_box(0, 119, 239, 127, SPI_T6963C_WHITE)
Notes None.
SPI_T6963C_circle
Prototype sub procedure SPI_T6963C_circle(dim x, y as integer, dim r as longint, dim
pcolor as word)
Description 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
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example SPI_T6963C_circle(120, 64, 110, SPI_T6963C_WHITE)
Notes None.
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)
Description Draws a filled circle on the Glcd.
Parameters Parameters:
Notes None.
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).
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example SPI_T6963C_image(my_image)
Notes 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_PartialImage
Prototype sub procedure SPI_T6963C_PartialImage(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).
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example ‘ Draws a 10x15 part of the image starting from the upper left corner on the
coordinate (10,12). Original image size is 16x32.
SPI_T6963C_PartialImage(10, 12, 10, 15, 16, 32, @image)
Use the integrated Glcd Bitmap Editor (menu option Tools › Glcd Bitmap Editor) to convert image to
a constant array suitable for displaying on Glcd.
MikroElektronika
495
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)
Description 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
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example SPI_T6963C_sprite(76, 4, einstein, 88, 119) ‘ draw a sprite
Notes 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
Prototype sub procedure SPI_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
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example SPI_T6963c_set_cursor(cposx, cposy)
Notes None.
SPI_T6963C_clearBit
Prototype sub procedure SPI_T6963C_clearBit(dim b as byte)
Description Clears control port bit(s).
Parameters - b: bit mask. The function will clear bit x on control port if bit x in bit mask is set to 1.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example ‘ clear bits 0 and 1 on control port
SPI_T6963C_clearBit(0x0003)
Notes None.
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.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example ‘ set bits 0 and 1 on control port
SPI_T6963C_setBit(0x0003)
Notes None.
SPI_T6963C_negBit
Prototype sub procedure SPI_T6963C_negBit(dim b as byte)
Description Negates control port bit(s).
Parameters - b: bit mask. The function will negate bit x on control port if bit x in bit mask is set to 1.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example ‘ 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 word)
MikroElektronika
497
mikoBasic PRO for PIC32
SPI_T6963C_displayTxtPanel
Prototype sub procedure SPI_T6963C_displayTxtPanel(dim n as word)
Description Display selected text panel.
Parameters - n: text panel number. Valid values: 0 and 1.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example ‘ display text panel 1
SPI_T6963C_displayTxtPanel(1)
Notes None.
SPI_T6963C_setGrPanel
Prototype sub procedure SPI_T6963C_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.
Parameters - n: graphic panel number. Valid values: 0 and 1.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example ‘ set graphic panel 1 as current graphic panel.
SPI_T6963C_setGrPanel(1)
Notes None.
SPI_T6963C_setTxtPanel
Prototype sub procedure SPI_T6963C_setTxtPanel(dim n as word)
Description Compute start address for selected text panel and set appropriate internal pointers. All subsequent
text operations will be preformed at this text panel.
Parameters - n: text panel number. Valid values: 0 and 1.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example ‘ set text panel 1 as current text panel.
SPI_T6963C_setTxtPanel(1)
Notes None.
MikroElektronika
498
mikroBasic PRO for PIC32
SPI_T6963C_panelFill
Prototype sub procedure SPI_T6963C_panelFill(dim v as word)
Description Fill current panel in full (graphic+text) with appropriate value (0 to clear).
Parameters - v: value to fill panel with.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example ‘ clear current panel
SPI_T6963C_panelFill(0)
Notes None.
SPI_T6963C_grFill
Prototype sub procedure SPI_T6963C_grFill(dim v as word)
Description Fill current graphic panel with appropriate value (0 to clear).
Parameters - v: value to fill graphic panel with.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example ‘ clear current graphic panel
SPI_T6963C_grFill(0)
Notes None.
SPI_T6963C_txtFill
Prototype sub procedure SPI_T6963C_txtFill(dim v as word)
Description Fill current text panel with appropriate value (0 to clear).
Parameters - v: this value increased by 32 will be used to fill text panel.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example ‘ clear current text panel
SPI_T6963C_txtFill(0)
Notes None.
MikroElektronika
499
mikoBasic PRO for PIC32
SPI_T6963C_cursor_height
Prototype sub procedure SPI_T6963C_cursor_height(dim n as byte)
Description Set cursor size.
Parameters - n: cursor height. Valid values: 0..7.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example SPI_T6963C_cursor_height(7)
Notes None.
SPI_T6963C_graphics
Prototype sub procedure SPI_T6963C_graphics(dim n as word)
Description Enable/disable graphic displaying.
Parameters - n: graphic enable/disable parameter. Valid values: 0 (disable graphic dispaying) and 1 (enable
graphic displaying).
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example ‘ enable graphic displaying
SPI_T6963C_graphics(1)
Notes None.
SPI_T6963C_text
Prototype sub procedure SPI_T6963C_text(dim n as word)
Description Enable/disable text displaying.
Parameters - n: text enable/disable parameter. Valid values: 0 (disable text dispaying) and 1 (enable text
displaying).
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example ‘ enable text displaying
SPI_T6963C_text(1)
Notes None.
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).
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example ‘ set cursor on
SPI_T6963C_cursor(1)
Notes None.
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).
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
Example ‘ enable cursor blinking
SPI_T6963C_cursor_blink(1)
Notes None.
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.
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 as sbit at TRISD8_bit
SPExpanderCS_Direction as sbit at TRISD9_bit
‘ End Port Expander module connections
MikroElektronika
501
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
CHECON = 0x32
AD1PCFG = 0xFFFF ‘ initialize AN pins as digital
panel = 0
i = 0
curs = 0
cposx = 0
cposy = 0
‘ * init display for 240 pixel width and 128 pixel height
‘ * 8 bits character width
‘ * data bus on MCP23S17 portB
‘ * control bus on MCP23S17 portA
‘ * bit 2 is !WR
‘ * bit 1 is !RD
‘ * bit 0 is !CD
‘ * bit 4 is RST
‘ * chip enable, reverse on, 8x8 font internaly set in library
MikroElektronika
502
mikroBasic PRO for PIC32
SPI_T6963C_graphics(1)
SPI_T6963C_text(1)
‘ * Text messages
SPI_T6963C_write_text(txt, 0, 0, SPI_T6963C_ROM_MODE_XOR)
SPI_T6963C_write_text(txt1, 0, 15, SPI_T6963C_ROM_MODE_XOR)
‘*
‘* Cursor
‘*
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
‘*
‘* Draw solid boxes
‘*
SPI_T6963C_box(0, 0, 239, 8, SPI_T6963C_WHITE)
SPI_T6963C_box(0, 119, 239, 127, SPI_T6963C_WHITE)
‘ *
‘ * Draw rectangles
‘ *
#IFDEF LINE_DEMO
SPI_T6963C_rectangle(0, 0, 239, 127, SPI_T6963C_WHITE)
SPI_T6963C_rectangle(20, 20, 219, 107, SPI_T6963C_WHITE)
SPI_T6963C_rectangle(40, 40, 199, 87, SPI_T6963C_WHITE)
SPI_T6963C_rectangle(60, 60, 179, 67, SPI_T6963C_WHITE)
#ENDIF
‘ *
‘ * Draw rounded edge rectangle
‘ *
#IFDEF LINE_DEMO
SPI_T6963C_Rectangle_Round_Edges(10, 10, 229, 117, 12, SPI_T6963C_WHITE)
SPI_T6963C_Rectangle_Round_Edges(30, 30, 209, 97, 12, SPI_T6963C_WHITE)
SPI_T6963C_Rectangle_Round_Edges(50, 50, 189, 77, 12, SPI_T6963C_WHITE)
#ENDIF
‘ *
‘ * Draw filled rounded edge rectangle
‘ *
#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)
SPI_T6963C_Rectangle_Round_Edges_Fill(40, 40, 199, 87, 12, SPI_T6963C_BLACK)
SPI_T6963C_Rectangle_Round_Edges_Fill(50, 50, 189, 77, 12, SPI_T6963C_WHITE)
#ENDIF
‘ *
‘ * Draw a cross
‘ *
MikroElektronika
503
mikoBasic PRO for PIC32
#IFDEF LINE_DEMO
SPI_T6963C_line(0, 0, 239, 127, SPI_T6963C_WHITE)
SPI_T6963C_line(0, 127, 239, 0, SPI_T6963C_WHITE)
#ENDIF
‘ *
‘ * Draw circles
‘ *
#IFDEF LINE_DEMO
SPI_T6963C_circle(120, 64, 10, SPI_T6963C_WHITE)
SPI_T6963C_circle(120, 64, 30, SPI_T6963C_WHITE)
SPI_T6963C_circle(120, 64, 50, SPI_T6963C_WHITE)
SPI_T6963C_circle(120, 64, 70, SPI_T6963C_WHITE)
SPI_T6963C_circle(120, 64, 90, SPI_T6963C_WHITE)
SPI_T6963C_circle(120, 64, 110, SPI_T6963C_WHITE)
SPI_T6963C_circle(120, 64, 130, SPI_T6963C_WHITE)
#ENDIF
‘ *
‘ * Draw filled circles
‘ *
#IFDEF FILL_DEMO
SPI_T6963C_circle_fill(120, 64, 60, SPI_T6963C_WHITE)
SPI_T6963C_circle_fill(120, 64, 55, SPI_T6963C_BLACK)
SPI_T6963C_circle_fill(120, 64, 50, SPI_T6963C_WHITE)
SPI_T6963C_circle_fill(120, 64, 45, SPI_T6963C_BLACK)
SPI_T6963C_circle_fill(120, 64, 40, SPI_T6963C_WHITE)
SPI_T6963C_circle_fill(120, 64, 35, SPI_T6963C_BLACK)
SPI_T6963C_circle_fill(120, 64, 30, SPI_T6963C_WHITE)
SPI_T6963C_circle_fill(120, 64, 25, SPI_T6963C_BLACK)
SPI_T6963C_circle_fill(120, 64, 20, SPI_T6963C_WHITE)
SPI_T6963C_circle_fill(120, 64, 15, SPI_T6963C_BLACK)
SPI_T6963C_circle_fill(120, 64, 10, SPI_T6963C_WHITE)
SPI_T6963C_circle_fill(120, 64, 5, SPI_T6963C_BLACK)
#ENDIF
Delay_ms(1000)
SPI_T6963C_sprite(76, 4, @einstein_bmp, 88, 119) ‘ Draw a sprite
Delay_ms(1000)
SPI_T6963C_image(@mikroE_240x128_bmp)
SPI_T6963C_displayGrPanel(1)
Delay_ms(1000)
#IFDEF PARTIAL_IMAGE_DEMO
SPI_T6963C_grFill(0)
SPI_T6963C_PartialImage(0, 0, 64, 64, 240, 128, @mikroE_240x128_bmp) ‘ Display
partial image
Delay_ms(1000)
SPI_T6963C_graphics(0)
#ENDIF
SPI_T6963C_image(@mikroE_240x128_bmp)
SPI_T6963C_graphics(1)
SPI_T6963C_displayGrPanel(0)
MikroElektronika
504
mikroBasic PRO for PIC32
‘*
‘* If RB8 is pressed, toggle the display between graphic panel 0 and graphic 1
‘*
if( RB8_bit <> 0) then
Inc(panel)
panel = panel and 1
SPI_T6963C_setPtr((SPI_T6963C_grMemSize + SPI_T6963C_txtMemSize) * panel, SPI_
T6963C_GRAPHIC_HOME_ADDRESS_SET)
Delay_ms(300)
‘*
‘* If RB9 is pressed, display only graphic panel
‘*
else
if ( RB9_bit <> 0) then
SPI_T6963C_graphics(1)
SPI_T6963C_text(0)
Delay_ms(300)
‘*
‘* If RB10 is pressed, display only text panel
‘*
else
if ( RB10_bit <> 0) then
SPI_T6963C_graphics(0)
SPI_T6963C_text(1)
Delay_ms(300)
‘*
‘* If RB11 is pressed, display text and graphic panels
‘*
else
if ( RB11_bit <> 0) then
SPI_T6963C_graphics(1)
SPI_T6963C_text(1)
Delay_ms(300)
‘*
‘* If RB12 is pressed, change cursor
‘*
else
if( RB12_bit <> 0) then
Inc(curs)
if (curs = 3) then
curs = 0
end if
select case curs
case 0
‘ no cursor
SPI_T6963C_cursor(0)
MikroElektronika
505
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
‘*
‘* If RB13 is pressed, perform the “Partial image” demonstration
‘*
#IFDEF PARTIAL_IMAGE_DEMO
if( RB13_bit = 1) then
SPI_T6963C_setGrPanel(0)
SPI_T6963C_setTxtPanel(0)
SPI_T6963C_txtFill(0)
SPI_T6963C_setGrPanel(1)
SPI_T6963C_setTxtPanel(0)
SPI_T6963C_graphics(1)
SPI_T6963C_text(1)
SPI_T6963C_displayGrPanel(1)
SPI_T6963C_write_text(txt2, 5, 15, SPI_T6963C_ROM_MODE_XOR)
Delay_1sec()
SPI_T6963C_grFill(0)
SPI_T6963C_PartialImage(0, 0, 64, 64, 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(txt1, 0, 15, SPI_T6963C_ROM_MODE_XOR)
end if
#ENDIF
end if
end if
end if
end if
‘*
‘* 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_CHARACTER_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
MikroElektronika
507
mikoBasic PRO for PIC32
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 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:
MikroElektronika
508
mikroBasic PRO for PIC32
MikroElektronika
509
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_PartialImage
- 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
510
mikroBasic PRO for PIC32
T6963C_init
Prototype sub procedure T6963C_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.
+---------------------+ /\
+ GRAPHICS PANEL #0 + |
+ + |
+ + |
+ + |
+---------------------+ | PANEL 0
+ TEXT PANEL #0 + |
+ + \/
+---------------------+ /\
+ GRAPHICS PANEL #1 + |
+ + |
+ + |
+ + |
+---------------------+ | PANEL 1
+ TEXT PANEL #1 + |
+ + |
+---------------------+ \/
Parameters - width: width of the Glcd panel
- height: height of the Glcd panel
- fntW: font width
Returns Nothing.
Requires Global variables:
MikroElektronika
511
mikoBasic PRO for PIC32
...
‘ init display for 240 pixel width, 128 pixel height and 8 bits character
width
T6963C_init(240, 128, 8)
Notes None.
T6963C_writeData
Prototype sub procedure T6963C_writeData(dim mydata as byte)
Description Writes data to T6963C controller.
Parameters - mydata: data to be written
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_writeData(AddrL);
Notes None.
MikroElektronika
512
mikroBasic PRO for PIC32
T6963C_writeCommand
Prototype sub procedure T6963C_writeCommand(dim mydata as byte)
Description Writes command to T6963C controller.
Parameters - mydata: command to be written
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_writeCommand(T6963C_CURSOR_POINTER_SET)
Notes None.
T6963C_setPtr
Prototype sub procedure 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
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_setPtr(T6963C_grHomeAddr + start, T6963C_ADDRESS_POINTER_SET)
Notes None.
T6963C_waitReady
Prototype sub procedure T6963C_waitReady()
Description Pools the status byte, and loops until Toshiba Glcd module is ready.
Parameters None.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_waitReady()
Notes None.
MikroElektronika
513
mikoBasic PRO for PIC32
T6963C_fill
Prototype sub procedure 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
- len: length of the memory block in bytes
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_fill(0x33,0x00FF,0x000F)
Notes None.
T6963C_dot
Prototype sub procedure T6963C_dot(dim x, y as integer, dim color as byte)
Description Draws a dot in the current graphic panel of Glcd at coordinates (x, y).
Parameters - x: dot position on x-axis
- y: dot position on y-axis
- color: color parameter. Valid values: T6963C_BLACK and T6963C_WHITE
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_dot(x0, y0, pcolor)
Notes None.
MikroElektronika
514
mikroBasic PRO for PIC32
T6963C_write_char
Prototype sub procedure T6963C_write_char(dim c, x, y, mode as byte)
Description Writes a char in the current text panel of Glcd at coordinates (x, y).
Parameters - c: char to be written
- x: char position on x-axis
- y: char position on y-axis
- mode: mode parameter. Valid values: T6963C_ROM_MODE_OR, T6963C_ROM_MODE_XOR,
T6963C_ROM_MODE_AND and T6963C_ROM_MODE_TEXT
- OR Mode: In the OR-Mode, text and graphics can be displayed and the data is logically “OR-ed”. This
is the most common way of combining text and graphics for example labels on buttons.
- XOR-Mode: In this mode, the text and graphics data are combined via the logical “exclusive OR”.
This can be useful to display text in the negative mode, i.e. white text on black background.
- AND-Mode: The text and graphic data shown on display are combined via the logical “AND
function”.
- TEXT-Mode: This option is only available when displaying just a text. The Text Attribute values are
stored in the graphic area of display memory.
MikroElektronika
515
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)
Description Writes text in the current text panel of Glcd at coordinates (x, y).
Parameters - str: text to be written
- x: text position on x-axis
- y: text position on y-axis
- mode: mode parameter. Valid values: T6963C_ROM_MODE_OR, T6963C_ROM_MODE_XOR,
T6963C_ROM_MODE_AND and T6963C_ROM_MODE_TEXT
- OR Mode: In the OR-Mode, text and graphics can be displayed and the data is logically “OR-ed”. This
is the most common way of combining text and graphics for example labels on buttons.
- XOR-Mode: In this mode, the text and graphics data are combined via the logical “exclusive OR”.
This can be useful to display text in the negative mode, i.e. white text on black background.
- AND-Mode: The text and graphic data shown on display are combined via the logical “AND
function”.
- TEXT-Mode: This option is only available when displaying just a text. The Text Attribute values are
stored in the graphic area of display memory.
T6963C_line
Prototype sub procedure T6963C_line(dim x0, y0, x1, y1 as integer, dim pcolor as
byte)
Description Draws a line from (x0, y0) to (x1, y1).
Parameters - x0: x coordinate of the line start
- y0: y coordinate of the line end
- x1: x coordinate of the line start
- y1: y coordinate of the line end
- pcolor: color parameter. Valid values: T6963C_BLACK and T6963C_WHITE
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_line(0, 0, 239, 127, T6963C_WHITE)
Notes None.
MikroElektronika
516
mikroBasic PRO for PIC32
T6963C_rectangle
Prototype sub procedure T6963C_rectangle(dim x0, y0, x1, y1 as integer, 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: T6963C_BLACK and T6963C_WHITE
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_rectangle(20, 20, 219, 107, T6963C_WHITE)
Notes None.
T6963C_rectangle_round_edges
Prototype sub procedure T6963C_rectangle_round_edges(dim x0, y0, x1, y1, radius as
integer, dim pcolor as byte)
Description 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: T6963C_BLACK and T6963C_WHITE
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_rectangle_round_edges(20, 20, 219, 107, 12, T6963C_WHITE)
Notes None.
MikroElektronika
517
mikoBasic PRO for PIC32
T6963C_rectangle_round_edges_fill
Prototype sub procedure T6963C_rectangle_round_edges_fill(dim x0, y0, x1, y1, radius
as integer, dim pcolor as byte)
Description 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: T6963C_BLACK and T6963C_WHITE
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_rectangle_round_edges_fill(20, 20, 219, 107, 12, T6963C_WHITE)
Notes None.
T6963C_box
Prototype sub procedure T6963C_box(dim x0, y0, x1, y1 as integer, dim pcolor as
byte)
Description 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
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_box(0, 119, 239, 127, T6963C_WHITE)
Notes None.
T6963C_circle
Prototype sub procedure T6963C_circle(dim x, y as integer, dim r as longint, dim
pcolor as word)
Description Draws a circle on Glcd.
Parameters - x: x coordinate of the circle center
- y: y coordinate of the circle center
- r: radius size
- pcolor: color parameter. Valid values: T6963C_BLACK and T6963C_WHITE
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_circle(120, 64, 110, T6963C_WHITE)
Notes None.
MikroElektronika
518
mikroBasic PRO for PIC32
T6963C_circle_fill
Prototype sub procedure T6963C_circle_fill(dim x, y as integer, dim r as longint, dim
pcolor as byte)
Description Draws a filled 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
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_circle_fill(120, 64, 110, T6963C_WHITE)
Notes None.
T6963C_image
Prototype sub procedure T6963C_image(dim const pic as ^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).
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_image(my_image)
Notes 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.
MikroElektronika
519
mikoBasic PRO for PIC32
T6963C_PartialImage
Prototype sub procedure T6963C_PartialImage(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).
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See T6963C_init routine.
Example ‘ Draws a 10x15 part of the image starting from the upper left corner on the
coordinate (10,12). Original image size is 16x32.
T6963C_PartialImage(10, 12, 10, 15, 16, 32, @image)
Notes 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)
Description 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
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_sprite(76, 4, einstein, 88, 119) ‘ draw a sprite
Notes If px and sx parameters are not multiples of the font width they will be scaled to the nearest lower
number that is a multiple of the font width.
MikroElektronika
520
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
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_set_cursor(cposx, cposy)
Notes None.
T6963C_displayGrPanel
Prototype sub procedure T6963C_displayGrPanel(dim n as word)
Description Display selected graphic panel.
Parameters - n: graphic panel number. Valid values: 0 and 1.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example ‘ display graphic panel 1
T6963C_displayGrPanel(1)
Notes None.
T6963C_displayTxtPanel
Prototype sub procedure T6963C_displayTxtPanel(dim n as word)
Description Display selected text panel.
Parameters - n: text panel number. Valid values: 0 and 1.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example ‘ display text panel 1
T6963C_displayTxtPanel(1)
Notes None.
MikroElektronika
521
mikoBasic PRO for PIC32
T6963C_setGrPanel
Prototype sub procedure T6963C_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.
Parameters - n: graphic panel number. Valid values: 0 and 1.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example ‘ set graphic panel 1 as current graphic panel.
T6963C_setGrPanel(1)
Notes None.
T6963C_setTxtPanel
Prototype sub procedure T6963C_setTxtPanel(dim n as word)
Description Compute start address for selected text panel and set appropriate internal pointers. All subsequent
text operations will be preformed at this text panel.
Parameters - n: text panel number. Valid values: 0 and 1.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example ‘ set text panel 1 as current text panel.
T6963C_setTxtPanel(1)
Notes None.
T6963C_panelFill
Prototype sub procedure T6963C_panelFill(dim v as word)
Description Fill current panel in full (graphic+text) with appropriate value (0 to clear).
Parameters - v: value to fill panel with.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example ‘ clear current panel
T6963C_panelFill(0)
Notes None.
MikroElektronika
522
mikroBasic PRO for PIC32
T6963C_grFill
Prototype sub procedure T6963C_grFill(dim v as word)
Description Fill current graphic panel with appropriate value (0 to clear).
Parameters - v: value to fill graphic panel with.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example ‘ clear current graphic panel
T6963C_grFill(0)
Notes None.
T6963C_txtFill
Prototype sub procedure T6963C_txtFill(dim v as word)
Description Fill current text panel with appropriate value (0 to clear).
Parameters - v: this value increased by 32 will be used to fill text panel.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example ‘ clear current text panel
T6963C_txtFill(0)
Notes None.
T6963C_cursor_height
Prototype sub procedure T6963C_cursor_height(dim n as word)
Description Set cursor size.
Parameters - n: cursor height. Valid values: 0..7.
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example T6963C_cursor_height(7)
Notes None.
MikroElektronika
523
mikoBasic PRO for PIC32
T6963C_graphics
Prototype sub procedure T6963C_graphics(dim n as word)
Description Enable/disable graphic displaying.
Parameters - n: graphic enable/disable parameter. Valid values: 0 (disable graphic dispaying) and 1 (enable
graphic displaying).
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example ‘ enable graphic displaying
T6963C_graphics(1)
Notes None.
T6963C_text
Prototype sub procedure T6963C_text(dim n as word)
Description Enable/disable text displaying.
Parameters - n: on/off parameter. Valid values: 0 (disable text displaying) and 1 (enable text displaying).
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example ‘ enable text displaying
T6963C_text(1)
Notes None.
T6963C_cursor
Prototype sub procedure 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).
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example ‘ set cursor on
T6963C_cursor(1)
Notes None.
MikroElektronika
524
mikroBasic PRO for PIC32
T6963C_cursor_blink
Prototype sub procedure 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).
Returns Nothing.
Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
Example ‘ enable cursor blinking
T6963C_cursor_blink(1)
Notes None.
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.
program T6963C_240x128
include __Lib_T6963C_Consts
MikroElektronika
525
mikoBasic PRO for PIC32
main:
CHECON = 0x32
AD1PCFG = 0xFFFF ‘ initialize AN pins as digital
T6963C_ctrlce_Direction = 0
T6963C_ctrlce = 0 ‘ Enable T6963C
T6963C_ctrlfs_Direction = 0
T6963C_ctrlfs = 0 ‘ Font Select 8x8
T6963C_ctrlmd_Direction = 0
T6963C_ctrlmd = 0 ‘ Column number select
panel = 0
i = 0
curs = 0
cposx = 0
cposy = 0
‘ Initialize T6369C
T6963C_init(240, 128, 8)
T6963C_graphics(1)
T6963C_text(1)
‘ * Text messages
T6963C_write_text(txt, 0, 0, T6963C_ROM_MODE_XOR)
T6963C_write_text(txt1, 0, 15, T6963C_ROM_MODE_XOR)
‘ * Cursor
T6963C_cursor_height(8) ‘ 8 pixel height
T6963C_set_cursor(0, 0) ‘ Move cursor to top left
T6963C_cursor(0) ‘ Cursor off
MikroElektronika
526
mikroBasic PRO for PIC32
‘ *
‘ * Draw solid boxes
‘ *
T6963C_box(0, 0, 239, 8, T6963C_WHITE)
T6963C_box(0, 119, 239, 127, T6963C_WHITE)
‘ *
‘ * Draw rectangles
‘ *
#IFDEF LINE_DEMO
T6963C_rectangle(0, 0, 239, 127, T6963C_WHITE)
T6963C_rectangle(20, 20, 219, 107, T6963C_WHITE)
T6963C_rectangle(40, 40, 199, 87, T6963C_WHITE)
T6963C_rectangle(60, 60, 179, 67, T6963C_WHITE)
#ENDIF
‘ *
‘ * Draw rounded edge rectangle
‘ *
#IFDEF LINE_DEMO
T6963C_Rectangle_Round_Edges(10, 10, 229, 117, 12, T6963C_WHITE)
T6963C_Rectangle_Round_Edges(30, 30, 209, 97, 12, T6963C_WHITE)
T6963C_Rectangle_Round_Edges(50, 50, 189, 77, 12, T6963C_WHITE)
#ENDIF
‘ *
‘ * Draw filled rounded edge rectangle
‘ *
#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_BLACK)
T6963C_Rectangle_Round_Edges_Fill(30, 30, 209, 97, 12, T6963C_WHITE)
T6963C_Rectangle_Round_Edges_Fill(40, 40, 199, 87, 12, T6963C_BLACK)
T6963C_Rectangle_Round_Edges_Fill(50, 50, 189, 77, 12, T6963C_WHITE)
#ENDIF
‘ *
‘ * Draw a cross
‘ *
#IFDEF LINE_DEMO
T6963C_line(0, 0, 239, 127, T6963C_WHITE)
T6963C_line(0, 127, 239, 0, T6963C_WHITE)
#ENDIF
‘ *
‘ * Draw circles
‘ *
#IFDEF LINE_DEMO
T6963C_circle(120, 64, 10, T6963C_WHITE)
T6963C_circle(120, 64, 30, T6963C_WHITE)
T6963C_circle(120, 64, 50, T6963C_WHITE)
T6963C_circle(120, 64, 70, T6963C_WHITE)
T6963C_circle(120, 64, 90, T6963C_WHITE)
T6963C_circle(120, 64, 110, T6963C_WHITE)
T6963C_circle(120, 64, 130, T6963C_WHITE)
#ENDIF
MikroElektronika
527
mikoBasic PRO for PIC32
‘ *
‘ * Draw filled circles
‘ *
#IFDEF FILL_DEMO
T6963C_circle_fill(120, 64, 60, T6963C_WHITE)
T6963C_circle_fill(120, 64, 55, T6963C_BLACK)
T6963C_circle_fill(120, 64, 50, T6963C_WHITE)
T6963C_circle_fill(120, 64, 45, T6963C_BLACK)
T6963C_circle_fill(120, 64, 40, T6963C_WHITE)
T6963C_circle_fill(120, 64, 35, T6963C_BLACK)
T6963C_circle_fill(120, 64, 30, T6963C_WHITE)
T6963C_circle_fill(120, 64, 25, T6963C_BLACK)
T6963C_circle_fill(120, 64, 20, T6963C_WHITE)
T6963C_circle_fill(120, 64, 15, T6963C_BLACK)
T6963C_circle_fill(120, 64, 10, T6963C_WHITE)
T6963C_circle_fill(120, 64, 5, T6963C_BLACK)
#ENDIF
Delay_ms(1000)
T6963C_sprite(76, 4, @einstein, 88, 119) ‘ Draw a sprite
Delay_ms(1000)
T6963C_image(@mikroE_240x128_bmp)
T6963C_displayGrPanel(1)
Delay_ms(1000)
#IFDEF PARTIAL_IMAGE_DEMO
T6963C_grFill(0)
T6963C_PartialImage(0, 0, 64, 64, 240, 128, @mikroE_240x128_bmp) ‘ Display partial
image
Delay_ms(1000)
T6963C_graphics(0)
#ENDIF
T6963C_image(@mikroE_240x128_bmp)
T6963C_graphics(1)
T6963C_displayGrPanel(0)
‘ * If RB8 is pressed, toggle the display between graphic panel 0 and graphic 1
if(RB8_bit <> 0) then
T6963C_graphics(1)
T6963C_text(0)
Delay_ms(300)
MikroElektronika
528
mikroBasic PRO for PIC32
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
‘*
‘* If RB13 is pressed, perform the “Partial image” demonstration
‘*
#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)
MikroElektronika
529
mikoBasic PRO for PIC32
T6963C_displayGrPanel(1)
T6963C_write_text(txt2, 5, 15, T6963C_ROM_MODE_XOR)
Delay_1sec()
T6963C_grFill(0)
T6963C_PartialImage(0, 0, 64, 64, 240, 128, @mikroE_240x128_bmp)
Delay_ms(1500)
T6963C_txtFill(0)
T6963C_write_text(txt, 0, 0, T6963C_ROM_MODE_XOR)
T6963C_write_text(txt1, 0, 15, T6963C_ROM_MODE_XOR)
end if
#ENDIF
end if
end if
end if
end if
‘*
‘ * Move cursor, even if not visible
‘*
Inc(cposx)
if (cposx = T6963C_txtCols) then
cposx = 0
Inc(cposy)
if (cposy = T6963C_grHeight div T6963C_CHARACTER_HEIGHT) then
cposy = 0
end if
end if
T6963C_set_cursor(cposx, cposy)
Delay_ms(100)
wend
end.
MikroElektronika
530
mikroBasic PRO for PIC32
HW Connection
MikroElektronika
531
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.
MikroElektronika
532
mikroBasic 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_PartialImage
- TFT_Image_Jpeg
- TFT_RGBToColor16bit
- TFT_Color16bitToRGB
MikroElektronika
533
mikoBasic PRO for PIC32
TFT_Init
Prototype sub procedure TFT_Init(dim display_width, display_height as word)
Returns Nothing
Description Initializes TFT display in the 8-bit working mode.
Parameters:
MikroElektronika
534
mikroBasic PRO for PIC32
TFT_Set_Index
Prototype sub procedure TFT_Set_Index(dim index as byte)
Returns Nothing
Description Accesses register space of the controller and sets the desired register.
Parameters:
TFT_Write_Command
Prototype sub procedure TFT_Write_Command(dim cmd as byte)
Returns Nothing
Description Accesses data space and writes a command.
Parameters:
TFT_Write_Data
Prototype sub procedure TFT_Write_Data(dim _data as word)
Returns Nothing
Description Writes date into display memory.
Parameters:
- _data:data to be written.
Requires TFT module needs to be initialized. See the TFT_Init routine.
Example ‘ Send data
TFT_Write_Data(0x02)
MikroElektronika
535
mikoBasic PRO for PIC32
TFT_Set_Active
Prototype sub procedure TFT_Set_Active(dim Set_Index_Ptr as ^TTFT_Set_Index_Ptr, dim
Write_Command_Ptr as ^TTFT_Write_Command_Ptr, dim Write_Data_Ptr as ^TTFT_
Write_Data_Ptr)
Returns Nothing
Description This function sets appropriate pointers to a user-defined basic routines in order to enable multiple
working modes.
Parameters:
main :
TRISE = 0
TRISD = 0
TFT_Set_Active(Set_Index,Write_Command,Write_Data)
TFT_Init(320, 240)
.....
end.
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)
Returns Nothing
Description Sets font, its color and font orientation.
Parameters:
Value Description
CL_AQUA Aqua color
CL_BLACK Black color
CL_BLUE Blue color
CL_FUCHSIA Fuchsia color
CL_GRAY Gray color
CL_GREEN Green color
CL_LIME Lime color
CL_MAROON Maroon color
CL_NAVY Navy color
CL_OLIVE Olive color
CL_PURPLE Purple color
CL_RED Red color
CL_SILVER Silver color
CL_TEAL Teal color
CL_WHITE White color
CL_YELLOW Yellow color
Value Description
FO_HORIZONTAL Horizontal orientation
FO_VERTICAL Vertical orientation
MikroElektronika
537
mikoBasic PRO for PIC32
TFT_Write_Char
Prototype sub procedure TFT_Write_Char(dim ch, x, y as word)
Returns Nothing.
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.
Requires TFT module needs to be initialized. See the TFT_Init routine.
Example TFT_Write_Char(“A”,22,23)
TFT_Write_Text
Prototype sub procedure TFT_Write_Text(dim byref text as string, dim x, y as word)
Returns Nothing.
Description Writes text on the TFT at coordinates (x, y).
Parameters:
MikroElektronika
538
mikroBasic PRO for PIC32
TFT_Fill_Screen
Prototype sub procedure TFT_Fill_Screen(dim color as word)
Returns Nothing.
Description Fills screen memory block with given color.
Parameters:
MikroElektronika
539
mikoBasic PRO for PIC32
TFT_Dot
Prototype sub procedure TFT_Dot(dim x, y as integer, dim color as word)
Returns Nothing.
Description Draws a dot on the TFT at coordinates (x, y).
Parameters:
Value Description
CL_AQUA Aqua color
CL_BLACK Black color
CL_BLUE Blue color
CL_FUCHSIA Fuchsia color
CL_GRAY Gray color
CL_GREEN Green color
CL_LIME Lime color
CL_MAROON Maroon color
CL_NAVY Navy color
CL_OLIVE Olive color
CL_PURPLE Purple color
CL_RED Red color
CL_SILVER Silver color
CL_TEAL Teal color
CL_WHITE White color
CL_YELLOW Yellow color
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)
Returns Nothing.
Description Sets color and thickness parameter for drawing line, circle and rectangle elements.
Parameters:
Value Description
CL_AQUA Aqua color
CL_BLACK Black color
CL_BLUE Blue color
CL_FUCHSIA Fuchsia color
CL_GRAY Gray color
CL_GREEN Green color
CL_LIME Lime color
CL_MAROON Maroon color
CL_NAVY Navy color
CL_OLIVE Olive color
CL_PURPLE Purple color
CL_RED Red color
CL_SILVER Silver color
CL_TEAL Teal color
CL_WHITE White color
CL_YELLOW Yellow color
MikroElektronika
541
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)
Returns Nothing.
Description Sets color and gradient which will be used to fill circles or rectangles.
Parameters:
MikroElektronika
542
mikroBasic PRO for PIC32
Value Description
1 Enable gradient.
0 Disable gradient.
Value Description
LEFT_TO_RIGHT Left to right gradient orientation
TOP_TO_BOTTOM Top to bottom gradient orientation
Value Description
CL_AQUA Aqua color
CL_BLACK Black color
CL_BLUE Blue color
CL_FUCHSIA Fuchsia color
CL_GRAY Gray color
CL_GREEN Green color
CL_LIME Lime color
CL_MAROON Maroon color
CL_NAVY Navy color
CL_OLIVE Olive color
CL_PURPLE Purple color
CL_RED Red color
CL_SILVER Silver color
CL_TEAL Teal color
CL_WHITE White color
CL_YELLOW Yellow color
MikroElektronika
543
mikoBasic PRO for PIC32
Value Description
CL_AQUA Aqua color
CL_BLACK Black color
CL_BLUE Blue color
CL_FUCHSIA Fuchsia color
CL_GRAY Gray color
CL_GREEN Green color
CL_LIME Lime color
CL_MAROON Maroon color
CL_NAVY Navy color
CL_OLIVE Olive color
CL_PURPLE Purple color
CL_RED Red color
CL_SILVER Silver color
CL_TEAL Teal color
CL_WHITE White color
CL_YELLOW Yellow color
TFT_Line
Prototype sub procedure TFT_Line(dim x1, y1, x2, y2 as integer)
Returns Nothing.
Description Draws a line from (x1, y1) to (x2, y2).
Parameters:
MikroElektronika
544
mikroBasic PRO for PIC32
TFT_H_Line
Prototype sub procedure TFT_H_Line(dim x_start, x_end, y_pos as integer)
Returns Nothing.
Description Draws a horizontal line on TFT.
Parameters:
TFT_V_Line
Prototype sub procedure TFT_V_Line(dim y_start, y_end, x_pos as integer)
Returns Nothing.
Description Draws a vertical line on TFT.
Parameters:
TFT_Rectangle
Prototype sub procedure TFT_Rectangle(dim x_upper_left, y_upper_left, x_bottom_right,
y_bottom_right as integer)
Returns Nothing.
Description Draws a rectangle on TFT.
Parameters:
MikroElektronika
545
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)
Returns Nothing.
Description Draws a rounded edge rectangle on TFT.
Parameters:
TFT_Circle
Prototype sub procedure TFT_Circle(dim x_center, y_center, radius as integer)
Returns Nothing.
Description Draws a circle on TFT.
Parameters:
TFT_Image
Prototype sub procedure TFT_Image(dim left, top as word, dim image as far const byte,
dim stretch as byte)
Returns Nothing.
Description Displays an image on a desired location.
Parameters:
MikroElektronika
546
mikroBasic PRO for PIC32
TFT_Partial_Image
Prototype sub procedure TFT_Partial_Image(dim left, top, width, height as word, dim
image as far const byte, dim stretch as byte)
Returns Nothing.
Description Displays a partial area of the image on a desired location.
Parameters:
TFT_Image_Jpeg
Prototype sub function TFT_Image_Jpeg(dim left, top as word, dim image as far const
byte) as byte
Returns - 0 - if image is loaded and displayed successfully.
- 1 - if error occured.
Description Displays a JPEG image on a desired location.
Parameters:
MikroElektronika
547
mikoBasic PRO for PIC32
TFT_RGBToColor16bit
Prototype sub function TFT_RGBToColor16bit(dim rgb_red, rgb_green, rgb_blue as byte)
as word
Returns 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:
TFT_Color16bitToRGB
Prototype sub procedure TFT_Color16bitToRGB(dim color as word, dim rgb_red, rgb_green,
rgb_blue as ^byte)
Returns Nothing.
Description Converts true color into 5:6:5 RGB format.
Parameters:
MikroElektronika
548
mikroBasic PRO for PIC32
HW Connection
TFT HW connection
MikroElektronika
549
mikoBasic PRO for PIC32
Library Routines
- TP_Init
- TP_Set_ADC_Threshold
- TP_Press_Detect
- TP_Get_Coordinates
- TP_Calibrate_Bottom_Left
- TP_Calibrate_Upper_Right
- TP_Get_Calibration_Consts
- TP_Set_Calibration_Consts
MikroElektronika
550
mikroBasic PRO for PIC32
TP_Init
Prototype sub procedure TP_Init(dim display_width as word, dim display_height as word,
dim readX_ChNo as byte, dim readY_ChNo as byte)
Description Initialize touch panel display. Default touch panel ADC threshold value is set to 3900.
Parameters
- display_width: set display width.
- display_height: set display height.
- readX_ChNo: read X coordinate from desired ADC channel.
- readY_ChNo: read Y coordinate from desired ADC channel.
Returns Nothing.
Requires Before calling this function initialize ADC module.
Example ADC1_Init() ‘ Initalize ADC module
TP_Init(128, 64, 6, 7) ‘ Initialize touch panel, dimensions 128x64
Notes None.
TP_Set_ADC_Threshold
Prototype sub procedure TP_Set_ADC_Threshold(dim threshold as word)
Description Set custom ADC threshold value, call this function after TP_Init.
Parameters - threshold: custom ADC threshold value.
Returns Nothing.
Requires TP_Init has to be called before using this routine.
Example TP_Set_ADC_Threshold(3900) ‘ Set touch panel ADC threshold
Notes None.
MikroElektronika
551
mikoBasic PRO for PIC32
TP_Press_Detect
Prototype sub function TP_Press_Detect() as byte
Description Detects if the touch panel has been pressed.
Parameters None.
Returns - 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.
MikroElektronika
552
mikroBasic PRO for PIC32
TP_Get_Coordinates
Prototype sub function TP_Get_Coordinates(dim byref x_coordinate as word, dim byref
y_coordinate as word) as byte
Description 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.
Returns - 1 - if reading is within display dimension range.
- 0 - if reading is out of display dimension range.
Requires Nothing.
Example if (TP_Get_Coordinates(@x_coord, @y_coord) = 0) then
...
end if
Notes None.
TP_Calibrate_Bottom_Left
Prototype sub procedure TP_Calibrate_Bottom_Left()
Description Calibrate bottom left corner of the touch Panel.
Parameters None.
Returns Nothing.
Requires Nothing.
Example TP_Calibrate_Bottom_Left() ‘ Calibration of bottom left corner
Notes None.
TP_Calibrate_Upper_Right
Prototype sub procedure TP_Calibrate_Upper_Right()
Description Calibrate upper right corner of the touch panel.
Parameters None.
Returns Nothing.
Requires Nothing.
Example TP_Calibrate_Upper_Right() ‘ Calibration of upper right corner
Notes None.
MikroElektronika
553
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_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.
Returns Nothing.
Requires Nothing.
Example TP_Get_Calibration_Consts(@x_min, @y_min, @x_max, @y_max) ‘ Get calibration
constants
Notes None.
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)
Description 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.
Returns Nothing.
Requires Nothing.
Example TP_Set_Calibration_Consts(148, 3590, 519, 3370) ‘ Set calibration
constants
Notes None.
MikroElektronika
554
mikroBasic PRO for PIC32
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
MikroElektronika
555
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)
Description 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.
Returns Nothing.
Requires Before calling this function initialize ADC module.
Example ADC1_Init() ‘ Initalize ADC module
TP_TFT_Init(320, 240, 13, 12) ‘ Initialize touch panel, dimensions 320x240
Notes None.
TP_TFT_Set_ADC_Threshold
Prototype sub procedure TP_TFT_Set_ADC_Threshold(dim threshold as word)
Description Set custom ADC threshold value, call this function after TP_TFT_Init.
Parameters - threshold: custom ADC threshold value.
Returns Nothing.
Requires TP_TFT_Init has to be called before using this routine.
Example TP_TFT_Set_ADC_Threshold(900) ‘ Set touch panel ADC threshold
Notes None.
MikroElektronika
556
mikroBasic PRO for PIC32
TP_TFT_Press_Detect
Prototype sub function TP_TFT_Press_Detect() as byte
Description Detects if the touch panel has been pressed.
Parameters None.
Returns - 1 - if touch panel is pressed.
- 0 - otherwise.
Requires Global variables:
MikroElektronika
557
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
Description 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.
Returns - 1 - if reading is within display dimension range.
- 0 - if reading is out of display dimension range.
Requires Nothing.
Example if (TP_TFT_Get_Coordinates(@x_coord, @y_coord) = 0) then
...
end if
Notes None.
TP_TFT_Calibrate_Min
Prototype sub procedure TP_TFT_Calibrate_Min()
Description Calibrate bottom left corner of the touch Panel.
Parameters None.
Returns Nothing.
Requires Nothing.
Example TP_TFT_Calibrate_Min() ‘ Calibration of bottom left corner
Notes None.
TP_TFT_Calibrate_Max
Prototype sub procedure TP_TFT_Calibrate_Max()
Description Calibrate upper right corner of the touch panel.
Parameters None.
Returns Nothing.
Requires Nothing.
Example TP_TFT_Calibrate_Max() ‘ Calibration of upper right corner
Notes None.
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 parameters.
Parameters - x_min: x coordinate of the bottom left corner of the working area.
- x_max: x coordinate of the upper right corner of the working area.
- y_min: y coordinate of the bottom left corner of the working area.
- y_max: y coordinate of the upper right corner of the working area.
Returns Nothing.
Requires Nothing.
Example TP_TFT_Get_Calibration_Consts(@x_min, @y_min, @x_max, @y_max) ‘ Get
calibration constants
Notes None.
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)
Description 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.
Returns Nothing.
Requires Nothing.
Example TP_TFT_Set_Calibration_Consts(148, 3590, 519, 3370) ‘ Set calibration
constants
Notes None.
MikroElektronika
559
mikoBasic PRO for PIC32
HW Connection
MikroElektronika
560
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
MikroElektronika
561
mikoBasic PRO for PIC32
UARTx_Init
Prototype sub procedure UARTx_Init(dim baud_rate as longword)
Description Configures and initializes the UART module.
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
562
mikroBasic 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)
Description 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:
High/Low Speed
Description Predefined library const
Low Speed UART _UART_LOW_SPEED
Hi Speed UART _UART_HI_SPEED
Data/Parity Mode
Description Predefined library const
8-bit data, no parity _UART_8BIT_NOPARITY
8-bit data, even parity _UART_8BIT_EVENPARITY
8-bit data, odd parity _UART_8BIT_ODDPARITY
9-bit data, no parity _UART_9BIT_NOPARITY
Stop bits
Description Predefined library const
One stop bit _UART_ONE_STOPBIT
Two stop bits _UART_TWO_STOPBITS
Returns Nothing.
Requires Routine requires the UART module.
Example
Notes Refer to the device data sheet for baud rates allowed for specific Fosc.
UART library routines require you to specify the module you want to use. To select the desired UART
module, simply change the letter x in the routine prototype for a number from 1 to 6.
Switching between the UART modules in the UART library is done by the UART_Set_Active function
(UART modules have to be previously initialized).
Number of UART modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
563
mikoBasic PRO for PIC32
UARTx_Data_Ready
Prototype sub function UARTx_Data_Ready() as word
Description The function tests if data in receive buffer is ready for reading.
Parameters None.
Returns - 1 if data is ready for reading
- 0 if there is no data in the receive register
Requires Routine requires at least one UART module.
Used UART module must be initialized before using this routine. See UARTx_Init and UARTx_Init_
Advanced routines.
Example dim receive as word
...
‘ read data if ready
if (UART1_Data_Ready() = 1) then
receive = UART1_Read()
end if
Notes 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
Description Use the function to test if the transmit shift register is empty or not.
Parameters None.
Returns - 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.
Example ‘ If the previous data has been shifted out, send next data:
if (UART1_Tx_Idle() = 1) then
UART1_Write(_data)
end if
Notes 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.
MikroElektronika
564
mikroBasic PRO for PIC32
UARTx_Read
Prototype sub function UARTx_Read() as word
Description The function receives a byte via UART. Use the UARTx_Data_Ready function to test if data is ready
first.
Parameters None.
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.
Example dim receive as word
...
‘ read data if ready
if (UART1_Data_Ready() = 1) then
receive = UART1_Read()
end if
Notes 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.
MikroElektronika
565
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).
Used UART module must be initialized before using this routine. See UARTx_Init and UARTx_Init_
Advanced routines.
Example Read text until the sequence “OK” is received, and send back what’s been received:
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.
Notes 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.
MikroElektronika
566
mikroBasic PRO for PIC32
UARTx_Write
Prototype sub procedure UARTx_Write(dim data_ as word)
Description The function transmits a byte via the UART module.
Parameters - _data: data to be sent.
Returns Nothing.
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.
Number of UART modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
UARTx_Write_Text
Prototype sub procedure UARTx_Write_Text(dim byref uart_text as string[20])
Description Sends text via UART. Text should be zero terminated.
Parameters - UART_text: text to be sent
Returns Nothing.
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.
Example Read text until the sequence “OK” is received, and send back what’s been received:
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.
Notes 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.
MikroElektronika
567
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 routines.
Parameters Parameters:
Used UART module must be initialized before using this routine. See UARTx_Init and UARTx_Init_
Advanced routines.
Example UART1_Init(9600); // initialize UART1 module
UART2_Init(9600); // initialize UART2 module
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 .
program UART1
dim uart_rd as byte
main:
CHECON = 0x32
AD1PCFG = 0xFFFF ‘ Configure AN pins as digital I/O
UART1_Write_Text(“Start”)
UART1_Write(13)
UART1_Write(10)
MikroElektronika
569
mikoBasic PRO for PIC32
HW Connection
RS232 HW connection
MikroElektronika
570
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, PDA’s, etc.
USB Library contains HID routines that support HID class devices, and also the generic routines that can be used with
vendor specified drivers.
- Keyboards and pointing devices, for example: standard mouse devices, trackballs, and joysticks.
- Front-panel controls, for example: knobs, switches, buttons, and sliders.
- Controls that might be found on devices such as telephones, VCR remote controls, games or simulation
devices, for example: data gloves, throttles, steering wheels, and rudder pedals.
- Devices that may not require human interaction but provide data in a similar format to HID class devices,
for example, bar-code readers, thermometers, or voltmeters.
Many typical HID class devices include indicators, specialized displays, audio feedback, and force or tactile feedback.
Therefore, the HID class definition includes support for various types of output directed to the end user.
Descriptor File
Each project based on the USB library should include a descriptor source file which contains vendor id and name,
product id and name, report length, and other relevant information. To create a descriptor file, use the integrated USB
HID terminal of 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
MikroElektronika
571
mikoBasic PRO for PIC32
HID_Enable
Prototype sub procedure HID_Enable(dim readbuff as ^byte, dim writebuff as ^byte)
Description Enables USB HID communication.
Parameters - readbuff: Read Buffer.
- writebuff: Write Buffer.
Example HID_Enable(@readbuff,@writebuff)
Notes This function needs to be called before using other routines of USB HID Library.
HID_Read
Prototype sub function HID_Read() as byte
Description Receives message from host and stores it in the Read Buffer.
Parameters None.
Returns If the data reading has failed, the function returns 0. Otherwise, it returns number of characters
received from the host.
Requires USB HID needs to be enabled before using this function. See HID_Enable.
Example while(HID_Read() = 0)
wend
Notes None.
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.
Returns If the data transmitting has failed, the function returns 0. Otherwise, it returns number of transmitted
bytes.
Requires USB HID needs to be enabled before using this function. See HID_Enable.
Example while(HID_Write(@writebuff,64) = 0)
wend
Notes Function call needs to be repeated as long as data is not successfuly sent.
MikroElektronika
572
mikroBasic PRO for PIC32
HID_Disable
Prototype sub procedure HID_Disable()
Description Disables USB HID communication.
Parameters None.
Returns Nothing.
Requires USB HID needs to be enabled before using this function. See HID_Enable.
Example HID_Disable()
Notes None.
USB_Interrupt_Proc
Prototype sub procedure USB_Interrupt_Proc()
Description This routine is used for servicing various USB bus events. Should be called inside USB interrupt
routine.
Parameters None.
Returns Nothing.
Requires Nothing.
MikroElektronika
573
mikoBasic PRO for PIC32
USB_Polling_Proc
Prototype sub procedure USB_Polling_Proc()
Description This routine is used for servicing various USB bus events. It should be periodically, preferably every
100 microseconds.
Parameters None.
Returns Nothing.
Requires Nothing.
Example while TRUE
USB_Polling_Proc()
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
Notes 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.
Returns Nothing.
Requires USB needs to be enabled before using this function. See HID_Enable.
Example Gen_Enable(@readbuff,@writebuff)
Notes None.
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
Description Generic routine that receives the specified data from the specified endpoint.
Parameters - readbuff: 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.
Requires USB needs to be enabled before using this function. See HID_Enable.
Example while(Gen_Read(@readbuff,64,1) = 0)
wend
Notes None.
Gen_Write
Prototype sub function Gen_Write(dim writebuff as ^byte, dim as length as byte, dim
ep as byte) as byte
Description 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.
Requires USB needs to be enabled before using this function. See HID_Enable.
Example while(Gen_Write(@writebuff,64,1) = 0)
wend
Notes None.
MikroElektronika
575
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.
program HID_Write_Polling
main:
CHECON = 0x32
AD1PCFG = 0xFFFF
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 Connection
MikroElektronika
576
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
MikroElektronika
577
mikoBasic PRO for PIC32
Button
Prototype sub function Button(dim byref port as word, dim pin as byte, dim time as
word, dim ActiveState as byte) as word
Description The function eliminates the influence of contact flickering upon pressing a button (debouncing). The
Button pin is tested just after the function call and then again after the debouncing period has expired.
If the pin was in the active state in both cases then the function returns 255 (true).
Parameters - port: button port address
- pin: button pin
- time: debouncing period in milliseconds
- active_state: determines what is considered as active state. Valid values: 0 (logical zero) and
1 (logical one)
Returns -255 if the pin was in the active state for given period.
- 0 otherwise
Requires Nothing.
Example program Button_Test
main:
oldstate = 0
ADPCFG = 0xFFFF ‘ initialize AN pins as digital
TRISD = 0xFFFF ‘ initialize portd as input
TRISB = 0x0000 ‘ initialize portb as output
while TRUE
if (Button(PORTD, 0, 1, 1)) then ‘ detect logical one on RB0 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
end.
Notes None.
MikroElektronika
578
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
Prototype sub function isalnum(dim character as byte) as byte
Description Function returns 0xFF if the character is alphanumeric (A-Z, a-z, 0-9), otherwise returns zero.
Example res = isalnum(“o”) ‘ returns 0xFF
res = isalnum(“\r”) ‘ returns 0
isalpha
Prototype sub function isalpha(dim character as byte) as word
Description Function returns 0xFF if the character is alphabetic (A-Z, a-z), otherwise returns zero.
Example res = isalpha(“A”) ‘ returns 0xFF
res = isalpha(“1”) ‘ returns 0
iscntrl
Prototype sub function iscntrl(dim character as byte) as word
Description Function returns 0xFF if the character is a control or delete character(decimal 0-31 and 127),
otherwise returns zero.
Example res = iscntrl(“\r”) ‘ returns 0xFF
res = iscntrl(“o”) ‘ returns 0
isdigit
Prototype sub function isdigit(dim character as byte) as word
Description Function returns 0xFF if the character is a digit (0-9), otherwise returns zero.
Example res = isdigit(“o”) ‘ returns 0xFF
res = isdigit(“1”) ‘ returns 0
MikroElektronika
579
mikoBasic PRO for PIC32
isgraph
Prototype sub function isgraph(dim character as byte) as word
Description Function returns 0xFF if the character is a printable, excluding the space (decimal 32), otherwise
returns zero.
Example res = isgraph(“o”) ‘ returns 0xFF
res = isgraph(“ “) ‘ returns 0
islower
Prototype sub function islower(dim character as byte) as word
Description Function returns 0xFF if the character is a lowercase letter (a-z), otherwise returns zero.
Example res = islower(“0”) ‘ returns 0xFF
res = islower(“A”) ‘ returns 0
ispunct
Prototype sub function ispunct(dim character as byte) as word
Description Function returns 0xFF if the character is a punctuation (decimal 32-47, 58-63, 91-96, 123-126),
otherwise returns zero.
Example res = ispunct(“.”) ‘ returns 0xFF
res = ispunct(“1”) ‘ returns 0
isspace
Prototype sub function isspace(dim character as byte) as word
Description Function returns 0xFF if the character is a white space (space, tab, CR, HT, VT, NL, FF), otherwise
returns zero.
Example res = isspace(“ “) ‘ returns 0xFF
res = isspace(“1”) ‘ returns 0
isupper
Prototype sub function isupper(dim character as byte) as word
Description Function returns 0xFF if the character is an uppercase letter (A-Z), otherwise returns zero.
Example res = isupper(“A”) ‘ returns 0xFF
res = isupper(“a”) ‘ returns 0
MikroElektronika
580
mikroBasic PRO for PIC32
isxdigit
Prototype sub function isxdigit(dim character as byte) as word/p>
Description Function returns 0xFF if the character is a hex digit (0-9, A-F, a-f), otherwise returns zero.
Example res = isxdigit(“A”) ‘ returns 0xFF
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.
Example 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.
Example res = tolower(“A”) ‘ returns a
res = tolower(“b”) ‘ returns b
MikroElektronika
581
mikoBasic PRO for PIC32
Conversions Library
mikroBasic PRO for PIC32 Conversions Library provides routines for numerals to strings and BCD/decimal
conversions.
Library Routines
You can get text representation 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
- StrToInt
- 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])
Description Converts input byte to a string. The output string is right justified and remaining positions on the left (if
any) are filled with blanks.
Parameters - input: byte to be converted
- output: destination string
Returns Nothing.
Requires Destination string should be at least 4 characters in length.
Example dim t as byte
txt as string[3]
...
t = 24
ByteToStr(t, txt) ‘ txt is “ 24” (one blank here)
Notes None.
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 string
Returns Nothing.
Requires Destination string should be at least 5 characters in length.
Example dim t as short
txt as string[4]
...
t = -24
ByteToStr(t, txt) ‘ txt is “ -24” (one blank here)
Notes None.
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
- output: destination string
Returns Nothing.
Requires Destination string should be at least 6 characters in length.
Example dim t as word
txt as string[5]
...
t = 437
WordToStr(t, txt) ‘ txt is “ 437” (two blanks here)
Notes None.
MikroElektronika
583
mikoBasic PRO for PIC32
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: signed integer number to be converted
- output: destination string
Returns Nothing.
IntToStr
Prototype sub procedure IntToStr(dim input as integer, dim byref output as
string[6])
Description Converts input integer number to a string. The output string is right justified and the remaining positions
on the left (if any) are filled with blanks.
Returns Nothing.
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
Returns Nothing.
Notes None.
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
Returns Nothing.
Notes None.
MikroElektronika
585
mikoBasic PRO for PIC32
FloatToStr
Prototype sub procedure 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
Returns Nothing.
Requires Nothing.
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 string
Returns Nothing.
Requires Nothing.
Example dim t as word
txt as string[5]
t = 437
WordToStrWithZeros(t, txt) ‘ txt is “00437”
Notes None.
MikroElektronika
586
mikroBasic PRO for PIC32
IntToStrWithZeros
Prototype sub procedure 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: integer number to be converted
- output: destination string
Returns Nothing.
Requires Nothing.
Example dim t as integer
txt as string[6]
t = -3276
IntToStrWithZeros(t, txt) ‘ txt is “-03276”
Notes None.
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.
Parameters - input: unsigned long number to be converted
- output: destination string
Returns Nothing.
Requires Nothing.
Example dim t as longword
txt as string[10]
t = 12345678
LongWordToStrWithZeros(t, txt) ‘ txt is “0012345678”
Notes None.
MikroElektronika
587
mikoBasic PRO for PIC32
LongIntToStrWithZeros
Prototype sub procedure LongIntToStrWithZeros(dim input as longint, dim byref output
as string[11])
Description Converts input longint to a string. The output string is right justified and the remaining positions on the
left (if any) are filled with zeros.
Parameters - input: word to be converted
- output: destination string
Returns Nothing.
Requires Nothing.
t = -12345678
LongIntToStrWithZeros(t, txt) ‘ txt is “-0012345678”
Notes None.
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.
Requires Nothing.
Example dim t as byte
txt as string[2]
t = 2
ByteToHex(t, txt) ‘ txt is “02”
Notes None.
MikroElektronika
588
mikroBasic PRO for PIC32
ShortToHex
Prototype sub procedure ShortToHex(dim input as short, 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.
Parameters - input: short number to be converted
- output: destination string
Returns Nothing.
Requires Nothing.
Example dim t as short
txt as string[2]
...
t = -100
ShortToHex(t, txt) ‘ txt is “9C”
Notes None.
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
Returns Nothing.
Requires Nothing.
t = 1111
WordToHex(t, txt) ‘ txt is “0457”
Notes None.
MikroElektronika
589
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 any) are filled with zeros.
Requires Nothing.
Example dim input as integer
txt as string[4]
input = -32768
IntToHex(input, txt) ‘ txt is “8000”
Notes None.
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
Returns Nothing.
Example dim input as longword
txt as string[8]
input = 65535
LongWordToHex(input, txt) ‘ txt is “0000FFFF”
Notes None.
MikroElektronika
590
mikroBasic PRO for PIC32
LongIntToHex
Prototype sub procedure LongIntToHex(dim input as longint, 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: longint number to be converted
- output: destination string
Returns Nothing.
Requires Nothing.
Example dim input as longint
txt as string[8]
input = -2147483648
LongIntToHex(input, txt) ‘ txt is “80000000”
Notes None.
StrToInt
Prototype sub function StrToInt(dim byref input as string[6]) as integer
Description Converts a string to an integer.
main:
...
ii = StrToInt(“-1234”)
end.
Notes None.
MikroElektronika
591
mikoBasic PRO for PIC32
StrToWord
Prototype sub function StrToWord(dim byref input as string[5]) as word
Description Converts a string to word.
main:
...
ww = StrToword(“65432”)
end.
Notes None.
Bcd2Dec
Prototype sub function Bcd2Dec(dim bcdnum as byte) as byte
Description Converts input BCD number to its appropriate decimal representation.
Parameters - bcdnum: number to be converted
Requires Nothing.
Notes None.
MikroElektronika
592
mikoBasic PRO for PIC32
Dec2Bcd
Prototype sub function Dec2Bcd(dim decnum as byte) as byte
Description Converts input number to its appropriate BCD representation.
Parameters - decnum: number to be converted
Requires Nothing.
Notes None.
Bcd2Dec16
Prototype sub function Bcd2Dec16(dim bcdnum as word) as word
Description Converts 16-bit BCD numeral to its decimal equivalent.
Parameters - bcdnum 16-bit BCD numeral to be converted
Returns Converted decimal value.
Requires Nothing.
Example dim a, b as word
...
a = 0x1234 ‘ a equals 4660
b = Bcd2Dec16(a) ‘ b equals 1234
Notes None.
Dec2Bcd16
Prototype sub function Dec2Bcd16(dim decnum as word) as word
Description Converts decimal value to its BCD equivalent.
Parameters - decnum decimal number to be converted
Returns Converted BCD value.
Requires Nothing.
Example dim a, b as word
...
a = 2345
b = Dec2Bcd16(a) ‘ b equals 9029
Notes None.
MikroElektronika
593
mikoBasic PRO for PIC32
Setjmp Library
The Setjmp library contains functions and types definitions for bypassing the normal function call and return
discipline.
Library Routines
- Setjmp
- Longjmp
Setjmp
Prototype sub function setjmp(dim byref env as word[4]) as integer
Parameters :
- env: buffer suitable for holding information needed for restoring calling environment
Requires Nothing.
Example dim buf as word[4]
...
Setjmp(buf)
Longjmp
Prototype sub procedure longjmp(dim byref env as word[4], dim val as integer)
Returns Nothing.
Description Restores calling environment saved in the env buffer by the most recent invocation of setjmp. If there
has been no such invocation, or the function containing the invocation of setjmp has terminated in the
interim, the behavior is undefined.
Parameters :
- env: buffer holding the information saved by the corresponding setjmp invocation
- val: value to be returned by the corresponding setjmp function
Requires Invocation of longjmp must occur before return from the function in which setjmp was called
encounters.
Example 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 other hand, restores the
environment saved by the most recent invocation of the Setjmp() with the corresponding buf argument.
program Setjmp
dim buf as word[4] ‘ Note: Program flow diagrams are indexed according
‘ to the sequence of execution
MikroElektronika
595
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
- ltrim
- 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
0xFFFF if ch was not found.
For the parameter p you can use either a numerical value (literal/variable/constant) indicating memory
address or a dereferenced value of an object, for example @mystring or @PORTB.
Example txt = “mikroElektronika”
res = memchr(@txt, “e”, 16) ‘ example locates first occurrence of the letter
‘e’ in the string ‘txt’ in the first 16 characters of the string
MikroElektronika
596
mikroBasic PRO for PIC32
memcmp
Prototype sub function memcmp(dim p1, 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
< 0 p1 “less than” p2
= 0 p1 “equal to” p2
> 0 p1 “greater than” p2
The value returned by the function is determined by the difference between the values of the first pair
of words that differ in the strings being compared.
For parameters p1 and p2 you can use either a numerical value (literal/variable/constant) indicating
memory address or a dereferenced value of an object, for example @mystring or @PORTB.
Example txt = “mikroElektronika”
txt_sub = “mikro”
res = memcmp(@txt, @txt_sub, 16) ‘ returns 69, which is ASCII code of the
first differing character - letter ‘E’
memcpy
Prototype sub procedure memcpy(dim p1, 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 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.
Example txt = “mikroElektronika”
txt_sub = “mikr”
MikroElektronika
597
mikoBasic PRO for PIC32
memmove
Prototype sub procedure memmove(dim p1, 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.
Example txt = “mikroElektronika”
txt_sub = “mikr”
memset
Prototype sub procedure 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 p you can use either a numerical value (literal/variable/constant) indicating memory
address or a dereferenced value of an object, for example @mystring or @PORTB.
Example txt = “mikroElektronika”
memset(@txt, “a”, 2) ‘ routine will copy the character ‘a’ into each of the
first ‘n’ characters of the string ‘txt”,
strcat
Prototype sub procedure strcat(dim byref s1, s2 as string)
Description The function appends the value of string s2 to string s1 and terminates s1 with a null character.
Example txt = “mikroElektronika”
txt_sub = “mikr”
txt[3] = 0
strcat(txt, “_test”) ‘ routine will append the ‘_test’ at the place of the
first null character, adding terminating null character to the result
MikroElektronika
598
mikroBasic PRO for PIC32
strcat2
Prototype sub procedure strcat2(dim byref l, s1, 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 l string.
Example dim txt as string[16]
txt_sub as string[5]
l as string[21]
strcat2(l, txt, txt_sub) ‘ routine will adjoin strings txt and txt_sub and
place the result into l
strchr
Prototype sub function strchr(dim byref s as string, dim ch as byte) 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 ch found in s; if no matching character
was found, the function returns 0xFFFF.
Example txt = “mikroElektronika”
res = strchr(txt, “E”) ‘ routine will locate the character ‘E’ in the ‘txt’
string, and return the position of the character
strcmp
Prototype sub function strcmp(dim byref s1, 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 s1 “less than” s2
= 0 s1 “equal to” s2
> 0 s1 “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.
Example txt = “mikroElektronika”
txt_sub = “mikr”
MikroElektronika
599
mikoBasic PRO for PIC32
strcpy
Prototype sub procedure strcpy(dim byref s1, s2 as string)
Description The function copies the value of the string s2 to the string s1 and appends a null character to the end
of s1.
Example txt = “mikroElektronika”
txt_sub = “mikr”
strlen
Prototype sub function strlen(dim byref s as string) as word
Description The function returns the length, in words, of the string s. The length does not include the null terminating
character.
Example txt = “mikroElektronika”
strncat
Prototype sub procedure strncat(dim byref s1, 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.
Example txt = “mikroElektronika”
txt_sub = “mikr”
txt[5] = 0
strncpy
Prototype sub procedure strncpy(dim byref s1, 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.
Example txt = “mikroElektronika”
txt_sub = “mikr”
MikroElektronika
600
mikroBasic PRO for PIC32
strspn
Prototype sub function strspn(dim byref s1, 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).
Example txt = “mikroElektronika”
txt_sub = “mikr”
strncmp
Prototype sub function strncmp(dim byref s1, s2 as string, dim len as byte) as
integer
Description The function lexicographically compares the first len characters of the strings s1 and s2 and returns
a value indicating their relationship:
Value Meaning
< 0 s1 “less than” s2
= 0 s1 “equal to” s2
> 0 s1 “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 len words).
Example txt = “mikroElektronika”
txt_sub = “mikr”
strstr
Prototype sub function strstr(dim byref s1, 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 function returns a number indicating the position of the first occurrence of s2 in s1; if no string was
found, the function returns 0xFFFF. If s2 is a null string, the function returns 0.
Example txt = “mikroElektronika”
txt_sub = “mikr”
res = strstr(txt_sub,txt)
MikroElektronika
601
mikoBasic PRO for PIC32
strcspn
Prototype sub function strcspn(dim byref s1, 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).
Example txt = “mikroElektronika”
txt_sub = “mikr”
res = strcspn(txt_sub,txt)
strpbrk
Prototype sub function strpbrk(dim byref s1, s2 as string) as word
Description The function searches s1 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 0xFFFF.
Example txt = “mikroElektronika”
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 string s for the last occurrence of the character ch. The null character
terminating s is not included in the search. The function returns an index of the last ch found in s; if no
matching character was found, the function returns 0xFFFF.
Example txt = “mikroElektronika”
ltrim
Prototype sub procedure ltrim(dim byref astring as string)
Description The procedure trims the leading spaces of the string.
Example txt = “ mikroE”
ltrim(txt) ‘ trims the leading 2 spaces of the ‘txt’ string
MikroElektronika
602
mikroBasic PRO for PIC32
rtrim
Prototype sub procedure rtrim(dim byref astring as string)
Description The procedure trims the trailing spaces of the string.
Example txt = “mikroE “
rtrim(txt) ‘ trims the trailing 2 spaces of the ‘txt’ string and adds
terminating null character to the result
strappendpre
Prototype sub procedure strappendpre(dim letter as char, dim byref s1 as string)
Description The procedure trims the trailing spaces of the string.
Example txt = “ikroE”
strappendsuf
Prototype sub procedure strappendsuf(dim byref s1 as string, dim letter as char)
Description The procedure appends character at the end of the string.
Example txt = “mikro”
length
Prototype sub function length(dim byref s as string) as word
Description The function returns length of passed string.
Example txt = “mikroE”
res = length(txt) ‘ calculates and returns the length of the ‘txt’ string
MikroElektronika
603
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.
The TimeStruct type is a structure type suitable for time and date storage.
Library Routines
- Time_dateToEpoch
- Time_epochToDate
- Time_dateDiff
Time_dateToEpoch
Prototype sub function Time_dateToEpoch(dim byref ts as TimeStruct) as longint
Description This function returns the UNIX time : number of seconds since January 1, 1970 0h00mn00s.
Parameters - ts: time and date value for calculating UNIX time.
Returns Number of seconds since January 1, 1970 0h00mn00s.
Requires Nothing.
Example dim ts1 as TimeStruct
Epoch as longint
...
‘ what is the epoch of the date in ts ?
epoch = Time_dateToEpoch(@ts1)
Notes None.
MikroElektronika
604
mikroBasic PRO for PIC32
Time_epochToDate
Prototype sub procedure Time_epochToDate(dim e as longint, dim byref ts as
TimeStruct)
Description Converts the UNIX time to time and date.
Parameters - e: UNIX time (seconds since UNIX epoch)
- ts: time and date structure for storing conversion output
Returns Nothing.
Requires Nothing.
Example dim ts2 as TimeStruct
epoch as longint
...
‘ what date is epoch 1234567890 ?
epoch = 1234567890
Time_epochToDate(epoch,ts2)
Notes None.
Time_dateDiff
Prototype sub function Time_dateDiff(dim byref t1, t2 as TimeStruct) 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)
Parameters None.
Returns Time difference in seconds as a signed long.
Requires Nothing.
Example dim ts1, ts2 as TimeStruct
diff as longint
...
‘ how many seconds between these two dates contained in ts1 and ts2
buffers?
diff = Time_dateDiff(ts1, ts2)
Notes None.
MikroElektronika
605
mikoBasic PRO for PIC32
Library Example
Demonstration of Time library routines usage for time calculations in UNIX time format.
program Time_Demo
‘*
‘* simple time structure
‘*
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
main:
ts1.ss = 0
ts1.mn = 7
ts1.hh = 17
ts1.md = 23
ts1.mo = 5
ts1.yy = 2006
‘*
‘* what is the epoch of the date in ts ?
‘*
epoch = Time_dateToEpoch(@ts1) ‘ epoch = 1148404020
‘*
‘* what date is epoch 1234567890 ?
‘*
epoch = 1234567890
Time_epochToDate(epoch, @ts2) ‘ ts2.ss = 30
‘ ts2.mn = 31
‘ ts2.hh = 23
‘ ts2.md = 13
‘ ts2.wd = 4
‘ ts2.mo = 2
‘ ts2.yy = 2009
‘*
‘* how much seconds between this two dates ?
‘*
diff = Time_dateDiff(@ts1, @ts2) ‘ diff = 86163870
end.
MikroElektronika
606
mikroBasic PRO for PIC32
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
- ldexp
- log
- log10
- modf
- pow
- sin
- sinh
- sqrt
- tan
- tanh
MikroElektronika
607
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 parameter
x must be between -1 and 1 (inclusive). The return value is in radians, between 0 and Π (inclusive).
Example res = acos(0.5) ‘ res = 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 -Π/2 and Π/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 f. The return
value is in radians, between -Π/2 and Π/2 (inclusive).
Example res = atan(1.0) ‘ res = 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 -Π and Π (inclusive).
Example res = atan2(2., 1.) ‘ res = 4.636475e-1
ceil
Prototype sub function ceil(dim x as float) as float
Description Function returns value of parameter 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
Description Function returns the cosine of f in radians. The return value is from -1 to 1.
Example res = 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-x)/2. If the value of x
is too large (if overflow occurs), the function fails.
Example res = cosh(PI/3.) ‘ res = 1.600286
eval_poly
Prototype sub function eval_poly(dim x as float, dim byref d as array[10] of float, dim
n as integer) as float
Description 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
Description 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
Description Function returns the absolute (i.e. positive) value of d.
Example res = fabs(-1.3) ‘ res = 1.3
floor
Prototype sub function floor(dim x as float) as float
Description 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 object pointed to
by eptr.
MikroElektronika
609
mikoBasic PRO for PIC32
ldexp
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.
returns x * 2n).
Example res = ldexp(2.5, 2) ‘ res = 10
log
Prototype sub function log(dim x as float) as float
Description Function returns the natural logarithm of x (i.e. loge(x)).
Example res = log(10) ‘ res = 2.302585E
log10
Prototype sub function log10(dim x as float) as float
Description Function returns the base-10 logarithm of x (i.e. log10(x)).
Example res = log10(100.) ‘ res = 2.000000
modf
Prototype sub function modf(dim val as float, dim byref iptr as float) as float
Description Returns argument val split to the fractional part (function return val) and integer part (in number iptr).
Example res = modf(6.25, iptr) ‘ res = 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.) ‘ res = 9.999984e+4
sin
Prototype sub function sin(dim arg as float) as float
Description Function returns the sine of f in radians. The return value is from -1 to 1.
Example res = sin(PI/2.) ‘ res = 1.000000
MikroElektronika
610
mikroBasic PRO for PIC32
sinh
Prototype sub function 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.
Example res = sinh(PI/2.) ‘ res = 2.301296
sqrt
Prototype sub function sqrt(dim x as float) as float
Description Function returns the non negative 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.
Example res = tan(PI/4.) ‘ res = 0.999998
tanh
Prototype sub function tanh(dim x as float) as float)
Description Function returns the hyperbolic tangent of x, defined mathematically as sinh(x)/cosh(x).
Example res = tanh(-PI/4.) ‘ res = -0.655793
MikroElektronika
611
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)
Parameters - angle_deg: input angle in degrees
Returns The function returns the sine of input parameter multiplied by 1000.
Requires Nothing.
Example 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)
Parameters - angle_deg: input angle in degrees
Returns The function returns the cosine of input parameter multiplied by 1000.
Requires Nothing.
Example 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 .mbp32)
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.
Note that the project does not include files in the same way as preprocessor does, see Add/Remove Files from
Project.
MikroElektronika
613
mikoBasic PRO for PIC32
New Project
The easiest way to create a project is by means of the New Project Wizard, drop-down menu Project › New Project or
by clicking the New Project Icon from Project Toolbar.
Step One - Select the device from the device drop-down list:
MikroElektronika
614
mikroBasic PRO for PIC32
Step Three - Specify the location where your project will be saved:
MikroElektronika
615
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:
MikroElektronika
616
mikroBasic PRO for PIC32
MikroElektronika
617
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.
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 or press Insert button on your keyboard. Each
added source file must be self-contained, i.e. it must have all necessary definitions after preprocessing.
To remove file(s) from the project, click the Remove File from Project Icon or press Delete button on your
keyboard.
Note : For inclusion of the module files, use the include clause. See File Inclusion for more information.
ANALOG
DEBUG
TEST
For example, lets make a project level define named pld_test. First of all, create a new file with the .pld 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.
#IFDEF PLD_TEST
...
#ENDIF
There are number of predefined project level defines. See predefined project level defines
MikroElektronika
619
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 project.
1. Select File › New Unit from the drop-down menu, or press Ctrl+N, or click the New File Icon from the File
Toolbar.
2. A new 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 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.
1. Select File › Open from the drop-down menu, or press Ctrl+O, or click the Open File Icon from the File
Toolbar. In Open Dialog browse to the location of the file that you want to open, select it and click the Open button.
2. The selected file is displayed in its own tab. If the selected file is already open, its current Editor tab will become
active.
Saving file
1. Make sure that the window containing the file that you want to save is the active window.
2. Select File › Save from the drop-down menu, or press Ctrl+S, or click the Save File Icon from the File
Toolbar.
MikroElektronika
620
mikroBasic PRO for PIC32
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:
MikroElektronika
621
mikoBasic PRO for PIC32
Icon Description
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.
MikroElektronika
622
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
button.
In case you need this scheme in another project, you can load it using button.
There is also a button which lets you select default configuration bit settings for the selected device.
Besides this, user can control the Interrupt mechanism by selecting either Single or Multi-Vector mode, Base Ad-
dress and SRS Priority level.
MikroElektronika
623
mikoBasic PRO for PIC32
MikroElektronika
624
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 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 from the Build Toolbar.
Progress bar will appear to inform you about the status of compiling. If there are some errors, you will be notified in the
Messages Window. If no errors are encountered, the 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:
Assembly View
After compiling the program in the mikroBasic PRO for PIC32, you can click the View Assembly icon
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
MikroElektronika
625
mikoBasic PRO for PIC32
MikroElektronika
626
mikroBasic PRO for PIC32
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 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.
Why do I still get demo limit error when I purchased and installed license key ?
If you are first time installing and registering compiler, you need to follow instructions exactly as described in registration
procedure. License is valid only for the computer from which request is made, so license requested from one computer
won’t work on another computer. You can find on our site manual and video describing in detail how to get your license.
If you previously had an older version of our compiler and have working license key for it but it doesn’t work with new
compiler, you have to repeat registration procedure from the new compiler and you will get a new license.
MikroElektronika
627
mikoBasic PRO for PIC32
I have bought license for the older version, do I 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.
I 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 I get your library sources ? I need to provide all sources with my project.
It is our company’s policy not to share our source code.
Can I use code I developed in your compilers in commercial purposes ? Are there some
limitations ?
Regarding your code, there are no limitations. Your application is your own property and you can do whatever you like
with it. If you want to include some of code we provide with our compilers or on our site, you may include them in your
project, however, you are not allowed to charge your users for these.
Your example works if I use the same MCU you did, but how to make it work for another
MCU ?
You should read your MCU’s datasheet. Different MCUs can have different pin assignments and may require different
settings. If you need help regarding this, you can find free online books on our website and recommend you starting
there. You can also ask for help on our forum.
MikroElektronika
628
mikroBasic PRO for PIC32
I have a question about your compilers which is not listed here. Where can I 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.
MikroElektronika
629
If you want to learn more about our products, please visit our website at www.mikroe.com
If you are experiencing some problems with any of our products or just need additional information, please place your ticket at
www.mikroe.com/en/support
If you have any questions, comments or business proposals, do not hesitate to contact us at office@mikroe.com
Mouser Electronics
Authorized Distributor
mikroElektronika:
MIKROE-728