Mikroc Dspic Manual v100
Mikroc Dspic Manual v100
Mikroc Dspic Manual v100
Manual
Compiler
MikroElektronika
Table of Contents
CHAPTER 1
INTRODUCTION
Introduction to mikroC PRO for dsPIC30/33 and PIC24
Features
Where to Start
Technical Support
How to Register
Who Gets the License Key
How to Get License Key
After Receving the License Key
CHAPTER 2
mikroC PRO for dsPIC30/33 and PIC24 Environment
Main Menu Options
File
File Menu Options
Edit
32
32
33
33
33
34
34
34
35
35
35
35
36
36
37
37
37
37
39
41
41
42
43
43
44
Edit Menu Options
Find Text
Replace Text
Find In Files
Go To Line
Regular expressions option
View
44
45
45
46
46
46
47
View Menu Options
Project
Project Menu Options
Build
47
49
49
50
Build Menu Options
Run
50
51
Run Menu Options
Tools
51
52
Tools Menu Options
MikroElektronika
52
53
Help Menu Options
Code Editor
Editor Settings
Auto Save
Highlighter
Spelling
Comment Style
Code Folding
Code Assistant
Parameter Assistant
Bookmarks
Go to Line
Column Select Mode
Editor Colors
Auto Correct
Auto Complete (Code Templates)
Code Explorer
Routine List
Project Manager
Project Settings
Library Manager
Managing libraries using Package Manager
Statistics
Memory Usage Windows
RAM Memory Usage
Used RAM Locations
SFR Locations
ROM Memory Usage
ROM Memory Constants
Functions
Functions Sorted By Name Chart
Functions Sorted By Size Chart
Functions Sorted By Addresses
Function Tree
Memory Summary
Messages Window
Quick Converter
Macro Editor
Image Preview
Toolbars
File Toolbar
Edit Toolbar
53
54
54
55
55
56
56
56
56
56
57
57
57
57
58
58
59
60
62
63
63
65
66
67
68
68
69
69
70
70
71
71
72
72
73
73
74
75
76
76
77
79
80
80
MikroElektronika
81
81
82
82
83
83
84
84
85
85
86
Docking Windows
Saving Layout
Auto Hide
Options
Code editor
Tools
Output settings
Integrated Tools
Active Comments Editor
ASCII Chart
EEPROM Editor
Filter Designer
Graphic Lcd Bitmap Editor
HID Terminal
Lcd Custom Character
Seven Segment Editor
UDP Terminal
USART Terminal
Active Comments
New Active Comment
Renaming Active Comment
Deleting Active Comment
Export Project
Jump To Interrupt
Regular Expressions
Introduction
Simple matches
Escape sequences
Character classes
Metacharacters
Metacharacters - Line separators
Metacharacters - Predefined classes
Metacharacters - Word boundaries
Metacharacters - Iterators
Metacharacters - Alternatives
MikroElektronika
86
87
87
88
88
88
89
91
91
92
93
93
94
95
96
97
97
98
99
99
106
107
108
109
110
110
110
110
110
111
111
112
112
112
113
Keyboard Shortcuts
CHAPTER 3
mikroC PRO for dsPIC30/33 and PIC24 Command Line Options
CHAPTER 4
mikroICD (In-Circuit Debugger)
Introduction
mikroICD Debugger Options
Debugger Options
CHAPTER 5
Software Simulator Overview
Software Simulator
Software Simulator Debug Windows
Debug Windows
Breakpoints Window
Watch Values Window
RAM Window
Stopwatch Window
EEPROM Watch Window
Code Watch Window
CHAPTER 6
mikroC PRO for dsPIC30/33 and PIC24 Specifics
113
113
114
116
116
118
118
118
120
120
121
125
125
125
125
127
127
128
129
130
130
131
132
132
132
132
134
134
135
136
137
137
138
138
GOTO Table
139
140
140
140
140
141
141
142
143
MikroElektronika
Interrupts
Function Calls from Interrupt
Disable Context Saving
Interrupt Handling
Interrupt Example
Linker Directives
Directive absolute
Directive orgall
Directive funcorg
Code Optimization
Constant folding
Constant propagation
Copy propagation
Value numbering
"Dead code" ellimination
Stack allocation
Local vars optimization
Better code generation and local optimization
144
144
145
145
145
145
146
147
147
147
148
148
149
150
150
151
151
152
152
153
153
153
154
154
154
155
155
155
156
157
157
157
157
157
157
157
157
157
158
Introduction
Proper Coding Recommendations
Asm code and SSA optimization
Debugging Notes
Warning Messages Enhancement
158
159
160
160
160
161
161
CHAPTER 7
dsPIC30/33 and PIC24 Specifics
Types Efficiency
Nested Calls Limitations
Limits of Indirect Approach Through PSV
Limits of Pointer to Function
Variable, constant and routine alignment
161
163
163
164
164
164
164
164
165
165
166
166
166
167
167
168
168
168
168
168
169
169
169
170
170
170
Comments
C comments
C++ comments
Nested comments
Tokens
Token Extraction Example
Constants
Integer Constants
Long and Unsigned Suffixes
Decimal
Hexadecimal
171
175
175
178
179
179
179
180
180
180
180
181
181
182
182
182
182
183
MikroElektronika
String Constants
Line Continuation with Backslash
Enumeration Constants
Pointer Constants
Constant Expressions
Keywords
Identifiers
Case Sensitivity
Uniqueness and Scope
Identifier Examples
Punctuators
Brackets
Parentheses
Braces
Comma
Semicolon
Colon
Asterisk (Pointer Declaration)
Equal Sign
Pound Sign (Preprocessor Directive)
Concepts
Objects
Objects and Declarations
Lvalues
Rvalues
Name Spaces
Duration
Static Duration
Local Duration
Types
Type Categories
Fundamental Types
Arithmetic Types
Integral Types
Floating-point Types
MikroElektronika
183
183
184
184
184
185
186
186
187
187
188
189
190
190
191
191
191
191
192
192
192
193
193
193
194
194
195
195
195
196
196
196
196
196
197
198
198
198
199
199
200
200
200
201
Void Type
Void Functions
Generic Pointers
Derived Types
Arrays
Array Declaration
Array Initialization
Arrays in Expressions
Multi-dimensional Arrays
Pointers
Pointer Declarations
Null Pointers
Assign an address to a Function Pointer
Function Pointers
Assign an address to a Function Pointer
Pointer Arithmetic
Arrays and Pointers
Assignment and Comparison
Pointer Addition
Pointer Subtraction
Structures
Structure Declaration and Initialization
Incomplete Declarations
Untagged Structures and Typedefs
Anonymous Structures
201
201
202
202
203
203
203
203
204
204
204
205
205
206
206
207
207
209
209
210
210
211
212
213
213
213
214
215
215
216
Assignment
Size of Structure
Structures and Functions
216
216
216
217
Unions
Union Declaration
Size of Union
Union Member Access
Anonymous Unions
Anonymous Union Member Access
Bit Fields
Bit Fields Declaration
Bit Fields Access
218
218
219
219
219
219
220
220
221
221
222
MikroElektronika
Linkage
Linkage Rules
Internal Linkage Rules
222
223
223
224
224
225
225
226
226
227
227
Storage Classes
227
Auto
Register
Static
Extern
228
228
228
228
Type Qualifiers
Qualifier const
Qualifier volatile
Typedef Specifier
asm Declaration
Accessing variables
Asm code and SSA optimization
Initialization
Automatic Initialization
Functions
Function Declaration
Function Prototypes
Function Definition
Functions reentrancy
Relational Operators
Relational Operators Overview
Relational Operators in Expressions
Bitwise Operators
Bitwise Operators Overview
Logical Operations on Bit Level
MikroElektronika
229
229
229
229
230
230
231
232
232
233
233
234
234
235
235
235
236
237
238
239
240
240
241
241
241
242
242
242
10
Logical Operators
Logical Operators Overview
Logical Operations
Logical Expressions and Side Effects
Logical vs. Bitwise
Conditional Operator ? :
Conditional Operator Rules
Assignment Operators
Simple Assignment Operator
Compound Assignment Operators
Assignment Rules
Unary Operators
Unary Arithmetic Operators
Unary Logical Operator
Unary Bitwise Operator
Address and Indirection Operator
Sizeof Operator
Sizeof Applied to Expression
Sizeof Applied to Type
Expressions
Comma Expressions
Statements
Labeled Statements
Expression Statements
Selection Statements
If Statement
Nested If statements
Switch Statement
Nested switch
Do Statement
For Statement
Jump Statements
Break and Continue Statements
Break Statement
Continue Statement
Goto Statement
Return Statement
Compound Statements (Blocks)
Preprocessor
11
243
243
244
244
244
244
245
245
245
246
246
246
246
247
247
248
248
248
249
249
249
250
250
251
251
252
252
252
252
253
254
254
254
254
255
256
256
256
256
257
257
258
258
MikroElektronika
Macros
Defining Macros and Macro Expansions
Macros with Parameters
Undefining Macros
File Inclusion
Explicit Path
Preprocessor Operators
Operator #
Operator ##
Conditional Compilation
Directives #if, #elif, #else, and #endif
Directives #ifdef and #ifndef
CHAPTER 9
mikroC PRO for dsPIC30/33 and PIC24 Libraries
Hardware Libraries
Digital Signal Processing Libraries
Standard ANSI C Libraries
Miscellaneous Libraries
Hardware Libraries
ADC Library
Library Routines
ADCx_Init
ADCx_Init_Advanced
ADCx_Get_Sample
ADCx_Read
ADC_Set_Active
Library Example
CAN Library
Library Routines
CANxSetOperationMode
CANxGetOperationMode
CANxInitialize
CANxSetBaudRate
CANxSetMask
CANxSetFilter
CANxRead
CANxWrite
CAN Constants
CAN_OP_MODE Constants
CAN_CONFIG_FLAGS Constants
CAN_TX_MSG_FLAGS Constants
CAN_RX_MSG_FLAGS Constants
MikroElektronika
258
259
259
259
260
261
261
262
263
263
263
264
264
265
266
266
267
267
268
268
269
269
270
270
271
272
272
273
273
275
275
276
276
277
278
279
280
281
282
283
283
283
284
285
12
CANSPI Library
Library Dependency Tree
External dependencies of CANSPI Library
Library Routines
CANSPISetOperationMode
CANSPIGetOperationMode
CANSPIInitialize
CANSPISetBaudRate
CANSPISetMask
CANSPISetFilter
CANSPIRead
CANSPIWrite
CANSPI Constants
CANSPI_OP_MODE Constants
CANSPI_TX_MSG_FLAGS Constants
CANSPI_RX_MSG_FLAGS Constants
CANSPI_MASK Constants
CANSPI_FILTER Constants
Library Example
HW Connection
13
285
286
286
289
290
290
290
291
291
292
292
294
295
296
297
298
298
298
300
300
301
301
302
305
306
306
307
308
309
310
310
310
311
311
311
312
312
312
313
313
314
315
315
316
316
316
317
MikroElektronika
ECAN Library
Library Routines
ECANxDmaChannelInit
ECANxSetOperationMode
ECANxGetOperationMode
ECANxInitialize
ECANxSelectTxBuffers
ECANxFilterDisable
ECANxFilterEnable
ECANxSetBufferSize
ECANxSetBaudRate
ECANxSetMask
ECANxSetFilter
ECANxRead
ECANxWrite
ECAN Constants
ECAN_OP_MODE Constants
ECAN_CONFIG_FLAGS Constants
ECAN_TX_MSG_FLAGS Constants
ECAN_RX_MSG_FLAGS Constants
ECAN_MASK Constants
ECAN_FILTER Constants
ECAN_RX_BUFFER Constants
Library Example
HW Connection
EEPROM Library
Library Routines
EEPROM_Erase
EEPROM_Erase_Block
EEPROM_Read
EEPROM_Write
EEPROM_Write_Block
Library Example
317
318
318
319
319
321
323
324
324
325
325
326
327
328
328
329
329
330
331
332
333
334
335
335
335
336
336
337
337
338
339
343
343
343
344
344
344
345
345
345
347
347
348
349
350
351
351
14
15
351
352
352
352
353
353
354
354
355
355
356
356
357
357
358
358
359
359
360
360
361
362
362
362
363
363
363
363
363
364
364
365
365
366
367
368
368
369
369
369
370
370
371
371
372
373
373
MikroElektronika
IC Library
Library Routines
I2Cx_Init
I2Cx_Start
I2Cx_Restart
I2Cx_Is_Idle
I2Cx_Read
I2Cx_Write
I2Cx_Stop
Library Example
HW Connection
Keypad Library
External dependencies of Keypad Library
Library Routines
Keypad_Init
Keypad_Key_Press
Keypad_Key_Click
Library Example
HW Connection
Lcd Library
Library Dependency Tree
Keypad_Key_Click
MikroElektronika
374
375
377
377
377
378
378
379
379
379
380
380
381
381
382
382
383
383
384
385
385
386
386
387
389
390
390
390
391
391
392
392
393
393
394
394
395
395
395
395
396
396
397
398
399
399
399
16
17
399
400
401
401
401
402
402
402
403
405
405
406
406
407
407
408
408
409
410
412
413
413
413
414
414
414
415
416
416
417
417
418
419
420
421
421
422
422
422
423
423
424
425
425
426
427
431
MikroElektronika
432
432
432
433
433
434
436
437
Library Routines
Unlock_IOLOCK
Lock_IOLOCK
PPS_Mapping
Direction Parameters
Input Functions
Output Functions
437
437
437
438
438
438
439
PS/2 Library
External dependencies of PS/2 Library
Library Routines
Ps2_Config
Ps2_Key_Read
Special Function Keys
Library Example
HW Connection
PWM Library
Library Routines
MikroElektronika
441
441
441
441
442
443
444
444
444
445
445
446
446
447
447
448
448
448
449
449
451
452
452
452
453
453
454
455
456
456
456
18
RS-485 Library
Library Dependency Tree
External dependencies of RS-485 Library
Library Routines
RS485Master_Init
RS485Master_Receive
RS485Master_Send
RS485Slave_Init
RS485Slave_Receive
RS485Slave_Send
Library Example
HW Connection
Message format and CRC calculations
Software IC Library
External dependencies of Software IC Library
Library Routines
Soft_I2C_Init
Soft_I2C_Start
Soft_I2C_Read
Soft_I2C_Write
Soft_I2C_Stop
Soft_I2C_Break
Library Example
19
457
457
458
458
458
460
460
460
461
462
462
463
464
464
465
465
465
465
466
466
467
468
468
469
472
473
474
474
474
475
475
476
476
477
478
479
481
481
481
482
483
483
483
485
485
485
MikroElektronika
Sound Library
Library Routines
Sound_Init
Sound_Play
HW Connection
SPI Library
Library Routines
SPIx_Init
SPIx_Init_Advanced
SPIx_Read
SPIx_Write
SPI_Set_Active
Library Example
HW Connection
486
486
487
488
489
489
489
489
491
492
492
493
494
496
496
497
497
498
499
499
500
501
501
502
503
504
505
505
506
506
506
507
507
507
508
509
510
510
510
511
511
512
512
513
514
514
515
20
21
522
523
523
524
525
526
528
529
530
530
531
531
532
532
532
533
533
534
534
535
535
536
536
537
537
538
539
540
540
540
541
541
541
541
542
543
543
543
544
544
545
545
546
546
547
547
548
MikroElektronika
548
549
549
550
551
552
552
553
553
554
556
557
557
557
557
558
558
559
559
559
560
560
561
561
563
563
563
563
564
565
565
565
566
566
567
567
570
570
570
571
572
573
573
574
574
574
575
22
23
575
576
577
577
578
578
579
579
579
580
580
581
581
581
582
582
582
583
583
583
584
584
584
585
585
585
586
586
586
591
592
592
593
594
595
596
597
597
597
598
598
599
600
600
601
601
602
MikroElektronika
TFT Library
External dependencies of TFT Library
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_Dot
TFT_Set_Pen
TFT_Set_Brush
TFT_Line
TFT_H_Line
TFT_V_Line
TFT_Rectangle_Round_Edges
TFT_Circle
TFT_Image
TFT_Partial_Image
TFT_Image_Jpeg
MikroElektronika
602
602
603
603
604
604
605
605
605
606
606
606
607
607
607
608
608
608
609
609
609
610
610
614
615
615
616
617
618
618
618
619
620
621
621
622
623
624
625
627
628
628
629
629
629
630
630
24
UART Library
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
Library Example
HW Connection
USB Library
USB HID Class
Library Routines
HID_Enable
25
631
631
632
633
633
633
633
634
634
635
636
636
637
637
638
638
643
643
643
643
644
644
645
646
646
647
647
648
648
649
649
650
651
653
654
655
656
657
658
659
660
661
662
662
662
663
MikroElektronika
DSP Libraries
Digital Signal Processing Libraries
FFT Library
Library Dependency Tree
FFT
Twiddle Factors:
TwiddleCoeff_64
TwiddleCoeff_128
TwiddleCoeff_256
TwiddleCoeff_512
Vectors Library
Library Routines
Vector_Set
Vector_Power
Vector_Subtract
Vector_Scale
Vector_Negate
Vector_Multiply
Vector_Min
Vector_Max
Vector_Dot
Vector_Correlate
Vector_Convolve
Vector_Add
Matrices Library
Library Routines
Matrix_Transpose
MikroElektronika
663
664
664
665
665
666
666
667
668
668
669
669
670
670
670
671
671
671
672
672
672
673
673
673
674
674
676
676
676
677
677
677
678
678
679
679
680
680
681
681
682
683
684
685
685
685
26
27
686
686
687
688
689
689
689
690
690
690
690
691
691
691
691
692
692
692
692
693
693
693
694
694
694
694
695
695
695
695
695
696
696
696
696
697
697
697
697
698
698
698
699
699
699
699
MikroElektronika
700
700
700
700
701
701
701
701
702
702
702
702
703
704
Library Functions
memchr
memcmp
memcpy
memmove
memset
strcat
strchr
strcmp
strcpy
strlen
strncat
strncpy
strspn
strncmp
strstr
strcspn
strpbrk
strrchr
strtok
704
704
705
705
705
706
706
706
707
707
707
708
708
708
709
709
710
710
710
711
Miscellaneous Libraries
Button Library
712
712
Library Routines
strrchr
712
712
Conversions Library
Library Dependency Tree
Library Routines
ByteToStr
ShortToStr
WordToStr
IntToStr
LongToStr
MikroElektronika
714
714
714
715
715
716
716
717
28
PrintOut Library
Library Dependency Tree
Library Routines
PrintOut
Setjmp Library
Library Routines
Setjmp
Longjmp
Library Example
Sprint Library
Library Dependency Tree
Functions
sprintf
sprintl
sprinti
Library Example
Time Library
Library Routines
Time_dateToEpoch
Time_epochToDate
Time_dateDiff
Library Example
Trigonometry Library
Library Routines
sinE3
cosE3
CHAPTER 10
Tutorials
29
717
718
719
719
720
720
721
721
722
722
723
723
724
724
725
725
726
726
727
727
727
727
731
731
731
732
732
734
734
734
734
736
736
737
738
738
738
739
740
741
742
742
742
743
744
744
MikroElektronika
744
Projects
744
New Project
745
New Project
New Project Wizard Steps
Customizing Projects
745
748
748
752
752
752
753
754
Source Files
Managing Source Files
Creating new source file
Opening an existing file
Printing an open file
Saving file
Saving file under a different name
Closing file
Search Paths
Paths for Source Files (.c)
Paths for Header Files (.h)
Edit Project
Source Files
Managing Source Files
Creating new source file
Opening an existing file
Printing an open file
Saving file
Saving file under a different name
Closing file
Search Paths
Paths for Source Files (.c)
Paths for Header Files (.h)
755
756
756
756
756
756
756
757
757
757
758
758
759
760
760
760
760
760
760
761
761
761
762
762
763
764
764
764
765
766
766
766
773
30
778
31
MikroElektronika
CHAPTER 1
INTRODUCTION
The mikroC PRO for dsPIC30/33 and PIC24 is a powerful, feature-rich development tool for dsPIC30/33 and PIC24
microcontrollers. It is designed to provide the programmer with the easiest possible solution to developing applications
for embedded systems, without compromising performance or control.
MikroElektronika
32
Features
mikroC PRO for dsPIC30/33 and PIC24 allows you to quickly develop and deploy complex applications:
- Write your source code using the built-in Code Editor (Code and Parameter Assistants, Code Folding,
Syntax Highlighting, Auto Correct, Code Templates, and more.)
- Use included mikroC PRO for dsPIC30/33 and PIC24 libraries to dramatically speed up the development:
data acquisition, memory, displays, conversions, communication etc.
- Monitor your program structure, variables, and functions in the Code Explorer.
- Generate commented, human-readable assembly, and standard HEX compatible with all programmers.
- Use the integrated 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.
- Generate COFF(Common Object File Format) file for software and hardware debugging under Microchips
MPLAB software.
- 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.
- mikroC PRO for dsPIC30/33 and PIC24 provides plenty of examples to expand, develop, and use as
building bricks in your projects. Copy them entirely if you deem fit thats why we included them
with the compiler.
Where to Start
- In case that youre a beginner in programming dsPIC30/33 and PIC24 microcontrollers, read carefully the
dsPIC Specifics chapter. It might give you some useful pointers on dsPIC30/33 and PIC24 constraints,
code portability, and good programming practices.
- If you are experienced in C programming, you will probably want to consult mikroC PRO for dsPIC30/33
and PIC24 Specifics first. For language issues, you can always refer to the comprehensive Language
Reference. A complete list of included libraries is available at mikroC PRO for dsPIC30/33 and
PIC24 Libraries.
- If you are not very experienced in C programming, dont panic! mikroC PRO for dsPIC30/33 and PIC24
provides plenty of examples making it easy for you to go quickly. We suggest that you first consult Projects
and Source Files, and then start browsing the examples that youre the most interested in.
Copyright (c) 2002-2010 mikroElektronika. All rights reserved.
What do you think about this topic ? Send us feedback!
33
MikroElektronika
Compiler Changes
Fixed :
- Optimization issues in specific cases when destination variable is in Rx space.
- Alignment not set for the first variable which is the first in block of initializers.
IDE Changes
Fixed :
- Error in Code Explorer in case void interrup is defined (without brackets).
- Compiler version is not visible in caption if no projects are open.
- Parameter assistant ignores commas when switching to another parameter.
- Occasional lost of configuration flags when swithing between projets.
- Improper display of RAM memory usage in statistics.
Improved :
- Communication to programmer concerning supported chips.
- License Key Request form.
MikroElektronika
34
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.
35
MikroElektronika
GENERAL PROVISIONS
This statement may only be modified in writing signed by you and an authorised officer of mikroElektronika Associates.
If any provision of this statement is found void or unenforceable, the remainder will remain valid and enforceable
according to its terms. If any remedy provided is determined to have failed for its essential purpose, all limitations of
liability and exclusions of damages set forth in the Limited Warranty shall remain in effect.
This statement gives you specific legal rights; you may have others, which vary, from country to country. mikroElektronika
Associates reserves all rights not specifically granted in this statement.
mikroElektronika
Visegradska 1A,
11000 Belgrade,
Europe.
Phone: + 381 11 36 28 830
Fax: +381 11 36 28 831
Web: www.mikroe.com
E-mail: office@mikroe.com
MikroElektronika
36
Technical Support
The latest software can be downloaded free of charge via Internet (you might want to bookmark the page so you could
check news, patches, and upgrades later on): www.mikroe.com/en/compilers/mikroC PRO/dspic/download.htm .
In case you encounter any problem, you are welcome to our support forums at www.mikroe.com/forum/. Here, you may
also find helpful information, hardware tips, and practical code snippets. Your comments and suggestions on future
development of the mikroC PRO for dsPIC30/33 and PIC24 are always appreciated feel free to drop a note or two
on our Wishlist.
In our Knowledge Base www.mikroe.com/en/kb/ you can find the answers to Frequently Asked Questions and solutions
to known problems. If you can not find the solution to your problem in Knowledge Base then report it to Support Desk
www.mikroe.com/en/support/. In this way, we can record and track down bugs more efficiently, which is in our mutual
interest. We respond to every bug report and question in a suitable manner, ever improving our technical support.
How to Register
The latest version of the mikroC PRO for dsPIC30/33 and PIC24 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 mikroC PRO for dsPIC30/33 and PIC24, 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 :
37
MikroElektronika
If you choose I work online registering method, following page will be opened in your default browser :
MikroElektronika
38
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.
39
MikroElektronika
MikroElektronika
40
CHAPTER 2
mikroC PRO for dsPIC30/33 and
PIC24 Environment
41
MikroElektronika
MikroElektronika
42
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.
Open source file for editing or image file for viewing.
Reopen recently used file.
Save changes for active editor.
Save the active source file with the different name or change the file type.
Close active source file.
Close all opened files.
Print Preview.
Print.
Exit IDE.
43
MikroElektronika
Edit
Edit Menu Options
The Edit Menu contains commands for editing the contents of the current document.
Edit
Description
Undo last change.
Redo last change.
Cut selected text to clipboard.
Copy selected text to clipboard.
Paste text from clipboard.
Delete selected text.
Select all text in active editor.
Find text in active editor.
Find next occurence of text in active editor.
Find previous occurence of text in active editor.
Replace text in active editor.
Find text in current file, in all opened files, or in files from desired folder.
Go to line to the desired line in active editor.
Advanced Code Editor options
MikroElektronika
44
Description
Comment selected code or put single line comment if there is no selection.
Uncomment selected code or remove single line comment if there is no selection.
Indent selected code.
Outdent selected code.
Changes selected text case to lowercase.
Changes selected text case to uppercase.
Changes selected text case to titlercase.
Find Text
Dialog box for searching the document for the specified text. The search is performed in the direction specified. If the
string is 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.
45
MikroElektronika
Go To Line
Dialog box that allows the user to specify the line number at which the cursor should be positioned.
MikroElektronika
46
View
View Menu Options
View Menu contains commands for controlling the on-screen display of the current project.
47
MikroElektronika
Description
Show/Hide Software Simulator / mikroICD (In-Circuit Debugger) Debug Windows.
Show/Hide Toolbars.
Show/Hide Bookmarks window.
Show/Hide Code Explorer window.
Show/Hide Library Manager window.
Show/Hide Macro Editor window.
Show/Hide Messages window.
Show/Hide Project Manager window.
Show/Hide Project Settings window.
Show/Hide Routine List in active editor.
Show/Hide Quick Converter window.
Show/Hide View Image Preview window.
View Assembly.
View Listing.
View Statistics.
Show Window List window.
The Tools toolbar can easily be customized by adding new tools in Options(F12) window.
Related topics: Keyboard shortcuts, Integrated Tools
MikroElektronika
48
Project
Project Menu Options
Project Menu allows user to easily manipulate current project.
Project
Description
Open New Project Wizard
Open existing project.
Open project group.
Open recently used project or project group.
Save current project.
Save active project file with the different name.
Close active project.
Close project group.
Add file to project.
Remove file from project.
Edit search paths.
Edit project settings
Clean Project Folder
Export Project.
Related topics: Keyboard shortcuts, Project Toolbar, Creating New Project, Project Manager, Project Settings
49
MikroElektronika
Build
Build Menu Options
Build Menu allows user to easily manage building and compiling process.
Build
Description
Build active project.
Rebuild all sources in acrive project.
Build all projects.
Stop building of all projects.
Build and program active project.
Related topics: Keyboard shortcuts, Project Toolbar, Creating New Project, Project Manager, Project Settings
MikroElektronika
50
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.
Jump to interrupt in current project.
Toggle Breakpoint.
Clear Breakpoints.
Toggle between source and disassembly.
51
MikroElektronika
Tools
Tools Menu Options
Tools Menu contain a number of applications designed to ease the use of compiler and included library routines.
Tools
Description
Run mikroElektronika Programmer.
Run Package Manager.
Show/Hide Active Comment Editor window.
Run ASCII Chart
Run EEPROM Editor
Generate HTML code suitable for publishing source code on the web.
Run Filter Designer Tool.
Run Glcd bitmap editor
Run HID Terminal
Run Lcd custom character
Run Seven Segment Editor
Run UDP communication terminal
Run USART Terminal
Open Options window
MikroElektronika
52
Help
Help Menu Options
Help
Description
pen Help File.
pen Code Migration Document.
Check if new compiler version is available.
Open mikroElektronika Support Forums in a default browser.
Open mikroElektronika Web Page in a default browser.
Information on how to register
Open About window.
53
MikroElektronika
- The Code Editor features adjustable Syntax Highlighting, Code Folding, Code Assistant, Parameters Assistant, Spell
Checker, Auto Correct for common typos and Code Templates (Auto Complete).
- The Code Explorer is at your disposal for easier project management.
- The Project Manager alows multiple project management
- General project settings can be made in the Project Settings window
- Library manager enables simple handling libraries being used in a project
- The Messages Window displays all messages during compiling and linking.
- The source-level Software Simulator lets you debug executable logic step-by-step by watching the program flow.
- The New Project Wizard is a fast, reliable, and easy way to create a project.
- Help files are syntax and context sensitive.
- Like in any modern Windows application, you may customize the layout of mikroC PRO for dsPIC30/33 and PIC24
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
54
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
55
MikroElektronika
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
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
from
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 (
code subsections.
MikroElektronika
and
56
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.
57
MikroElektronika
Editor Colors
MikroElektronika
58
Auto Correct
Auto Correct option facilitate 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 :
59
MikroElektronika
MikroElektronika
60
You can add your own templates to the list by entering the desired keyword, description and code of your template in
appropriate boxes.
Autocomplete macros can retreive system and project information :
- %DATE% - current system date
- %TIME% - current system time
- %DEVICE% - device(MCU) name as specified in project settings
- %DEVICE_CLOCK% - clock as specified in project settings
- %COMPILER% - current compiler version
These macros can be used in template code, see template ptemplate provided with mikroC PRO for dsPIC30/33 and
PIC24 installation.
61
MikroElektronika
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 first error and it's location in code.
Icon
Description
Expand/Collapse all nodes in tree.
Locate declaration in code.
MikroElektronika
62
Project Manager
Project Manager is IDE feature which allows 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.
63
MikroElektronika
Description
Save project Group.
Open project group.
Close the active project.
Close project group.
Add project to the project group.
Remove project from the project group.
Add file to the active project.
Remove selected file from the project.
Build the active project.
Run mikroElektronikas Flash programmer.
For details about adding and removing files from project see Add/Remove Files from Project.
Related topics: Project Settings, Project Menu Options, File Menu Options, Project Toolbar, Build Toolbar, Add/Remove
Files from Project
MikroElektronika
64
Project Settings
Following options are available in the Project Settings :
- Device - select the appropriate device from the device drop-down list.
- MCU Clock - enter the clock frequency value.
- Build/Debugger Type - choose debugger type.
65
MikroElektronika
Library Manager
Library Manager enables simple handling libraries being used in a project. Library Manager window lists all libraries
(extension .mcl) 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
In case none library is needed in a project, press the button Clear All
project.
Only the selected libraries will be linked.
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.
Include all available libraries in current project.
No libraries from the list will be included in current project.
Restore library to the state just before last project saving.
MikroElektronika
66
From the Library Manager, user can also uninstall the desired package by right clicking the the appropriate node, and
from the drop-down menu choose Uninstall package :
67
MikroElektronika
Related topics: mikroC PRO for PIC Libraries, Creating New Library
Statistics
After successful compilation, you can review statistics of your code. Click the Statistics Icon
MikroElektronika
68
69
MikroElektronika
MikroElektronika
70
Functions
Sorts and displays functions in various ways.
71
MikroElektronika
MikroElektronika
72
Function Tree
Displays Function Tree with the relevant data for each function.
73
MikroElektronika
MikroElektronika
74
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 wont 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.
75
MikroElektronika
Quick Converter
Quick Converter enables 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
76
Description
Starts recording keystrokes for later playback.
Stops capturing keystrokes that was started when the Start Recording command was selected.
Allows a macro that has been recorded to be replayed.
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 mikroC PRO for dsPIC30/33 and PIC24 provides this possibility through a Image Preview Window.
To add a image to the Image Preview Window, right click the Image Files node in the Project Manager :
77
MikroElektronika
Next, right click the added file, and choose Set As Preview Image :
MikroElektronika
78
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 mikroC PRO for dsPIC30/33 and PIC24 Help :
- File Toolbar
- Edit Toolbar
- Advanced Edit Toolbar
- Find Toolbar
- Project Toolbar
- Build Toolbar
- Debug Toolbar
- Styles Toolbar
- Tools Toolbar
- View Toolbar
- Layout Toolbar
- Help Toolbar
79
MikroElektronika
Description
Opens a new editor window.
Open source file for editing or image file for viewing.
Save changes for active window.
Save changes in all opened windows.
Print Preview.
Print.
Edit Toolbar
Description
Undo last change.
Redo last change.
Cut selected text to clipboard.
Copy selected text to clipboard.
Paste text from clipboard.
MikroElektronika
80
Description
Comment selected code or put single line comment if there is no selection
Uncomment selected code or remove single line comment if there is no selection.
Select text from starting delimiter to ending delimiter.
Go to ending delimiter.
Go to line.
Indent selected code lines.
Outdent selected code lines.
Generate HTML code suitable for publishing current source code on the web.
Find/Replace Toolbar
Description
Find text in current editor.
Find next occurence.
Find previous occurence.
Replace text.
Find text in files.
81
MikroElektronika
Description
New project.
Open Project
Save Project
Edit project settings.
Close current project.
Clean project folder.
Add File To Project
Remove File From Project
Build Toolbar
Description
Build current project.
Build all opened projects.
Build and program active project.
Start programmer and load current HEX file.
MikroElektronika
82
Description
Start Software Simulator or mikroICD (In-Circuit Debugger).
Run/Pause Debugger.
Stop Debugger.
Step Into.
Step Over.
Step Out.
Run To Cursor.
Toggle Breakpoint.
View Breakpoints Window
Clear Breakpoints.
View Watch Window
View Stopwatch Window
Styles Toolbar
Styles toolbar allows you to easily change colors of your workspace.
83
MikroElektronika
Description
Run USART Terminal
EEPROM
ASCII Chart
Seven Segment Editor.
Open Active Comment editor.
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
Open assembly code in editor.
Open listing file in editor.
View statistics for current project.
MikroElektronika
84
Help Toolbar
Description
Open Help file.
How To Register.
85
MikroElektronika
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
86
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.
- Click the window you want to keep visible to give it focus.
- Click the Pushpin Icon
87
MikroElektronika
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 mikroC PRO for dsPIC30/33 and PIC24 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
88
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 mikroC PRO for dsPIC30/33 and PIC24 specifics).
Build all files as library enables user to use compiled library (*.mcl) 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.
89
MikroElektronika
MikroElektronika
90
Integrated Tools
Active Comments Editor
Active Comments Editor is a tool, particularly useful when working with Lcd display. You can launch it from the dropdown menu Tools Active Comments Editor or by clicking the Active Comment Editor Icon
91
MikroElektronika
MikroElektronika
92
Filter Designer
The Filter designer is a tool for designing FIR and IIR filters. It has an user-friendly visual interface for setting the filter
parameters. Filter designer output is the mikroC PRO for dsPIC30/33 and PIC24 compatible code. You can launch it
from the drop-down menu Tools Filter Designer.
93
MikroElektronika
MikroElektronika
94
95
MikroElektronika
MikroElektronika
96
UDP Terminal
The mikroC PRO for dsPIC30/33 and PIC24 includes the UDP Terminal. You can launch it from the drop-down menu
Tools UDP Terminal.
97
MikroElektronika
from
Tools toolbar.
MikroElektronika
98
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
99
MikroElektronika
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.
MikroElektronika
100
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 :
101
MikroElektronika
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
MikroElektronika
or
button.
102
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 :
103
MikroElektronika
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
104
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:
105
MikroElektronika
If you click No, comment will be removed from the source code.
MikroElektronika
106
107
MikroElektronika
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. 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
108
Jump To Interrupt
Lets you choose which interrupt you want to jump to.
Requirement: Interrupt routine is included in project.
You can call Jump To Interrupt by selecting Run Jump To Interrupt from the drop-down menu, or by clicking the Jump
To Interrupt Icon
By checking the Only Used box, you can display only the used breakpoints.
109
MikroElektronika
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 :
unsigned matches string 'unsigned'
\^unsigned matches string '^unsigned'
Escape sequences
Characters may be specified using a escape sequences: "\n" matches a newline, "\t" a tab, etc. More generally, \
xnn, where nn is a string of hexadecimal digits, matches the character whose ASCII value is nn.
If you need wide (Unicode) character code, you can use '\x{nnnn}', where 'nnnn' - one or more hexadecimal
digits.
\xnn - char with hex code nn
\x{nnnn)- char with hex code nnnn (one byte for plain text and two bytes for Unicode)
\t - tab (HT/TAB), same as \x09
\n - newline (NL), same as \x0a
\r - car.return (CR), same as \x0d
\f - form feed (FF), same as \x0c
\a - alarm (bell) (BEL), same as \x07
\e - escape (ESC) , same as \x1b
Examples:
unsigned\x20int matches 'unsigned int' (note space in the middle)
\tunsigned matches 'unsigned' (predecessed by tab)
Character classes
You can specify a character class, by enclosing a list of characters in [], which will match any of the characters from the
list. If the first character after the [ is ^, the class matches any character not in the list.
MikroElektronika
110
Metacharacters
Metacharacters are special characters which are the essence of regular expressions. There are different types of
metacharacters, described below.
111
MikroElektronika
routi\de - matches strings like 'routi1e', 'routi6e' and so on, but not 'routine', 'routime' and
Metacharacters - Iterators
Any item of a regular expression may be followed by another type of metacharacters - iterators. Using this
metacharacters,you can specify number of occurences of previous character, metacharacter or subexpression.
* - zero or more (greedy), similar to {0,}
+ - one or more (greedy), similar to {1,}
? - zero or one (greedy), similar to {0,1}
{n} - exactly n times (greedy)
{n,} - at least n times (greedy)
{n,m} - at least n but not more than m times (greedy)
*? - zero or more (non-greedy), similar to {0,}?
+? - one or more (non-greedy), similar to {1,}?
?? - zero or one (non-greedy), similar to {0,1}?
{n}? - exactly n times (non-greedy)
{n,}? - at least n times (non-greedy)
{n,m}? - at least n but not more than m times (non-greedy)
So, digits in curly brackets of the form, {n,m}, specify the minimum number of times to match the item n and the
maximum m. The form {n} is equivalent to {n,n} and matches exactly n times. The form {n,} matches n or more
times. There is no limit to the size of n or m, but large numbers will chew up more memory and slow down execution.
If a curly bracket occurs in any other context, it is treated as a regular character.
MikroElektronika
112
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:
rou(tine|te) - matches strings 'routine' or 'route'.
Metacharacters - Subexpressions
The bracketing construct ( ... ) may also be used for define regular subexpressions. Subexpressions are numbered
based on the left to right order of their opening parenthesis. First subexpression has number 1
Examples:
(int){8,10} matches strings which contain 8, 9 or 10 instances of the int
routi([0-9]|a+)e matches routi0e, routi1e , routine, routinne, routinnne etc.
Metacharacters - Backreferences
Metacharacters \1 through \9 are interpreted as backreferences. \ matches previously matched subexpression #.
Examples:
(.)\1+ matches aaaa and cc.
(.+)\1+ matches abab and 123123
([]?)(\d+)\1 matches 13 (in double quotes), or 4 (in single quotes) or 77 (without quotes) etc
113
MikroElektronika
Keyboard Shortcuts
Below is a complete list of keyboard shortcuts available in mikroC PRO for dsPIC30/33 and PIC24 IDE.
IDE Shortcuts
F1
Help
Ctrl+Space
Code Assistant
Ctrl+N
New Unit
Ctrl+Shift+Space
Parameters Assistant
Ctrl+O
Open
Ctrl+D
Find Declaration
Ctrl+Shift+O
Open Project
Ctrl+E
Incremental Search
Ctrl+Shift+N
New Project
Ctrl+L
Routine List
Ctrl+K
Close Project
Ctrl+G
Goto Line
Ctrl+F4
Close unit
Ctrl+J
Ctrl+Shift+E
Edit Project
Ctrl+Shift+.
Comment Code
Ctrl+F9
Build
Ctrl+Shift+,
Uncomment Code
Shift+F9
Build All
Ctrl+number
Goto Bookmark
Ctrl+F11
Ctrl+Shift+number
Set Bookmark
Shift+F4
View Breakpoints
Ctrl+Shift+I
Indent Selection
Ctrl+Shift+F5
Clear Breakpoints
Ctrl+Shift+U
Unindent Selection
F11
Start mE Programmer
TAB
Indent Selection
Ctrl+Shift+F11
Project Manager
Shift+TAB
Unindent Selection
F12
Options
Alt+Select
Select Columns
Alt + X
Ctrl+Alt+Select
Select Columns
F3
Ctrl+Alt+L
Shift+F3
Find Previous
Ctrl+Alt+U
Alt+F3
Ctrl+Alt+T
Convert to Titlecase
Ctrl+A
Select All
Ctrl+T
USART Terminal
Ctrl+C
Copy
Ctrl+Q
Quick Converter
Ctrl+F
Find
Ctrl+R
Replace
Ctrl+P
F2
Jump To Interrupt
Ctrl+S
Save Unit
F4
Run to Cursor
Ctrl+Shift+S
Save All
F5
Toggle Breakpoint
Ctrl+V
Paste
F6
Run/Pause Debugger
Ctrl+X
Cut
F7
Step Into
Ctrl+Y
F8
Step Over
Ctrl+Z
Undo
F9
Start Debugger
Ctrl+Shift+Z
Redo
Ctrl+F2
Stop Debugger
MikroElektronika
114
Ctrl+F8
Step Out
Alt+D
Disassembly View
Shift+F5
Ctrl+Shift+A
115
MikroElektronika
CHAPTER 3
mikroC PRO for dsPIC30/33 and
PIC24 Command Line Options
Usage: mikroCdsPIC.exe [-<opts> [-<opts>]] [<infile> [-<opts>]] [-<opts>]]
Infile can be of *.c, *.mcl and *.pld type.
The following parameters are valid :
-P <devicename> : MCU for which compilation will be done.
-FO <oscillator> : Set oscillator [in MHz].
-SP <directory> : Add directory to the search path list.
-IP <directory> : Add directory to the #include search path list.
-N <filename> : Output files generated to file path specified by filename.
-B <directory> : Save compiled binary files (*.mcl) to 'directory'.
-O : Miscellaneous output options.
-DBG : Generate debug info.
-L : Check and rebuild new libraries.
-DL : Build all files as libraries.
-Y : Dynamic link for string literals.
-UICD : ICD build type.
-EH <filename> : Full EEPROM HEX file name with path.
-LHF : Generate Long hex format.
-GC : Generate COFF file.
Example:
mikroCdsPIC.exe -MSF -DBG -p30F4013 -Y -DL -O11111114 -fo80 -NC:\Lcd\Lcd.mcpds -SPC:\
Program Files\Mikroelektronika\mikroC PRO for dsPIC\Defs
-SPC:\Program Files\Mikroelektronika\mikroC PRO for dsPIC\Uses -SPC:\
Lcd\ Lcd.c __Lib_Math.mcl __Lib_MathDouble.mcl
__Lib_System.mcl __Lib_Delays.mcl __Lib_LcdConsts.mcl __Lib_Lcd.
mcl
MikroElektronika
116
117
MikroElektronika
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 mikroC PRO for dsPIC30/33 and PIC24 program on a host dsPIC30/33 or PIC24 microcontroller and
view variable values, Special Function Registers (SFR), RAM, CODE and EEPROM memory along with the mikroICD
code execution on hardware.
MikroElektronika
118
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.
Related topics: mikroICD Debugger Example, mikroICD Debug Windows, mikroICD Debugger Options
119
MikroElektronika
Description
Function
Key
Start Debugger
Starts Debugger.
F9
Stop Debugger
Stop Debugger.
Ctrl + F2
F6
Step Into
F7
Step Over
F8
Step Out
Ctrl + F8
Run To Cursor
Toggle Breakpoint
Toolbar
Icon
F4
F5
MikroElektronika
120
First you have to write a program. We will show how the mikroICD works using this example :
// Lcd module connections
sbit LCD_RS at LATD0_bit;
sbit LCD_EN at LATD1_bit;
sbit LCD_D4 at LATB0_bit;
sbit LCD_D5 at LATB1_bit;
sbit LCD_D6 at LATB2_bit;
sbit LCD_D7 at LATB3_bit;
sbit LCD_RS_Direction at TRISD0_bit;
sbit LCD_EN_Direction at TRISD1_bit;
sbit LCD_D4_Direction at TRISB0_bit;
sbit LCD_D5_Direction at TRISB1_bit;
sbit LCD_D6_Direction at TRISB2_bit;
sbit LCD_D7_Direction at TRISB3_bit;
// End Lcd module connections
char text[] = "mikroElektronika";
char i;
void Move_Delay() {
Delay_ms(500);
}
void main() {
ADPCFG = 0xFFFF;
Lcd_Init();
Lcd_Cmd(_LCD_CLEAR);
Lcd_Cmd(_LCD_CURSOR_OFF);
for(i = 1; i < 17; i++) {
Lcd_Chr(1, i, text[i-1]);
}
}
121
MikroElektronika
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. To execute code line by line press [F8]. However, it is not recommended to use
Step Over [F8] over Delay routines and routines containing delays. In this case use Run to cursor [F4] function or Run
[F6] function combined with Breakpoints.
MikroElektronika
122
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 RealTime mode. Pressing F5 marks the line selected by the user for breakpoint. F6 executes code until the breakpoint
is reached. After reaching that breakpoint Debugger halts. Here in our example we will use breakpoints for writing a
word "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.
123
MikroElektronika
Common Errors :
- Trying to program the MCU while the mikroICD is active.
- Trying to debug Release build version of the program with the mikroICD debugger.
- Trying to debug program code which has been changed, but has not been compiled and programmed into the MCU.
- Trying to select line that is empty for Run to cursor [F4] and Toggle Breakpoints [F5] functions.
- Trying to debug MCU with mikroICD while Watch Dog Timer is enabled.
- Trying to debug MCU with mikroICD while Power Up Timer is enabled.
- Trying to Step Into [F7] the mikroC PRO for dsPIC30/33 and PIC24 Library routines. Use Step Over [F8] command
for these routines.
- It is not possible to force Code Protect while trying to debug MCU with mikroICD.
- Trying to debug MCU with mikroICD with pull-up resistors set to ON on RB6 and RB7.
Related topics: mikroICD Debugger, mikroICD Debug Windows, mikroICD Debugger Options
MikroElektronika
124
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 breakpoints
name.
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
125
button.
MikroElektronika
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
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.
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
126
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.
127
MikroElektronika
MikroElektronika
128
129
MikroElektronika
CHAPTER 5
Software Simulator Overview
MikroElektronika
130
Software Simulator
The Source-level Software Simulator is an integral component of the mikroC PRO for dsPIC30/33 and PIC24
environment. It is designed to simulate operations of the Microchip dsPIC30/33 and PIC24 MCUs and assist the users
in debugging code written for these devices.
Upon completion of writing your program, choose Release build Type in the Project Settings window:
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
Starting the Software Simulator makes more options available: Step Into, Step Over, Step Out, Run to Cursor, etc. Line
that is to be executed is color highlighted (blue by default).
Note : The Software Simulator simulates the program flow and execution of instruction lines, but it cannot fully emulate
dsPIC device behavior, i.e. it doesnt update timers, interrupt flags, etc.
Related topics: Software Simulator Debug Windows, Software Simulator Debugger Options
131
MikroElektronika
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.
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
MikroElektronika
button.
132
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
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.
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.
133
MikroElektronika
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
134
135
MikroElektronika
MikroElektronika
136
Description
Function
Key
Start Debugger
Starts Debugger.
F9
Stop Debugger
Stop Debugger.
Ctrl + F2
F6
Step Into
F7
Step Over
F8
Step Out
Ctrl + F8
Run To Cursor
Toggle Breakpoint
Toolbar
Icon
F4
F5
137
MikroElektronika
CHAPTER 6
mikroC PRO for dsPIC30/33 and
PIC24 Specifics
The following topics cover the specifics of mikroC PRO for dsPIC30/33 and PIC24 compiler:
- ANSI Standard Issues
- Predefined Globals and Constants
- Accessing Individual Bits
- Interrupts
- Linker Directives
- Built-in Routines
- Code Optimization
MikroElektronika
138
139
MikroElektronika
C Language Extensions
mikroC PRO for dsPIC30/33 and PIC24 has additional set of keywords that do not belong to the ANSI standard C
language keywords:
-
code
data
rx
sfr
xdata
ydata
dma
near
far
at
sbit
bit
iv
Implementation-defined Behavior
Certain sections of the ANSI standard have implementation-defined behavior. This means that the exact behavior of
some C code can vary from compiler to compiler. This Help contains the sections describing how the mikroC PRO for
dsPIC30/33 and PIC24 compiler behaves in such situations.
The most notable specifics include:
- Storage Classes
- Bit Fields
Related topics: Keywords, dsPIC30/33 and PIC24 Specifics
MikroElektronika
140
141
MikroElektronika
MikroElektronika
142
sbit type
The mikroC PRO for dsPIC30/33 and PIC24 compiler has sbit data type which provides access to registers, SFRs,
variables, etc.
You can declare a sbit variable in a unit in such way that it points to a specific bit in SFR register:
extern sfr sbit Abit; // Abit is precisely defined in some external file, for example in
the main program unit
In the main program you have to specify to which register this sbit points to, for example:
sbit Abit at PORTB.B0; // this is where Abit is fully defined
...
void main() {
...
}
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.
Note : Declaring a sbit variable is not possible via F0, F1, F15 identifiers.
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:
extern sbit AnotherBit; // AnotherBit is precisely defined in some external file, for
example in the main program unit
char MyVar;
sbit AnotherBit at MyVar.B0; // this is where AnotherBit is fully defined
...
void main() {
...
}
143
MikroElektronika
bit type
The mikroC PRO for dsPIC30/33 and PIC24 compiler provides a bit data type that may be used for variable
declarations. It can not be used for argument lists, and function-return values.
bit bf;
// bit variable
// invalid
// invalid
Note :
- Bit variables can not be initialized.
- Bit variables can not be members of structures and unions.
- Bit variables do not have addresses, therefore unary operator & (address of) is not applicable to these variables.
Related topics: Bit fields, Predefined globals and constants, Extern modifier
MikroElektronika
144
Interrupts
The dsPIC30/33 and PIC24 interrupt controller module reduces numerous peripheral interrupt request signals to a
single interrupt request signal to the dsPIC30/33 and PIC24 CPU and has the following features:
- Up to 8 processor exceptions and software traps
- 7 user-selectable priority levels
- Interrupt Vector Table (IVT) with up to 62 vectors (dsPIC30) or up to 118 vectors (dsPIC33 and PIC24)
- A unique vector for each interrupt or exception source
- Fixed priority within a specified user priority level
- Alternate Interrupt Vector Table (AIVT) for debug support
ISRs are organized in IVT. ISR is defined as a standard function but with the iv directive afterwards which connects the
function with specific interrupt vector. For example iv IVT_ADDR_T1INTERRUPT is IVT address of Timer1 interrupt
source of the dsPIC 30F3014 MCU. For more information on IVT refer to the dsPIC30/33 and PIC24 Family Reference
Manual.
Interrupt Handling
For the sake of interrupt handling convenience, new keyword, iv, is introduced. It is used to declare Interrupt Vector
Table (IVT) address for a defined interrupt routine :
void int1() iv IVT_ADDR_U1RXINTERRUPT{
asm nop;
}
Now it is possible to explicitly declare interrupt routine address :
void int1() org 0x600 iv IVT_ADDR_U1RXINTERRUPT {
asm nop;
}
145
MikroElektronika
Interrupt Example
Here is a simple example of handling the interrupts from Timer1 (if no other interrupts are allowed):
// Interrupt routine
void Timer1Int() iv IVT_ADDR_T1INTERRUPT {
//** it is necessary to clear manually the interrupt flag:
IFS0 = IFS0 & 0xFFF7;
// Clear TMR1IF
//** user code starts here
LATB = ~ PORTB;
// Invert PORTB
//** user code ends here
}
MikroElektronika
146
Linker Directives
The mikroC PRO for dsPIC30/33 and PIC24 uses an internal algorithm to distribute objects within memory. If you need
to have a variable or routine at specific predefined address, use the linker directives absolute and org.
Directive absolute
Directive absolute specifies the starting address in RAM for a variable or a starting address in ROM for a constant. If
the variable or constant is multi-byte, higher bytes will be stored at the consecutive locations.
Directive absolute is appended to declaration of a variable or constant :
// Variable x will occupy 1 byte at address 0x22 :
short x absolute 0x22;
// Variable y will occupy 2 bytes at addresses 0x23 and 0x24 :
int y absolute 0x23;
// Array elements will be placed on the consecutive locations starting from 0x1000 :
const short ConstantArray[] = {1,2,3} absolute 0x1000;
Note :
If you want to place simple type constant into Flash memory, instead of following declaration:
const short SimpeConstant = 0xAA absolute 0x2000;
use an array consisting of single element :
const short SimpleConstant[] = {0xAA} absolute 0x2000;
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.
Be careful when using the absolute directive, as you may overlap two variables by accident. For example:
// Variable i will occupy 1 byte at address 0x33
char i absolute 0x33;
// Variable will occupy 4 bytes at 0x30, 0x31, 0x32, 0x33; thus,
// changing i changes jjjj highest byte at the same time, and vice versa
long jjjj absolute 0x30;
Directive orgall
If the user wants to place his routines, constants, etc, above a specified address in ROM, #pragma orgall directive
should be used:
#pragma orgall 0x200
147
MikroElektronika
<starting_address>
MikroElektronika
148
Built-in Routines
The mikroC PRO for dsPIC30/33 and PIC24 compiler provides a set of useful built-in utility functions.
The Lo, Hi, Higher, Highest, LoWord, HiWord routines are implemented as macros. If you want to use these
functions you must include built_in.h header file (located in the inlclude folder of the compiler) into 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 doesnt count against the nested call limit.
The Vdelay_ms, Vdelay_advanced_ms, Delay_Cyc, Delay_Cyc_Long, Get_Fosc_kHz and Get_
Fosc_Per_Cyc are actual C routines. Their sources can be found in Delays.c file located in the uses folder of the
compiler.
- Lo
- Hi
- Higher
- Highest
- LoWord
- HiWord
- 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
149
MikroElektronika
Description
The function returns low byte of number. The 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 doesnt count against
the nested call limit.
Parameters
Returns
Requires
Nothing.
Example
d = 0x12345678;
tmp = Lo(d); // Equals 0x78
Lo(d) = 0xAA; // d equals 0x123456AA
Notes
None.
Hi
Prototype
Description
The function returns high byte of number. The 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 doesnt count against
the nested call limit.
Parameters
Returns
Requires
Nothing.
Example
d = 0x12345678;
tmp = Hi(d); // Equals 0x56
Hi(d) = 0xAA; // d equals 0x1234AA78
Notes
None.
MikroElektronika
150
Description
The function returns higher byte of number. The 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 doesnt count against
the nested call limit.
Parameters
Returns
Requires
Nothing.
Example
d = 0x12345678;
tmp = Higher(d);
// Equals 0x34
None.
Highest
Prototype
Description
The function returns highest byte of number. The 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 doesnt count against
the nested call limit.
Parameters
Returns
Requires
Nothing.
Example
d = 0x12345678;
tmp = Highest(d);
// Equals 0x12
151
None.
MikroElektronika
Description
The function returns low word of number. The function does not interpret bit patterns of number it
merely returns 16 bits as found in register.
This is an inline routine; code is generated in the place of the call, so the call doesnt count against
the nested call limit.
Parameters
Returns
Requires
Nothing.
Example
d = 0x12345678;
tmp = LoWord(d);
// Equals 0x5678
None.
HiWord
Prototype
Description
The function returns high word of number. The function does not interpret bit patterns of number it
merely returns 16 bits as found in register.
This is an inline routine; code is generated in the place of the call, so the call doesnt count against
the nested call limit.
Parameters
Returns
Requires
Nothing.
Example
d = 0x12345678;
tmp = HiWord(d);
// Equals 0x1234
None.
MikroElektronika
152
Description
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(10);
Notes
None.
Delay_ms
Prototype
Description
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);
Notes
For generating delays with variable as input parameter use the Vdelay_ms routine.
Vdelay_ms
Prototype
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
Returns
Nothing.
Requires
Nothing.
Example
unsignedpause = 1000;
...
Vdelay_ms(pause); // ~ one second pause
Notes
Vdelay_ms is a library function rather than a built-in routine; it is presented in this topic for the sake
of convenience.
153
MikroElektronika
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.
Parameters
Returns
Nothing.
Requires
Nothing.
Example
pause = 1000;
fosc = 10000;
VDelay_Advanced_ms(pause, fosc);
// Generates approximately one second
pause, for a oscillator frequency of 10 MHz
Notes
Note that VDelay_Advanced_ms is library function rather than a built-in routine; it is presented in
this topic for the sake of convenience.
Delay_Cyc
Prototype
Description
Creates a delay based on MCU clock. Delay lasts for x*16384 + y MCU clock cycles.
Parameters
Returns
Nothing.
Requires
Nothing.
Example
Delay_Cyc(1, 10);
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
Description
Creates a delay based on MCU clock. Delay lasts for CycNo MCU clock cycles.
Parameters
Returns
Nothing.
Requires
Nothing.
Example
Delay_Cyc_Long(16394);
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
154
Description
Parameters
None.
Returns
Requires
Nothing.
Example
Notes
None.
Clock_Mhz
Prototype
Description
Parameters
None.
Returns
Requires
Nothing.
Example
Notes
None.
Get_Fosc_kHz
Prototype
Description
Parameters
None.
Returns
Requires
Nothing.
Example
Notes
None.
155
MikroElektronika
Description
Function returns devices 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
Requires
Nothing.
Example
Notes
None.
MikroElektronika
156
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.
157
MikroElektronika
MikroElektronika
if(y+k)
ADD
_WREG1, _WREG2, _WREG0
BRA Z L_main0
asm nop;
NOP
158
MOV
ADD
ADD
BRA Z
if(y+k)
[_WREG14+0], _WREG1
_WREG14, #2, _WREG0
_WREG1, [_WREG0], _WREG0
L_main0
asm nop;
NOP
159
MikroElektronika
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.
}
Related topics: Code Optimization, dsPIC Specifics, mikroC PRO for dsPIC30/33 and PIC24 specifics, Memory type
specifiers
MikroElektronika
160
161
MikroElektronika
3. Now, compile the project. In the messages window, appropriate message on COFF file generation should appear :
4. Generated COFF file will be created in the project folder, with the .cof extension.
Related topics: Using MPLAB ICD 2 Debugger, Using MPLAB Simulator
MikroElektronika
162
CHAPTER 7
dsPIC30/33 and PIC24 Specifics
In order to get the most from the mikroC PRO for dsPIC30/33 and PIC24 compiler, the user should be familiar with certain
aspects of dsPIC30/33 and PIC24 MCU. This knowledge is not essential, but it can provide a better understanding of
the dsPIC30/33 and PIC24s capabilities and limitations, and their impact on the code writing as well.
163
MikroElektronika
MikroElektronika
164
165
MikroElektronika
MikroElektronika
166
167
MikroElektronika
code
data
rx
sfr
xdata
ydata
dma
code
Description The code memory type may be used for allocating constants in program memory.
Example
data
Description This memory specifier is used when storing variable to the Data RAM.
Example
rx
Description This memory specifier allows variable to be stored in the working registers space
(WREG0-WREG15).
Example
sfr
Description This memory specifier allows user to access special function registers. It also
instructs compiler to maintain same identifier in source and assembly.
Example
MikroElektronika
168
ydata
Description This memory specifier allows user to access Y Data memory space.
Example
dma
Description This memory specifier allows user to access DMA memory space (dsPIC33F
specific).
Example
Note: If none of the memory specifiers are used when declaring a variable, data specifier will be set
as default by the compiler.
Related topics: dsPIC Memory Organization, dsPIC Memory Type Qualifiers, Accessing individual
bits, SFRs, Constants, Functions
169
MikroElektronika
Data Memory
near
Program Memory
First 8 kB of RAM
In default page
far
Anywhere in RAM
Example:
char i;
// far memory qualifier is set, variable i can allocated somewhere in data memory
char near j;
// near memory qualifier is set, variable j will be allocated in the first 8kB of data memory
const int k = 10; // near memory qualifier is set, constant k will be allocated in the default memory page
Related topics: dsPIC Memory Organization, dsPIC Memory Type Specifiers
MikroElektronika
170
171
PORTB is read:
STORE
MikroElektronika
WRITE
MikroElektronika
WRITE
172
Actual voltage levels on MCU pins are no longer relevant when using LATx for output
MODIFY Data is modified to set the RB0 bit:
173
WRITE
MikroElektronika
Actual voltage levels on MCU pins are no longer relevant when using LATx for output
MODIFY Data is modified to set the bit:
MikroElektronika
174
CHAPTER 8
mikroC PRO for dsPIC30/33 and
PIC24 Language Reference
175
MikroElektronika
MikroElektronika
176
177
MikroElektronika
MikroElektronika
178
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
int i; float f;
and
int
i;
float f;
are lexically equivalent and parse identically to give six tokens:
int
i
;
float
f
;
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,
char name[] = mikro foo;
parses into seven tokens, including a single string literal token:
char
name
[
]
=
mikro foo
;
179
MikroElektronika
Comments
Comments are pieces of a text used to annotate a program and technically are another form of whitespace. Comments
are for the programmers use only; they are stripped from the source text before parsing. There are two ways to delineate
comments: the C method and the C++ method. Both are supported by mikroC PRO for dsPIC30/33 and PIC24.
You should also follow the guidelines on the use of whitespace and delimiters in comments, discussed later in this topic
to avoid other portability problems.
C comments
C comment is any sequence of characters placed after the symbol pair /*. The comment terminates at the first occurance
of the pair */ following the initial /*. The entire sequence, including four comment-delimiter symbols, is replaced by one
space after macro expansion.
In the mikroC PRO for dsPIC30/33 and PIC24,
int /* type */ i /* identifier */;
parses as:
int i;
Note that the mikroC PRO for dsPIC30/33 and PIC24 does not support a nonportable token pasting strategy using /**/.
For more information on token pasting, refer to the Preprocessor Operators.
C++ comments
The mikroC PRO for dsPIC30/33 and PIC24 allows single-line comments using two adjacent slashes (//). The comment
can start in any position and extends until the next new line.
The following code
int i;
int j;
// this is a comment
parses as:
int i;
int j;
Nested comments
ANSI C doesnt allow nested comments. The attempt to nest a comment like this
/*
int /* declaration */ i; */
fails, because the scope of the first /* ends at the first */. This gives us
i; */
which would generate a syntax error.
MikroElektronika
180
Tokens
Token is the smallest element of a C program that compiler can recognize. The parser separates tokens from the input
stream by creating the longest token possible using the input characters in a lefttoright scan.
The mikroC PRO for dsPIC30/33 and PIC24 recognizes the following kinds of tokens:
- keywords
- identifiers
- constants
- operators
- punctuators (also known as separators)
Tokens can be concatenated (pasted) by means of the preprocessor operator ##. See the Preprocessor Operators for
details.
a+++b;
First, note that inter would be parsed as a single identifier, rather than as the keyword int followed by the identifier
er.
The programmer who has written the code might have intended to write inter = a + (++b), but it wouldnt work
that way. The compiler would parse it into the seven following tokens:
inter
=
a
++
+
b
;
//
//
//
//
//
//
//
variable identifier
assignment operator
variable identifier
postincrement operator
addition operator
variable identifier
statement terminator
181
MikroElektronika
Constants
Constants or literals are tokens representing fixed numeric or character values.
The mikroC PRO for dsPIC30/33 and PIC24 supports:
- integer constants
- floating point constants
- character constants
- string constants (strings literals)
- enumeration constants
The data type of a constant is deduced by the compiler using such clues as a numeric value and format used in the
source code.
Integer Constants
Integer constants can be decimal (base 10), hexadecimal (base 16), binary (base 2), or octal (base 8). In the absence
of any overriding suffixes, the data type of an integer constant is derived from its value.
Decimal
Decimal constants from -2147483648 to 4294967295 are allowed. Constants exceeding these bounds will produce
an Out of range error. Decimal constants must not use an initial zero. An integer constant that has an initial zero is
interpreted as an octal constant. Thus,
int i = 10;
int i = 010;
int i = 0;
MikroElektronika
/* decimal 10 */
/* decimal 8 */
/* decimal 0 = octal 0 */
182
Assumed Type
< -2147483648
-2147483648 -32769
long
-32768 -129
int
-128 127
short
128 255
unsigned short
256 32767
int
32768 65535
unsigned int
65536 2147483647
long
2147483648 4294967295
unsigned long
> 4294967295
Hexadecimal
All constants starting with 0x (or 0X) are taken to be hexadecimal. In the absence of any overriding suffixes, the data
type of an hexadecimal constant is derived from its value, according to the rules presented above. For example,
0xC367 will be treated as unsigned int.
Binary
All constants starting with 0b (or 0B) are taken to be binary. In the absence of any overriding suffixes, the data type
of an binary constant is derived from its value, according to the rules presented above. For example, 0b11101 will be
treated as short.
Octal
All constants with an initial zero are taken to be octal. If an octal constant contains the illegal digits 8 or 9, an error
is reported. In the absence of any overriding suffixes, the data type of an octal constant is derived from its value,
according to the rules presented above. For example, 0777 will be treated as int.
183
MikroElektronika
//
//
//
//
//
//
=
=
=
=
=
=
0.0
-1.23
23.45 * 10^6
2.0 * 10^-5
3.0 * 10^10
0.09 * 10^34
The mikroC PRO for dsPIC30/33 and PIC24 floating-point constants are of the type double. Note that the mikroC PRO
for dsPICs implementation of ANSI Standard considers float and double (together with the long double variant)
to be the same type.
Character Constants
A character constant is one or more characters enclosed in single quotes, such as A, +, or \n. In the mikroC
PRO for dsPIC30/33 and PIC24, single-character constants are of the unsigned int type. Multi-character constants
are referred to as string constants or string literals. For more information refer to String Constants.
Escape Sequences
A backslash character (\) is used to introduce an escape sequence, which allows a visual representation of certain
nongraphic characters. One of the most common escape constants is the newline character (\n).
A backslash is used with octal or hexadecimal numbers to represent an ASCII symbol or control code corresponding
to that value; for example, \x3F for the question mark. Any value within legal range for data type char (0 to 0xFF
for the mikroC PRO for dsPIC30/33 and PIC24) can be used. Larger numbers will generate the compiler error Out of
range.
MikroElektronika
184
Value
Char
What it does?
\a
0x07
BEL
Audible bell
\b
0x08
BS
Backspace
\f
0x0C
FF
Formfeed
\n
0x0A
LF
Newline (Linefeed)
\r
0x0D
CR
Carriage Return
\t
0x09
HT
Tab (horizontal)
\v
0x0B
VT
Vertical Tab
\\
0x5C
Backslash
0x27
0x22
Double quote
\?
0x3F
Question mark
\O
any
\xH
any
\XH
any
Disambiguation
Some ambiguous situations might arise when using escape sequences.
Here is an example:
Lcd_Out_Cp(\x091.0 Intro);
This is intended to be interpreted as \x09 and 1.0 Intro. However, the mikroC PRO for dsPIC30/33 and PIC24
compiles it as the hexadecimal number \x091 and literal string .0 Intro. To avoid such problems, we could
rewrite the code in the following way:
Lcd_Out_Cp(\x09 1.0 Intro);
For more information on the previous line, refer to String Constants.
Ambiguities might also arise if an octal escape sequence is followed by a nonoctal digit. For example, the following
constant:
\118
would be interpreted as a two-character constant made up of the characters \11 and 8, because 8 is not a legal octal digit.
185
MikroElektronika
String Constants
String constants, also known as string literals, are a special type of constants which store fixed sequences of characters.
A string literal is a sequence of any number of characters surrounded by double quotes:
This is a string.
The null string, or empty string, is written like . A literal string is stored internally as a given sequence of characters
plus a final null character. A null string is stored as a single null character.
The characters inside the double quotes can include escape sequences. This code, for example:
\t\Name\\\\tAddress\n\n
prints like this:
Name\
Address
The Name is preceded by two tabs; The Address is preceded by one tab. The line is followed by two new lines. The
\ provides interior double quotes. The escape character sequence \\ is translated into \ by the compiler.
Adjacent string literals separated only by whitespace are concatenated during the parsing phase. For example:
This is just
an example.
is equivalent to
This is just an example.
MikroElektronika
186
Enumeration Constants
Enumeration constants are identifiers defined in enum type declarations. The identifiers are usually chosen as
mnemonics to contribute to legibility. Enumeration size is calculated according to the enumerators (enumeration
elements). They can be used in any expression where integer constants are valid.
For example:
enum weekdays { SUN = 0, MON, TUE, WED, THU, FRI, SAT };
The identifiers (enumerators) used must be unique within the scope of the enum declaration. Negative initializers are
allowed. See Enumerations for details about enum declarations.
Pointer Constants
A pointer or pointed-at object can be declared with the const modifier. Anything declared as const cannot change its
value. It is also illegal to create a pointer that might violate a non-assignability of the constant object.
Consider the following examples:
int i;
int * pi;
int * const cp = &i;
const int ci = 7;
const int * pci;
const int * const cpc = &ci;
//
//
//
//
//
//
i is an int
pi is a pointer to int (uninitialized)
cp is a constant pointer to int
ci is a constant int
pci is a pointer to constant int
cpc is a constant pointer to a constant int
//
//
//
//
//
Similar rules are applayed to the volatile modifier. Note that both const and volatile can appear as modifiers
to the same identifier.
187
MikroElektronika
Constant Expressions
A constant expressions can be evaluated during translation rather that runtime and accordingly may be used in any
place that a constant may be.
Constant expressions can consist only of the following:
- literals,
- enumeration constants,
- simple constants (no constant arrays or structures),
- sizeof operators.
Constant expressions cannot contain any of the following operators, unless the operators are contained within the
operand of a sizeof operator: assignment, comma, decrement, function call, increment.
Each constant expression can evaluate to a constant that is in the range of representable values for its type.
Constant expression can be used anywhere a constant is legal.
MikroElektronika
188
Keywords
Keywords are words reserved for special purposes and must not be used as normal identifier names.
Beside standard C keywords, all relevant SFR are defined as global variables and represent reserved words that
cannot be redefined (for example: TMR0, PCL, etc). Probe the Code Assistant for specific letters (Ctrl+Space in Editor)
or refer to Predefined Globals and Constants.
Here is an alphabetical listing of keywords in C:
-
absolute
asm
at
auto
bit
bool
break
case
catch
char
class
code
const
continue
data
default
delete
dma
do
double
else
enum
explicit
extern
false
far
float
for
friend
goto
if
inline
int
iv
long
mutable
namespace
near
operator
org
pascal
private
189
MikroElektronika
protected
public
register
return
rx
sfr
short
signed
sizeof
static
struct
switch
template
this
throw
true
try
typedef
typeid
typename
union
unsigned
using
virtual
void
volatile
while
xdata
ydata
Also, the mikroC PRO for dsPIC30/33 and PIC24 includes a number of predefined identifiers used in libraries. You
could replace them by your own definitions, if you want to develop your own libraries. For more information, see mikroC
PRO for dsPIC30/33 and PIC24 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 (dont get confused with the
meaning of object in object-oriented programming).
Identifiers can contain the letters a to z and A to Z, underscore character _, and digits from 0 to 9. The only restriction
is that the first character must be a letter or an underscore.
Case Sensitivity
The mikroC PRO for dsPIC30/33 and PIC24 identifiers arent case sensitive by default, so that Sum, sum, and suM
represent an equivalent identifier. Case sensitivity can be activated or suspended in Output Settings window. Even if
case sensitivity is turned off Keywords remain case sensitive and they must be written in lower case.
MikroElektronika
190
Identifier Examples
Here are some valid identifiers:
temperature_V1
Pressure
no_hit
dat2string
SUM3
_vtext
and here are some invalid identifiers:
7temp
%higher
int
j23.07.04
//
//
//
//
NO
NO
NO
NO
-----
cannot
cannot
cannot
cannot
Punctuators
The mikroC PRO for dsPIC30/33 and PIC24 punctuators (also known as separators) are:
- [ ] Brackets
- ( ) Parentheses
- { } Braces
- , Comma
- ; Semicolon
- : Colon
- * Asterisk
- = Equal sign
- # Pound sign
Most of these punctuators also function as operators.
Brackets
Brackets [ ] indicate single and multidimensional array subscripts:
char ch, str[] = mikro;
int mat[3][4];
ch = str[3];
191
/* 3 x 4 matrix */
/* 4th element */
MikroElektronika
if (d == z) ++x;
func();
void func2(int n);
Parentheses are recommended in macro definitions to avoid potential precedence problems during an expansion:
#define CUBE(x) ((x) * (x) * (x))
For more information, refer to Operators Precedence And Associativity and Expressions.
Braces
Braces { } indicate the start and end of a compound statement:
if (d == z) {
++x;
func();
}
Closing brace serves as a terminator for the compound statement, so a semicolon is not required after }, except in
structure declarations. Sometimes, the semicolon can be illegal, as in
if (statement)
{ ... };
/* illegal semicolon! */
else
{ ... };
For more information, refer to the Compound Statements.
Comma
Comma (,) separates the elements of a function argument list:
void func(int n, float f, char ch);
Comma is also used as an operator in comma expressions. Mixing two uses of comma is legal, but you must use
parentheses to distinguish them. Note that (exp1, exp2) evalutates both but is equal to the second:
func(i, j);
func((exp1, exp2), (exp3, exp4, exp5));
MikroElektronika
192
Colon
Use colon (:) to indicate the labeled statement:
start: x = 0;
...
goto start;
Labels are discussed in the Labeled Statements.
Pointers with multiple levels of indirection can be declared by indicating a pertinent number of asterisks:
int **int_ptr;
double ***double_ptr;
You can also use asterisk as an operator to either dereference a pointer or as multiplication operator:
i = *int_ptr;
a = b * 3.14;
For more information, see the Pointers.
193
MikroElektronika
MikroElektronika
194
Concepts
This section covers some basic concepts of language, essential for understanding of how C programs work. First, we
need to establish the following terms that will be used throughout the help:
- Objects and lvalues
- Scope and Visibility
- Name Spaces
- Duration
Objects
An object is a specific region of memory that can hold a fixed or variable value (or set of values). This use of a term
object is different from the same term, used in object-oriented languages, which is more general. Our definiton of the
word would encompass functions, variables, symbolic constants, user-defined data types, and labels.
Each value has an associated name and type (also known as a data type). The name is used to access the object and
can be a simple identifier or complex expression that uniquely refers the object.
195
MikroElektronika
Rvalues
The expression a + b is not lvalue: a + b = a is illegal because the expression on the left is not related to an object.
Such expressions are sometimes called rvalues (short for right values).
Visibility
The visibility of an identifier is a region of the program source code from which an identifiers associated object can be
legally accessed.
Scope and visibility usually coincide, though there are circumstances under which an object becomes temporarily
hidden by the appearance of a duplicate identifier: the object still exists but the original identifier cannot be used to
access it until the scope of the duplicate identifier ends.
MikroElektronika
196
//
//
//
//
nested block
j is local name in the nested block
i and double j are visible;
int j = 3 in scope but hidden
}
j += 1;
}
// i and j are both out of scope
Name Spaces
Name space is a scope within which an identifier must be unique. The mikroC PRO for dsPIC30/33 and PIC24 uses
four distinct categories of identifiers:
1. goto label names - must be unique within the function in which they are declared.
2. Structure, union, and enumeration tags - must be unique within the block in which they are defined. Tags
declared outside of any function must be unique.
3. Structure and union member names - must be unique within the structure or union in which they are
defined. There is no restriction on the type or offset of members with the same member name in different
structures.
4. Variables, typedefs, functions, and enumeration members - must be unique within the scope in which they
are defined. Externally declared identifiers must be unique among externally declared variables.
Duplicate names are legal for different name spaces regardless of the scope rules.
For example:
int blue = 73;
{ // open a block
enum colors { black, red, green, blue, violet, white } c;
/* enumerator blue = 3 now hides outer declaration of int blue */
struct colors { int i, j; };
double red = 2;
}
blue = 37;
197
MikroElektronika
Duration
Duration, closely related to a storage class, defines a period during which the declared identifiers have real, physical
objects allocated in memory. We also distinguish between compile-time and run-time objects. Variables, for instance,
unlike typedefs and types, have real memory allocated during run time. There are two kinds of duration: static and
local.
Static Duration
Memory is allocated to objects with static duration as soon as execution is underway; this storage allocation lasts until
the program terminates. Static duration objects usually reside in fixed data segments allocated according to the memory
specifier in force. All globals have static duration. All functions, wherever defined, are objects with static duration. Other
variables can be given static duration by using the explicit static or extern storage class specifiers.
In the mikroC PRO for dsPIC30/33 and PIC24, static duration objects are not initialized to zero (or null) in the absence
of any explicit initializer.
Dont mix static duration with file or global scope. An object can have static duration and local scope see the example
below.
Local Duration
Local duration objects are also known as automatic objects. They are created on the stack (or in a register) when an
enclosing block or a function is entered. They are deallocated when the program exits that block or function. Local
duration objects must be explicitly initialized; otherwise, their contents are unpredictable.
The storage class specifier auto can be used when declaring local duration variables, but it is usually redundant,
because auto is default for variables declared within a block.
An object with local duration also has local scope because it does not exist outside of its enclosing block. On the other
hand, a local scope object can have static duration. For example:
void f() {
/* local duration variable; init a upon every call to f */
int a = 1;
/* static duration variable; init b only upon first call to f */
static int b = 1;
/* checkpoint! */
a++;
b++;
}
void main() {
/* At checkpoint,
f(); // a=1, b=1,
f(); // a=1, b=2,
f(); // a=1, b=3,
// etc.
}
MikroElektronika
we will have: */
after first call,
after second call,
after third call,
198
Types
The mikroC PRO for dsPIC30/33 and PIC24 is a strictly typed language, which means that every object, function,
and expression must have a strictly defined type, known in the time of compilation. Note that the mikroC PRO for
dsPIC30/33 and PIC24 works exclusively with numeric types.
The type serves:
- to determine the correct memory allocation required,
- to interpret the bit patterns found in the object during subsequent accesses,
- in many type-checking situations, to ensure that illegal assignments are trapped.
The mikroC PRO for dsPIC30/33 and PIC24 supports many standard (predefined) and user-defined data types, including
signed and unsigned integers in various sizes, floating-point numbers with various precisions, arrays, structures, and
unions. In addition, pointers to most of these objects can be established and manipulated in memory.
The type determines how much memory is allocated to an object and how the program will interpret the bit patterns
found in the objects storage allocation. A given data type can be viewed as a set of values (often implementationdependent) that identifiers of that type can assume, together with a set of operations allowed with these values. The
compile-time operator sizeof allows you to determine the size in bytes of any standard or user-defined type.
The mikroC PRO for dsPIC30/33 and PIC24 standard libraries and your own program and header files must provide
unambiguous identifiers (or expressions derived from them) and types so that the mikroC PRO for dsPIC can
consistently access, interpret, and (possibly) change the bit patterns in memory corresponding to each active object in
your program.
Type Categories
A common way to categorize types is to divide them into:
- fundamental
- derived
The fudamental types represent types that cannot be split up into smaller parts. They are sometimes referred to as
unstructured types. The fundamental types are void, char, int, float, and double, together with short, long,
signed, and unsigned variants of some of them. For more information on fundamental types, refer to the topic
Fundamental Types.
The derived types are also known as structured types and they include pointers to other types, arrays of other types,
function types, structures, and unions. For more information on derived types, refer to the topic Derived Types.
199
MikroElektronika
Fundamental Types
The fudamental types represent types that cannot be divided into more basic elements, and are the model for
representing elementary data on machine level. The fudamental types are sometimes referred to as unstructured types,
and are used as elements in creating more complex derived or user-defined types.
The fundamental types include:
- Arithmetic Types
- Enumerations
- Void Type
Arithmetic Types
The arithmetic type specifiers are built up from the following keywords: void, char, int, float and double,
together with the prefixes short, long, signed and unsigned. From these keywords you can build both integral
and floating-point types.
Integral Types
The types char and int, together with their variants, are considered to be integral data types. Variants are created
by using one of the prefix modifiers short, long, signed and unsigned.
In the table below is an overview of the integral types keywords in parentheses can be (and often are) omitted.
The modifiers signed and unsigned can be applied to both char and int. In the absence of the unsigned prefix,
signed is automatically assumed for integral types. The only exception is char, which is unsigned by default. The
keywords signed and unsigned, when used on their own, mean signed int and unsigned int, respectively.
The modifiers short and long can only be applied to int. The keywords short and long, used on their own,
mean short int and long int, respectively.
Type
MikroElektronika
Size in bytes
Range
bit
1-bit
0 or 1
sbit
1-bit
0 or 1
(unsigned) char
0 .. 255
signed char
- 128 .. 127
- 128 .. 127
0 .. 255
(signed) int
-32768 .. 32767
unsigned (int)
0 .. 65535
-2147483648 .. 2147483647
0 .. 4294967295
200
Size in bytes
Range
1045
.. +3.4 * 1038
float
-1.5 *
double
long double
Enumerations
An enumeration data type is used for representing an abstract, discreet set of values with appropriate symbolic
names.
Enumeration Declaration
Enumeration is declared like this:
enum tag {enumeration-list};
Here, tag is an optional name of the enumeration; enumeration-list is a comma-delimited list of discreet values,
enumerators (or enumeration constants). Each enumerator is assigned a fixed integral value. In the absence of
explicit initializers, the first enumerator is set to zero, and the value of each succeeding enumerator is set to a value of
its predecessor increased by one.
Variables of the enum type are declared the same as variables of any other type. For example, the following
declaration:
enum colors { black, red, green, blue, violet, white } c;
establishes a unique integral type, enum colors, variable c of this type, and set of enumerators with constant integer
values (black = 0, red = 1, ...). In the mikroC PRO for dsPIC30/33 and PIC24, a variable of an enumerated type can be
assigned any value of the type int no type checking beyond that is enforced. That is:
c = red;
c = 1;
201
// OK
// Also OK, means the same
MikroElektronika
//
//
//
//
//
//
value
value
value
value
value
value
0
1
2
6
7
4
Initializer expression can include previously declared enumerators. For example, in the following declaration:
enum memory_sizes { bit = 1, nibble = 4 * bit, byte = 2 * nibble,
kilobyte = 1024 * byte };
nibble would acquire the value 4, byte the value 8, and kilobyte the value 8192.
Like with struct and union declarations, you can omit the tag if no further variables of this enum type are required:
/* Anonymous enum type: */
enum { black, red, green, blue, violet, white } color;
Enumeration Scope
Enumeration tags share the same name space as structure and union tags. Enumerators share the same name space
as ordinary variable identifiers:
int blue = 73;
{ // open a block
enum colors { black, red, green, blue, violet, white } c;
/* enumerator blue = 3 now hides outer declaration of int blue */
struct colors { int i, j; };
double red = 2;
}
blue = 37;
MikroElektronika
202
Void Type
void is a special type indicating the absence of any value. There are no objects of void; instead, void is used for
deriving more complex types.
Void Functions
Use the void keyword as a function return type if the function does not return a value.
void print_temp(char temp) {
Lcd_Out_Cp(Temperature:);
Lcd_Out_Cp(temp);
Lcd_Chr_Cp(223); // degree character
Lcd_Chr_Cp(C);
}
Use void as a function heading if the function does not take any parameters. Alternatively, you can just write empty
parentheses:
main(void) { // same as main()
...
}
Generic Pointers
Pointers can be declared as void, which means that they can point to any type. These pointers are sometimes called
generic.
Derived Types
The derived types are also known as structured types. They are used as elements in creating more complex userdefined types.
The derived types include:
- arrays
- pointers
- structures
- unions
203
MikroElektronika
Arrays
Array is the simplest and most commonly used structured type. A variable of array type is actually an array of objects
of the same type. These objects represent elements of an array and are identified by their position in array. An array
consists of a contiguous region of storage exactly large enough to hold all of its elements.
Array Declaration
Array declaration is similar to variable declaration, with the brackets added after identifer:
type array_name[constant-expression]
This declares an array named as array_name and composed of elements of type. The type can be any scalar type
(except void), user-defined type, pointer, enumeration, or another array. Result of constant-expression within the
brackets determines a number of elements in array. If an expression is given in an array declarator, it must evaluate to
a positive constant integer. The value is a number of elements in an array.
Each of the elements of an array is indexed from 0 to the number of elements minus one. If a number of elements is n,
elements of array can be approached as variables array_name[0] .. array_name[n-1] of type.
Here are a few examples of array declaration:
#define MAX = 50
int
vector_one[10];
float vector_two[MAX];
float vector_three[MAX - 20];
Array Initialization
An array can be initialized in declaration by assigning it a comma-delimited sequence of values within braces. When
initializing an array in declaration, you can omit the number of elements it will be automatically determined according
to the number of elements assigned. For example:
/* Declare an array which holds number of days in each month: */
int days[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
/* This declaration is identical to the previous one */
int days[] = {31,28,31,30,31,30,31,31,30,31,30,31};
If you specify both the length and starting values, the number of starting values must not exceed the specified length. The opposite
is possible, in this case the trailing excess elements will be assigned to some encountered runtime values from memory.
In case of array of char, you can use a shorter string literal notation. For example:
/* The two declarations are identical: */
const char msg1[] = {T, e, s, t, \0};
const char msg2[] = Test;
For more information on string literals, refer to String Constants.
MikroElektronika
204
Multi-dimensional Arrays
An array is one-dimensional if it is of scalar type. One-dimensional arrays are sometimes referred to as vectors.
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 of 2-dimensional
array:
float m[50][20];
A variable m is an array of 50 elements, which in turn are arrays of 20 floats each. Thus, we have a matrix of 50x20
elements: the first element is m[0][0], the last one is m[49][19]. The first element of the 5th row would be m[4]
[0].
If you dont initialize the array in the declaration, you can omit the first dimension of multi-dimensional array. In that
case, array is located elsewhere, e.g. in another file. This is a commonly used technique when passing arrays as
function parameters:
int a[3][2][4];
205
MikroElektronika
Pointers
Pointers are special objects for holding (or pointing to) memory addresses. In the mikroC PRO for dsPIC30/33 and
PIC24, address of an object in memory can be obtained by means of an unary operator &. To reach the pointed object,
we use an indirection operator (*) on a pointer.
A pointer of type pointer to object of type holds the address of (that is, points to) an object of type. Since pointers are
objects, you can have a pointer pointing to a pointer (and so on). Other objects commonly pointed to include arrays,
structures, and unions.
A pointer to a function is best thought of as an address, usually in a code segment, where that functions executable
code is stored; that is, the address to which control is transferred when that function is called.
Although pointers contain numbers with most of the characteristics of unsigned integers, they have their own rules and
restrictions for declarations, assignments, conversions, and arithmetic. The examples in the next few sections illustrate
these rules and restrictions.
Pointer Declarations
Pointers are declared the same as any other variable, but with * ahead of identifier. A type at the beginning of declaration
specifies the type of a pointed object. A pointer must be declared as pointing to some particular type, even if that type
is void, which really means a pointer to anything. Pointers to void are often called generic pointers, and are treated
as pointers to char in the mikroC PRO for dsPIC30/33 and PIC24.
If type is any predefined or user-defined type, including void, the declaration
type *p;
/* Uninitialized pointer */
declares p to be of type pointer to type. All scoping, duration, and visibility rules are applied to the p object just
declared. You can view the declaration in this way: if *p is an object of type, then p has to be a pointer to such object
(object of type).
Note:
You must initialize pointers before using them! Our previously declared pointer *p is not initialized (i.e.
assigned a value), so it cannot be used yet.
In case of multiple pointer declarations, each identifier requires an indirect operator. For example:
MikroElektronika
206
The pointer type pointer to void must not be confused with the null pointer. The declaration
void *vp;
declares that vp is a generic pointer capable of being assigned to by any pointer to type value, including null, without
complaint.
Assignments without proper casting between a pointer to type1 and a pointer to type2, where type1 and type2
are different types, can invoke a compiler warning or error. If type1 is a function and type2 isnt (or vice versa),
pointer assignments are illegal. If type1 is a pointer to void, no cast is needed. If type2 is a pointer to void, no
cast is needed.
207
MikroElektronika
MikroElektronika
208
Thus functions and function pointers with different calling convention (argument order, arguments type or
return type is different) are incompatible with each other.
209
MikroElektronika
Pointer Arithmetic
Pointer arithmetic in the mikroC PRO for dsPIC30/33 and PIC24 is limited to:
- assigning one pointer to another,
- comparing two pointers,
- comparing pointer to zero,
- adding/subtracting pointer and an integer value,
- subtracting two pointers.
The internal arithmetic performed on pointers depends on the memory specifier in force and the presence of any
overriding pointer modifiers. When performing arithmetic with pointers, it is assumed that the pointer points to an array
of objects.
MikroElektronika
210
=
=
a + i
*(a + i)
// pa points to a[4]
// x = a[7]
/* .. but: */
y = *pa + 3;
// y = a[4] + 3
The following examples are also valid, but better avoid this syntax as it can make the code really illegible:
(a + 1)[i] = 3;
// same as: *((a + 1) + i) = 3, i.e. a[i + 1] = 3
(i + 2)[a] = 0;
// same as: *((i + 2) + a) = 0, i.e. a[i + 2] = 0
211
Comparing pointers pointing to different objects/arrays can be performed at programmers own responsibility
a precise overview of datas physical storage is required
MikroElektronika
/*
/*
/*
/*
There is no such element as one past the last element, of course, but the pointer is allowed to assume such value. C
guarantees that the result of addition is defined even when pointing to one element past array. If P points to the last
array element, P + 1 is legal, but P + 2 is undefined.
This allows you to write loops which access the array elements in a sequence by means of incrementing pointer in
the last iteration you will have the pointer pointing to one element past the array, which is legal. However, applying an
indirection operator (*) to a pointer to one past the last element leads to undefined behavior.
For example:
void f (some_type a[], int n) {
/* function f handles elements of array a; */
/* array a has n elements of type some_type */
int i;
some_type *p=&a[0];
for ( i = 0; i < n; i++ ) {
/* .. here we do something with *p .. */
p++; /* .. and with the last iteration p exceeds
the last element of array a */
}
/* at this point, *p is undefined! */
}
MikroElektronika
212
a[10];
*pi1 = &a[0];
*pi2 = &a[4];
pi2 - pi1;
-= (i >> 1);
/* i equals 8 */
/* pi2 = pi2 - 4: pi2 now points to [0] */
Structures
A structure is a derived type usually representing a user-defined collection of named members (or components). These
members can be of any type, either fundamental or derived (with some restrictions to be discussed later), in any
sequence. In addition, a structure member can be a bit field.
Unlike arrays, structures are considered to be single objects. The mikroC PRO for dsPIC30/33 and PIC24 structure
type lets you handle complex data structures almost as easily as single variables.
The mikroC PRO for dsPIC30/33 and PIC24 supports anonymous structures.
213
MikroElektronika
Incomplete Declarations
Incomplete declarations are also known as forward declarations. A pointer to a structure type A can legally appear in
the declaration of another structure B before A has been declared:
struct A; // incomplete
struct B {struct A *pa;};
struct A {struct B *pb;};
The first appearance of A is called incomplete because there is no definition for it at that point. An incomplete declaration
is allowed here, because the definition of B doesnt need the size of A.
MikroElektronika
214
Anonymous Structures
mikroC PRO for dsPIC30/33 and PIC24 allows you to declare a structure variable within another structure without
giving it a name.
These nested structures are called anonymous structures.
You can access the members of an anonymous structure as if they were members in the containing structure:
struct phone{
int areacode;
long number;
};
struct person {
char
name[30];
char
gender;
int
age;
int
weight;
struct phone;
// Anonymous structure; no name needed
} Jim;
Jim.number = 1234567;
}
Related topics: Working with structures
215
MikroElektronika
Assignment
Variables of the same structured type may be assigned one to another by means of simple assignment operator (=).
This will copy the entire contents of the variable to destination, regardless of the inner complexity of a given structure.
Note that two variables are of the same structured type only if they are both defined by the same instruction or using
the same type identifier. For example:
/* a and b are of the same type: */
struct {int m1, m2;} a, b;
/* But c and d are _not_ of the same type although
their structure descriptions are identical: */
struct {int m1, m2;} c;
struct {int m1, m2;} d;
Size of Structure
The size of the structure in memory can be retrieved by means of the operator sizeof. It is not necessary that the
size of the structure is equal to the sum of its members sizes. It is often greater due to certain limitations of memory
storage.
mystruct func1(void);
mystruct *func2(void);
MikroElektronika
/* directly */
/* via a pointer */
216
is of the type M, and represents the member object m in s. The expression ps->m is a convenient shorthand for
(*ps).m.
For example:
struct mystruct {
int i;
char str[21];
double d;
} s, *sptr = &s;
...
s.i = 3;
sptr -> d = 1.23;
The expression s.m is lvalue, providing that s is lvalue and m is not an array type. The expression sptr->m is an lvalue
unless m is an array type.
217
MikroElektronika
//
//
//
//
assign
assign
assign
assign
3 to
2 to
1.23
3.14
the i member of B
the j member of A
to the d member of B
to x member of A
Structure Uniqueness
Each structure declaration introduces a unique structure type, so that in
struct A {
int i,j; double d;
} aa, aaa;
struct B {
int i,j; double d;
} bb;
the objects aa and aaa are both of the type struct A, but the objects aa and bb are of different structure types.
Structures can be assigned only if the source and destination have the same type:
aa = aaa;
aa = bb;
/* but
aa.i =
aa.j =
aa.d =
MikroElektronika
218
Unions
Union types are derived types sharing many of syntactic and functional features of structure types. The key difference
is that a union members share the same memory space.
Note: The mikroC PRO for PIC supports anonymous unions.
Union Declaration
Unions have the same declaration as structures, with the keyword union used instead of struct:
union tag { member-declarator-list };
Unlike structures members, the value of only one of unions members can be stored at any time. Here is a simple
example:
union myunion {
int i;
double d;
char ch;
} mu, *pm;
The identifier mu, of the type myunion, can be used to hold a 2-byte int, 4-byte double or single-byte char, but only
one of them at a certain moment. The identifier pm is a pointer to union myunion.
Size of Union
The size of a union is the size of its largest member. In our previous example, both sizeof(union myunion) and
sizeof(mu) return 4, but 2 bytes are unused (padded) when mu holds the int object, and 3 bytes are unused when
mu holds char.
// OK: mu.i = 3
The third line is legal, since mu.i is an integral type. However, the bit pattern in mu.i corresponds to parts of the
previously assigned double. As such, it probably wont provide an useful integer interpretation.
When properly converted, a pointer to a union points to each of its members, and vice versa.
219
MikroElektronika
MikroElektronika
220
Bit Fields
Bit fields are specified numbers of bits that may or may not have an associated identifier. Bit fields offer a way of
subdividing structures into named parts of user-defined sizes.
Structures and unions can contain bit fields that can be up to 16 bits.
You cannot take the address of a bit field.
Note:
If you need to handle specific bits of 8-bit variables (char and unsigned short) or registers, you dont
need to declare bit fields.
Much more elegant solution is to use the mikroC PRO for dsPIC30/33 and PIC24s intrinsic ability for
individual bit access see Accessing Individual Bits for more information.
} myreg;
Here is an example:
typedef struct
lo_nibble :
hi_nibble :
high_byte :
{
4;
4;
8;} myunsigned;
which declares the structured type myunsigned containing three components: lo_nibble (bits 3..0), hi_nibble
(bits 7..4) and high_byte (bits 15..8).
221
MikroElektronika
...
Value_For_PortB.lo_nibble = 7;
Value_For_PortB.hi_nibble = 0x0C;
Value_For_PortB.high_byte = 0xAA;
PORTB = *(unsigned *) (void *)&Value_For_PortB;
// typecasting :
// 1. address of structure to pointer to void
// 2. pointer to void to pointer to unsigned
// 3. dereferencing to obtain the value
}
Types Conversions
The mikroC PRO for dsPIC30/33 and PIC24 is a strictly typed language, with each operator, statement and function
demanding appropriately typed operands/arguments. However, we often have to use objects of mismatching types in
expressions. In that case, type conversion is needed.
Conversion of object of one type means that objects type is changed into another type. The mikroC PRO for dsPIC30/33
and PIC24 defines a set of standard conversions for built-in types, provided by compiler when necessary. For more
information, refer to the Standard Conversions.
Conversion is required in the following situations:
- if a statement requires an expression of particular type (according to language definition), and we use an
expression of different type,
- if an operator requires an operand of particular type, and we use an operand of different type,
- if a function requires a formal parameter of particular type, and we pass it an object of different type,
- if an expression following the keyword return does not match the declared function return type,
- if intializing an object (in declaration) with an object of different type.
In these situations, compiler will provide an automatic implicit conversion of types, without any programmers interference.
Also, the programmer can demand conversion explicitly by means of the typecast operator. For more information, refer
to the Explicit Typecasting.
MikroElektronika
222
Standard Conversions
Standard conversions are built in the mikroC PRO for dsPIC30/33 and PIC24. These conversions are performed
automatically, whenever required in the program. They can also be explicitly required by means of the typecast operator
(refer to the Explicit Typecasting).
The basic rule of automatic (implicit) conversion is that the operand of simpler type is converted (promoted) to the type
of more complex operand. Then, the type of the result is that of more complex operand.
Arithmetic Conversions
When using arithmetic expression, such as a + b, where a and b are of different arithmetic types, the mikroC PRO
for dsPIC30/33 and PIC24 performs implicit type conversions before the expression is evaluated. These standard
conversions include promotions of lower types to higher types in the interests of accuracy and consistency.
Assigning a signed character object (such as a variable) to an integral object results in automatic sign extension.
Objects of type signed char always use sign extension; objects of type unsigned char always has its high byte set to
zero when converted to int.
Converting a longer integral type to a shorter type truncates the higher order bits and leaves low-order bits unchanged.
Converting a shorter integral type to a longer type either sign-extends or zero-fills the extra bits of the new value,
depending on whether the shorter type is signed or unsigned, respectively.
Note:
Conversion of floating point data into integral value (in assignments or via explicit typecast) produces correct
results only if the float value does not exceed the scope of destination integral type.
In details:
Here are the steps the mikroC PRO for dsPIC30/33 and PIC24 uses to convert the operands in an arithmetic
expression:
First, any small integral types are converted according to the following rules:
1. bit converts to char
2. char converts to int
3. signed char converts to int, with the same value
4. short converts to int, with the same value, sign-extended
5. unsigned short converts to unsigned int, with the same value, zero-filled
6. enum converts to int, with the same value
After this, any two values associated with an operator are either int (including the long and unsigned modifiers) or
float (equivalent with double and long double in the mikroC PRO for dsPIC30/33 and PIC24).
1. If either operand is float, the other operand is converted to float.
2. Otherwise, if either operand is unsigned long, the other operand is converted to unsigned long.
3. Otherwise, if either operand is long, then the other operand is converted to long.
4. Otherwise, if either operand is unsigned, then the other operand is converted to unsigned.
5. Otherwise, both operands are int.
The result of the expression is the same type as that of the two operands.
223
MikroElektronika
/* 2. + 3.1 5.1 */
/* (5/4)*3. 1*3. 1.*3. 3. */
/* (3.*5)/4 (3.*5.)/4 15./4 15./4. 3.75 */
Pointer Conversions
Pointer types can be converted to other pointer types using the typecasting mechanism:
char *str;
int *ip;
str = (char *)ip;
More generally, the cast type* will convert a pointer to type pointer to type.
MikroElektronika
224
Declarations
A declaration introduces one or several names to a program it informs the compiler what the name represents, what
its type is, what operations are allowed with it, etc. This section reviews concepts related to declarations: declarations,
definitions, declaration specifiers, and initialization.
The range of objects that can be declared includes:
- Variables
- Constants
- Functions
- Types
- Structure, union, and enumeration tags
- Structure members
- Union members
- Arrays of other types
- Statement labels
- Preprocessor macros
225
MikroElektronika
Linkage
An executable program is usually created by compiling several independent translation units, then linking the resulting
object files with preexisting libraries. A term translation unit refers to a source code file together with any included files,
but without the source lines omitted by conditional preprocessor directives. A problem arises when the same identifier
is declared in different scopes (for example, in different files), or declared more than once in the same scope.
The linkage is a process that allows each instance of an identifier to be associated correctly with one particular object
or function. All identifiers have one of two linkage attributes, closely related to their scope: external linkage or internal
linkage. These attributes are determined by the placement and format of your declarations, together with an explicit (or
implicit by default) use of the storage class specifier static or extern.
Each instance of a particular identifier with external linkage represents the same object or function throughout the entire
set of files and libraries making up the program. Each instance of a particular identifier with internal linkage represents
the same object or function within one file only.
MikroElektronika
226
Storage Classes
Associating identifiers with objects requires each identifier to have at least two attributes: storage class and type
(sometimes referred to as data type). The mikroC PRO for dsPIC30/33 and PIC24 compiler deduces these attributes
from implicit or explicit declarations in the source code.
A storage class dictates the location (data segment, register, heap, or stack) of object and its duration or lifetime (the
entire running time of the program, or during execution of some blocks of code). A storage class can be established by
the syntax of a declaration, by its placement in the source code, or by both of these factors:
storage-class type identifier
The storage class specifiers in the mikroC PRO for dsPIC30/33 and PIC24 are:
- auto
- register
- static
- extern
227
MikroElektronika
Register
The register storage-class specifier is used to define local variables that should be stored in a register instead of RAM.
At the moment this modifier has no special meaning in mikroC PRO for dsPIC30/33 and PIC24.
mikroC PRO for dsPIC30/33 and PIC24 simply ignores requests for register allocation.
Static
The static storage class specifier lets you define variables or functions with internal linkage, which means that each
instance of a particular identifier represents the same variable or function within one file only.
In addition, variables declared static have static storage duration, which means that memory for these variables is
allocated when the program begins running and is freed when the program terminates.
Static storage duration for a variable is different from file or global scope. A variable can have static duration, but local
scope.
Extern
The extern storage class specifier lets you declare objects that can be used in several source files. An extern declaration
makes a described variable usable by the succeeding part of the current source file.
This declaration does not replace the definition. It is used to describe a variable that is externally defined. An extern
declaration can appear outside a function or at the beginning of a block.
If the declaration describes a function or appears outside a function and describes an object with external linkage, the
keyword extern is optional.
If a declaration for an identifier already exists within the file scope, any extern declaration of the same identifier found
within a block refers to the same object.
If no other declaration for the identifier exists within the file scope, the identifier has external linkage.
See Linkage for more information.
MikroElektronika
228
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 const qualifier is used to indicate that variable value cannot be changed. Its value is set at initialization.
The mikroC PRO for dsPIC30/33 and PIC24 treats objects declared with the const qualifier the same as literals or
preprocessor constants. If the user tries to change an object declared with the const qualifier compiler will report an
error.
For example:
const double PI = 3.14159;
Qualifier volatile
The volatile qualifier indicates that variable values can be changed both with or without users interference in the
program. The compiler should not optimize such variable.
Typedef Specifier
The typedef declaration introduces a name that, within its scope, becomes a synonym for the specified type. You can
use typedef declarations to construct shorter or more meaningful names for types already defined by the language or
declared by the user.
Typedef names allow you to encapsulate implementation details that may change. Unlike the struct, union, and
enum declarations, the typedef declarations do not introduce new types, but new names for existing types.
The specifier typedef stands first in the declaration:
typedef <type_definition> synonym;
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 mikroC PRO for dsPIC30/33 and PIC24.
229
MikroElektronika
*Pti, Array[10];
Here, Pti is a synonym for type pointer to int, and Array is a synonym for type array of 10 int elements.
asm Declaration
The mikroC PRO for dsPIC30/33 and PIC24 allows embedding assembly in the source code by means of the asm
declaration. The declarations _asm and __asm are also allowed in the mikroC PRO for dsPIC30/33 and PIC24 and
have the same meaning. Note that numerals cannnot be used as absolute addresses for SFR or GPR variables in
assembly instructions. Symbolic names may be used instead (listing will display these names as well as addresses).
Assembly instructions can be grouped by the asm keyword (or _asm, or __asm):
asm {
block of assembly instructions
}
The mikroC PRO for dsPIC30/33 and PIC24 comments (both single-line and multi-line) are allowed in embedded
assembly code.
The only types whose name remains the same in asm as it is in the mikroC PRO for dsPIC30/33 and PIC24 are
registers, e.g. INTCON, PORTB, WREG, GIE, etc.
Accessing variables
Depending on the place of declaration, accessing a variable can be done in several ways:
- Accessing global variable:
1. If declared as static (visible only in the file where it was declared):
<source_file_name>_<variable_name>.
2. If declared as a non-static global (visible throughout the whole project): _<variable_name>.
3. If accessing registers (declared through register, rx or sfr specifiers, visible throughout the whole
project) : <variable_name>.
- Accessing local variable: <routine_name>_<variable_name>.
- Accessing routine parameter: FARG_<routine_name>_<variable_name>.
MikroElektronika
230
231
MikroElektronika
Initialization
The initial value of a declared object can be set at the time of declaration (initialization). A part of the declaration which
specifies the initialization is called initializer.
Initializers for globals and static objects must be constants or constant expressions. The initializer for an automatic
object can be any legal expression that evaluates to an assignment-compatible value for the type of the variable
involved.
Scalar types are initialized with a single expression, which can optionally be enclosed in braces. The initial value of an
object is that of the expression; the same constraints for type and conversions as for simple assignments are applied
to initializations too.
For example:
int i = 1;
char *s = hello;
struct complex c = {0.1, -0.2};
// where complex is a structure (float, float)
For structures or unions with automatic storage duration, the initializer must be one of the following:
- An initializer list.
- A single expression with compatible union or structure type. In this case, the initial value of the object is
that of the expression.
For example:
struct dot {int x; int y; } m = {30, 40};
For more information, refer to Structures and Unions.
Also, you can initialize arrays of character type with a literal string, optionally enclosed in braces. Each character in the
string, including the null terminator, initializes successive elements in the array. For more information, refer to Arrays.
Automatic Initialization
The mikroC PRO for dsPIC30/33 and PIC24 does not provide automatic initialization for objects. Uninitialized globals
and objects with static duration will take random values from memory.
MikroElektronika
232
Functions
Functions are central to C programming. Functions are usually defined as subprograms which return a value based
on a number of input parameters. Return value of the function can be used in expressions technically, function call is
considered to be an expression like any other.
C allows a function to create results other than its return value, referred to as side effects. Often, the function return value
is not used at all, depending on the side effects. These functions are equivalent to procedures of other programming
languages, such as Pascal. C does not distinguish between procedure and function functions play both roles.
Each program must have a single external function named main marking the entry point of the program. Functions
are usually declared as prototypes in standard or user-supplied header files, or within program files. Functions have
external linkage by default and are normally accessible from any file in the program. This can be restricted by using the
static storage class specifier in function declaration (see Storage Classes and Linkage).
Note:
Check the dsPIC30/33 and PIC24 Specifics for more information on functions limitations on the dsPIC30/33
and PIC24 MCUs.
Function Declaration
Functions are declared in users source files or made available by linking precompiled libraries. The declaration syntax
of the function is:
type function_name(parameter-declarator-list);
The function_name must be a valid identifier. This name is used to call the function; see Function Calls for more
information.
type represents the type of function result, and can be of any standard or user-defined type. For functions that do not
return value the void type should be used. The type can be omitted in global function declarations, and function will
assume the int type by default.
Function type can also be a pointer. For example, float* means that a function result is a pointer to float. The generic
pointer void* is also allowed.
The function cannot return an array or another function.
Within parentheses, parameter-declarator-list is a list of formal arguments that function takes. These
declarators specify the type of each function parameter. The compiler uses this information to check validity of function
calls. If the list is empty, a function does not take any arguments. Also, if the list is void, a function also does not take
any arguments; note that this is the only case when void can be used as an arguments type.
Unlike variable declaration, each argument in the list needs its own type specifier and possible qualifier const or
volatile.
233
MikroElektronika
Function prototypes are very useful in documenting code. For example, the function Cf_Init takes two parameters:
Control Port and Data Port. The question is, which is which? The function prototype:
void Cf_Init(char *ctrlport, char *dataport);
makes it clear. If a header file contains function prototypes, the user can read that file to get the information needed
for writing programs that call these functions. If a prototype parameter includes an identifier, then the indentifier is only
used for error checking.
Function Definition
Function definition consists of its declaration and function body. The function body is technically a block a
sequence of local definitions and statements enclosed within braces {}. All variables declared within function body are
local to the function, i.e. they have function scope.
The function itself can be defined only within the file scope, which means that function declarations cannot be nested.
To return the function result, use the return statement. The statement return in functions of the void type cannot have
a parameter in fact, the return statement can be omitted altogether if it is the last statement in the function body.
Here is a sample function definition:
/* function max returns greater one of its 2 arguments: */
int max(int x, int y) {
return (x>=y) ? x : y;
}
MikroElektronika
234
Functions reentrancy
Functions reentrancy is allowed. Remember that the dsPICs and PIC24 has stack and memory limitations which can
varies greatly between MCUs.
235
MikroElektronika
Argument Conversions
If a function prototype has not been previously declared, the mikroC PRO for dsPIC30/33 and PIC24 converts integral
arguments to a function call according to the integral widening (expansion) rules described in Standard Conversions. If
a function prototype is in scope, the mikroC PRO for dsPIC30/33 and PIC24 converts the passed argument to the type
of the declared parameter according to the same conversion rules as in assignment statements.
If a prototype is present, the number of arguments must match. The types need to be compatible only to the extent that
an assignment can legally convert them. The user can always use an explicit cast to convert an argument to a type that
is acceptable to a function prototype.
Note:
If the function prototype does not match the actual function definition, the mikroC PRO for dsPIC30/33 and
PIC24 will detect this if and only if that definition is in the same compilation unit as the prototype.
If you create a library of routines with the corresponding header file of prototypes, consider including that
header file when you compile the library, so that any discrepancies between the prototypes and actual
definitions will be detected.
The compiler is also able to force arguments to change their type to a proper one. Consider the following code:
int limit = 32;
char ch = A;
long res;
// prototype
extern long func(long par1, long par2);
main() {
...
res = func(limit, ch);
}
// function call
Since the program has the function prototype for func, it converts limit and ch to long, using the standard rules of
assignment, before it places them on the stack for the call to func.
Without the function prototype, limit and ch would be placed on the stack as an integer and a character, respectively;
in that case, the stack passed to func will not match size or content that func expects, which can cause problems.
MikroElektronika
236
237
MikroElektronika
Operators
Operators are tokens that trigger some computation when applied to variables and other objects in an expression.
- Arithmetic Operators
- Assignment Operators
- Bitwise Operators
- Logical Operators
- Reference/Indirect Operators
- Relational Operators
- Structure Member Selectors
- Comma Operator ,
- Conditional Operator ? :
- Array subscript operator []
- Function call operator ()
- sizeof Operator
- Preprocessor Operators # and ##
MikroElektronika
238
Operands
Operators
15
()
14
!
~
++
sizeof
13
12
11
<<
10
<
==
&
&&
||
?:
=
|=
[]
Asociativity
->
--
&
(type)
>>
<=
>
>=
!=
*=
/=
%=
<<=
>>=
+=
-=
&=
^=
Note: Operator * is context sensitive and can also represent the pointer reference operator.
239
MikroElektronika
Remainder operand % works only with integers; the sign of result is equal to the sign of the first operand:
/* for example:
9 % 3;
7 % 3;
-7 % 3;
*/
/* equals 0 */
/* equals 1 */
/* equals -1 */
/* k = k + 1, j = k, which gives us j = 6, k = 6 */
but:
int j = 5;
j = k++;
MikroElektronika
/* j = k, k = k + 1, which gives us j = 5, k = 6 */
240
Relational Operators
Use relational operators to test equality or inequality of expressions. If an expression evaluates to be true, it returns 1;
otherwise it returns 0.
All relational operators associate from left to right.
Operation
Precedence
==
equal
!=
not equal
>
greater than
10
<
less than
10
>=
<=
10
Do not forget that relational operators return either 0 or 1. Consider the following examples:
/* ok: */
5 > 7
10 <= 20
/* returns 0 */
/* returns 1 */
241
MikroElektronika
Bitwise Operators
Use the bitwise operators to modify individual bits of numerical operands.
Bitwise operators associate from left to right. The only exception is the bitwise complement operator ~ which associates
from right to left.
Operation
Precedence
&
<<
>>
14
Bitwise operators &, | and ^ perform logical operations on the appropriate pairs of bits of their operands. Operator ~
complements each bit of its operand. For example:
0x1234 & 0x5678
/* equals 0x1230 */
/* because ..
0x1234 : 0001 0010 0011 0100
0x5678 : 0101 0110 0111 1000
---------------------------&
: 0001 0010 0011 0000
.. that is, 0x1230 */
MikroElektronika
242
/* equals 0x567C */
/* equals 0x444C */
/* equals 0xEDCB */
Note: Operator & can also be a pointer reference operator. Refer to Pointers for more information.
000001 <<
0x3801 <<
5;
4;
/* equals 000040 */
/* equals 0x8010, overflow! */
With shift right (>>), far right bits are discarded and the freed bits on the left are assigned zeroes (in case of unsigned
operand) or the value of a sign bit (in case of signed operand). Shifting operand to the right by n positions is equivalent
to dividing it by 2n.
0xFF56 >>
0xFF56u >>
4;
4;
/* equals 0xFFF5 */
/* equals 0x0FF5 */
/* equals 000000 */
/* equals 1 */
~ 0x1234;
! 0x1234;
/* equals 0xEDCB */
/* equals 0 */
243
MikroElektronika
Logical Operators
Operands of logical operations are considered true or false, that is non-zero or zero. Logical operators always return 1
or 0. Operands in a logical expression must be of scalar type.
Logical operators && and || associate from left to right. Logical negation operator ! associates from right to left.
Operation
Precedence
&&
logical AND
||
logical OR
logical negation
14
Logical Operations
&&
||
Precedence of logical, relational, and arithmetic operators was designated in such a way to allow complex expressions
without parentheses to have an expected meaning:
c >= 0 && c <= 9;
a + 1 == b || ! f(x);
Logical AND && returns 1 only if both expressions evaluate to be nonzero, otherwise returns 0. If the first expression
evaluates to false, the second expression will not be evaluated. For example:
a > b && c < d;
/* reads as (a > b) && (c < d) */
/* if (a > b) is false (0), (c < d) will not be evaluated */
Logical OR || returns 1 if either of expression evaluates to be nonzero, otherwise returns 0. If the first expression
evaluates to true, the second expression is not evaluated. For example:
a && b || c && d; /* reads as: (a && b) || (c && d) */
/* if (a && b) is true (1), (c && d) will not be evaluated */
MikroElektronika
244
/* equals 000000 */
/* equals 1 */
~ 0x1234
! 0x1234
/* equals 0xEDCB */
/* equals 0 */
Conditional Operator ? :
The conditional operator ? : is the only ternary operator in C. Syntax of the conditional operator is:
expression1 ? expression2 : expression3
The expression1 is evaluated first. If its value is true, then expression2 evaluates and expression3 is ignored.
If expression1 evaluates to false, then expression3 evaluates and expression2 is ignored. The result will be a
value of either expression2 or expression3 depending upon which of them evaluates.
Conditional operator associates from right to left.
Note: The fact that only one of these two expressions evaluates is very important if they are expected to produce side effects!
Here are a couple of practical examples:
/* Find max(a, b): */
max = ( a > b ) ? a : b;
/* Convert small letter to capital: */
/* (no parentheses are actually necessary) */
c = ( c >= a && c <= z ) ? ( c - 32 ) : c;
245
MikroElektronika
Assignment Operators
Unlike many other programming languages, C treats value assignment as operation (represented by an operator)
rather than instruction.
Assignment Rules
For both simple and compound assignment, the operands expression1 and expression2 must obey one of the
following rules:
1. expression1 is of qualified or unqualified arithmetic type and expression2 is of arithmetic type.
2. expression1 has a qualified or unqualified version of structure or union type compatible with the type of
expression2.
3. expression1 and expression2 are pointers to qualified or unqualified versions of compatible types
and the type pointed to by left has all qualifiers of the type pointed to by right.
MikroElektronika
246
Unary Operators
Unary operators are operators that take exactly one argument.
Operation
Precedence
14
14
++
--
For example:
int j = 5;
j = ++k;
/* k = k + 1, j = k, which gives us j = 6, k = 6 */
but:
int j = 5;
j = k++;
247
/* j = k, k = k + 1, which gives us j = 5, k = 6 */
MikroElektronika
Operation
Precedence
logical negation
14
Operation
Precedence
Operation
Precedence
&
14
Example:
int *p_to_y;
int y;
p_to_y = &y;
*p_to_y = 3;
Note: Besides these, sizeof and casting unary operators are supported also.
MikroElektronika
248
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.
/* returns 1 */
/* returns 2 */
/* returns 4 */
/* 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):
int i, j, a[10];
...
j = sizeof(a[1]);
i = sizeof(a);
/* j = sizeof(int) = 2 */
/* i = 10*sizeof(int) = 20 */
249
MikroElektronika
Expressions
Expression is a sequence of operators, operands, and punctuators that specifies a computation. Formally, expressions
are defined recursively: subexpressions can be nested without formal limit. However, the compiler will report an out-ofmemory error if it cant compile an expression that is too complex.
In ANSI C, the primary expressions are: constant (also referred to as literal), identifier, and (expression), defined
recursively.
Expressions are evaluated according to a certain conversion, grouping, associativity and precedence rules, which
depends on the operators used, 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 the mikroC
PRO for dsPIC30/33 and PIC24.
Expressions can produce lvalue, rvalue, or no value. Expressions might cause side effects whether they produce a
value or not.
Comma Expressions
One of the specifics of C is that it allows using of comma as a sequence operator to form so-called comma expressions
or sequences. Comma expression is a comma-delimited list of expressions it is formally treated as a single expression
so it can be used in places where an expression is expected. The following sequence:
expression_1, expression_2;
results in the left-to-right evaluation of each expression, with the value and type of expression_2 giving the result
of the whole expression. Result of expression_1 is discarded.
Binary operator comma (,) has the lowest precedence and associates from left to right, so that a, b, c is the same
as (a, b), c. This allows writing sequences with any number of expressions:
expression_1, expression_2, ... expression_n;
which results in the left-to-right evaluation of each expression, with the value and type of expression_n giving the
result of the whole expression. Results of other expressions are discarded, but their (possible) side-effect do occur.
For example:
result = ( a = 5, b /= 2, c++ );
/* returns preincremented value of variable c,
but also intializes a, divides b by 2 and increments c */
result = ( x = 10, y = x + 3, x--, z -= x * 3 - --y );
/* returns computed value of variable z,
and also computes x and y */
MikroElektronika
250
Statements
Statements specify a flow of control as the program executes. In the absence of specific jump and selection statements,
statements are executed sequentially in the order of appearance in the source code.
Statements can be roughly divided into:
- Labeled Statements
- Expression Statements
- Selection Statements
- Iteration Statements (Loops)
- Jump Statements
- Compound Statements (Blocks)
Labeled Statements
Each statement in a program can be labeled. A label is an identifier added before the statement like this:
label_identifier: statement;
There is no special declaration of a label it just tags the statement. Label_identifier has a function scope and
the same label cannot be redefined within the same function.
Labels have their own namespace: label identifier can match any other identifier in the program.
A statement can be labeled for two reasons:
1. The label identifier serves as a target for the unconditional goto statement,
2. The label identifier serves as a target for the switch statement. For this purpose, only case and default
labeled statements are used:
case constant-expression : statement
default : statement
251
MikroElektronika
Expression Statements
Any expression followed by a semicolon forms an expression statement:
expression;
The mikroC PRO for dsPIC30/33 and PIC24 executes an expression statement by evaluating the expression. All side
effects from this evaluation are completed before the next statement starts executing. Most of expression statements
are assignment statements or function calls.
A null statement is a special case, consisting of a single semicolon (;). The null statement does nothing, and therefore
is useful in situations where the mikroC PRO for dsPIC30/33 and PIC24 syntax expects a statement but the program
does not need one. For example, a null statement is commonly used in empty loops:
for (; *q++ = *p++ ;);
Selection Statements
Selection or flow-control statements select one of alternative courses of action by testing certain values. There are two
types of selection statements:
- if
- switch
If Statement
The if statement is used to implement a conditional statement. The syntax of the if statement is:
if (expression) statement1 [else statement2]
If expression evaluates to true, statement1 executes. If expression is false, statement2 executes. The
expression must evaluate to an integral value; otherwise, the condition is ill-formed. Parentheses around the
expression are mandatory.
The else keyword is optional, but no statements can come between if and else.
Nested If statements
Nested if statements require additional attention. A general rule is that the nested conditionals are parsed starting from
the innermost conditional, with each else bound to the nearest available if on its left:
if (expression1) statement1
else if (expression2)
if (expression3) statement2
else statement3
/* this belongs to: if (expression3) */
else statement4
/* this belongs to: if (expression2) */
MikroElektronika
252
#if and #else preprocessor statements (directives) look similar to if and else statements, but have
very different effects. They control which source file lines are compiled and which are ignored.
Switch Statement
The switch statement is used to pass control to a specific program branch, based on a certain condition. The syntax
of the switch statement is:
switch (expression) {
case constant-expression_1 : statement_1;
.
.
.
case constant-expression_n : statement_n;
[default : statement;]
}
First, the expression (condition) is evaluated. The switch statement then compares it to all available constantexpressions following the keyword case. If a match is found, switch passes control to that matching case causing
the statement following the match evaluates. Note that constant-expressions must evaluate to integer. It is not
possible to have two same constant expressions evaluating to the same value.
Parentheses around expression are mandatory.
Upon finding a match, program flow continues normally: the following instructions will be executed in natural order
regardless of the possible case label. If no case satisfies the condition, the default case evaluates (if the label
default is specified).
For example, if a variable i has value between 1 and 3, the following switch would always return it as 4:
switch
case
case
case
}
(i) {
1: i++;
2: i++;
3: i++;
To avoid evaluating any other cases and relinquish control from switch, each case should be terminated with break.
Here is a simple example with switch. Suppose we have a variable phase with only 3 different states (0, 1, or 2) and a
corresponding function (event) for each of these states. This is how we could switch the code to the appopriate routine:
switch (phase) {
case 0: Lo(); break;
case 1: Mid(); break;
case 2: Hi(); break;
default: Message(Invalid state!);
}
253
MikroElektronika
While Statement
The while keyword is used to conditionally iterate a statement. The syntax of the while statement is:
while (expression) statement
The statement executes repeatedly until the value of expression is false. The test takes place before statement
is executed. Thus, if expression evaluates to false on the first pass, the loop does not execute. Note that parentheses
around expression are mandatory.
Here is an example of calculating scalar product of two vectors, using the while statement:
int s = 0, i = 0;
while (i < n) {
s += a[i] * b[i];
i++;
}
Note that body of the loop can be a null statement. For example:
while (*q++ = *p++);
Do Statement
The do statement executes until the condition becomes false. The syntax of the do statement is:
do statement while (expression);
The statement is executed repeatedly as long as the value of expression remains non-zero. The expression is
evaluated after each iteration, so the loop will execute statement at least once.
Parentheses around expression are mandatory.
MikroElektronika
254
For Statement
The for statement implements an iterative loop. The syntax of the for statement is:
for ([init-expression]; [condition-expression]; [increment-expression]) statement
Before the first iteration of the loop, init-expression sets the starting variables for the loop. You cannot pass
declarations in init-expression.
condition-expression is checked before the first entry into the block; statement is executed repeatedly until the
value of condition-expression is false. After each iteration of the loop, increment-expression increments a
loop counter. Consequently, i++ is functionally the same as ++i.
All expressions are optional. If condition-expression is left out, it is assumed to be always true. Thus, empty
for statement is commonly used to create an endless loop in C:
for ( ; ; ) statement
The only way to break out of this loop is by means of the break statement.
Here is an example of calculating scalar product of two vectors, using the for statement:
for ( s = 0, i = 0; i < n; i++ ) s += a[i] * b[i];
There is another way to do this:
for ( s = 0, i = 0; i < n; s += a[i] * b[i], i++ );
but it is considered a bad programming style. Although legal, calculating the sum should not be a part of the incrementing
expression, because it is not in the service of loop routine. Note that null statement (;) is used for the loop body.
255
MikroElektronika
Jump Statements
The jump statement, when executed, transfers control unconditionally. There are four such statements in the mikroC
PRO for dsPIC30/33 and PIC24:
- break
- continue
- goto
- return
Continue Statement
The continue statement within loops is used to skip the cycle. It passes control to the end of the innermost enclosing
end brace belonging to a looping construct. At that point the loop continuation condition is re-evaluated. This means
that continue demands the next iteration if the loop continuation condition is true.
Specifically, the continue statement within the loop will jump to the marked position as it is shown below:
while (..) {
...
if (val>0) continue;
...
// continue jumps here
}
MikroElektronika
do {
...
if (val>0) continue;
...
// continue jumps here
while (..);
for (..;..;..) {
...
if (val>0) continue;
...
// continue jumps here
}
256
Goto Statement
The goto statement is used for unconditional jump to a local label for more information on labels, refer to Labeled
Statements. The syntax of the goto statement is:
goto label_identifier;
This will transfer control to the location of a local label specified by label_identifier. The label_identifier has
to be a name of the label within the same function in which the goto statement is. The goto line can come before or
after the label.
goto is used to break out from any level of nested control structures but it cannot be used to jump into block while
skipping that blocks initializations for example, jumping into loops body, etc.
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 (...) {
for (...) {
...
if (disaster) goto Error;
...
}
}
.
.
.
Error: /* error handling code */
Return Statement
The return statement is used to exit from the current function back to the calling routine, optionally returning a value.
The syntax is:
return [expression];
This will evaluate expression and return the result. Returned value will be automatically converted to the expected
function type, if needed. The expression is optional; if omitted, the function will return a random value from
memory.
Note:
257
The statement return in functions of the void type cannot have expression in fact, the return
statement can be omitted altogether if it is the last statement in the function body.
MikroElektronika
Preprocessor
Preprocessor is an integrated text processor which prepares the source code for compiling. Preprocessor allows:
- inserting text from a specifed file to a certain point in the code (see File Inclusion),
- replacing specific lexical symbols with other symbols (see Macros),
- conditional compiling which conditionally includes or omits parts of the code (see Conditional Compilation).
Note that preprocessor analyzes text at token level, not at individual character level. Preprocessor is controled by
means of preprocessor directives and preprocessor operators.
Preprocessor Directives
Any line in the source code with a leading # is taken as a preprocessing directive (or control line), unless # is within
a string literal, in a character constant, or embedded in a comment. The initial # can be preceded or followed by a
whitespace (excluding new lines).
A null directive consists of a line containing the single character #. This line is always ignored.
Preprocessor directives are usually placed at the beginning of the source code, but they can legally appear at any point
in a program. The mikroC PRO for dsPIC30/33 and PIC24 preprocessor detects preprocessor directives and parses the
tokens embedded in them. A directive is in effect from its declaration to the end of the program file.
Here is one commonly used directive:
#include <math.h>
MikroElektronika
258
#if
#ifdef
#ifndef
#include
#line
#undef
Macros
Macros provide a mechanism for a token replacement, prior to compilation, with or without a set of formal, function-like
parameters.
259
MikroElektronika
MikroElektronika
260
Undefining Macros
The #undef directive is used to undefine a macro.
#undef macro_identifier
The directive #undef detaches any previous token sequence from macro_identifier; the macro definition has been
forgotten, and macro_identifier is undefined. No macro expansion occurs within the #undef lines.
The state of being defined or undefined is an important property of an identifier, regardless of the actual definition. The
#ifdef and #ifndef conditional directives, used to test whether any identifier is currently defined or not, offer a
flexible mechanism for controlling many aspects of a compilation.
After a macro identifier has been undefined, it can be redefined with #define, using the same or different token
sequence.
File Inclusion
The preprocessor directive #include pulls in header files (extension .h) into the source code. Do not rely on
preprocessor to include source files (extension .c) see Add/Remove Files from Project for more information.
The syntax of the #include directive has two formats:
#include <header_name>
#include header_name
261
MikroElektronika
Explicit Path
By placing an explicit path in header_name, only that directory will be searched. For example:
#include C:\my_files\test.h
Note
There is also a third version of the #include directive, rarely used, which assumes that neither < nor appear as the
first non-whitespace character following #include:
#include macro_identifier
It assumes that macro definition that will expand macro identifier into a valid delimited header name with either
<header_name> or header_name formats exists.
MikroElektronika
262
Preprocessor Operators
The # (pound sign) is a preprocessor directive when it occurs as the first non-whitespace character on a line. Also, #
and ## perform operator replacement and merging during the preprocessor scanning phase.
Operator #
In C preprocessor, a character sequence enclosed by quotes is considered a token and its content is not analyzed. This
means that macro names within quotes are not expanded.
If you need an actual argument (the exact sequence of characters within quotes) as a result of preprocessing, use the #
operator in macro body. It can be placed in front of a formal macro argument in definition in order to convert the actual
argument to a string after replacement.
For example, lets have macro LCD_PRINT for printing variable name and value on Lcd:
#define LCD_PRINT(val) Lcd_Out_Cp(#val : ); \
Lcd_Out_Cp(IntToStr(val));
Now, the following code,
LCD_PRINT(temp)
will be preprocessed to this:
Lcd_Out_Cp(temp : ); Lcd_Out_Cp(IntToStr(temp));
Operator ##
Operator ## is used for token pasting. Two tokens can be pasted(merged) together by placing ## in between them
(plus optional whitespace on either side). The preprocessor removes whitespace and ##, combining the separate
tokens into one new token. This is commonly used for constructing identifiers.
For example, see the definition of macro SPLICE for pasting two tokens into one identifier:
#define SPLICE(x,y) x ## _ ## y
Now, the call SPLICE(cnt, 2) will expand to the identifier cnt_2.
Note:
The mikroC PRO for dsPIC30/33 and PIC24 does not support the older nonportable method of token pasting
using (l/**/r).
263
MikroElektronika
Conditional Compilation
Conditional compilation directives are typically used to make source programs easy to change and easy to compile
in different execution environments. The mikroC PRO for dsPIC30/33 and PIC24 supports conditional compilation by
replacing the appropriate source-code lines with a blank line.
All conditional compilation directives must be completed in the source or include file in which they have begun.
MikroElektronika
264
265
MikroElektronika
CHAPTER 9
mikroC PRO for dsPIC30/33 and
PIC24 Libraries
mikroC PRO for dsPIC30/33 and PIC24 provides a set of libraries which simplify the initialization and use of dsPIC30/33
and PIC24 and their modules:
Use Library manager to include mikroC PRO for dsPIC30/33 and PIC24 Libraries in you project.
MikroElektronika
266
Hardware Libraries
- ADC Library
- CAN Library
- CANSPI Library
- Compact Flash Library
- Enhanced CAN Library
- EEPROM Library
- Epson S1D13700 Graphic Lcd Library
- Flash Memory Library
- Graphic Lcd Library
- IC Library
- Keypad Library
- Lcd Library
- Manchester Code Library
- Multi Media Card Library
- OneWire Library
- Peripheral Pin Select Library
- Port Expander Library
- PS/2 Library
- PWM Library
- PWM Motor Library
- RS-485 Library
- Software IC 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
267
MikroElektronika
Miscellaneous Libraries
- Button Library
- Conversions Library
- PrintOut Library
- Setjmp Library
- Sprint Library
- Time Library
- Trigonometry Library
- See also Built-in Routines.
MikroElektronika
268
Hardware Libraries
- ADC Library
- CAN Library
- CANSPI Library
- Compact Flash Library
- DSP Libraries
- Enhanced CAN Library
- EEPROM Library
- Epson S1D13700 Graphic Lcd Library
- Flash Memory Library
- Graphic Lcd Library
- IC Library
- Keypad Library
- Lcd Library
- Manchester Code Library
- Multi Media Card Library
- OneWire Library
- Peripheral Pin Select Library
- Port Expander Library
- PS/2 Library
- PWM Library
- PWM Motor Library
- RS-485 Library
- Software IC Library
- Software SPI Library
- Software UART Library
- Sound Library
- SPI Library
- SPI Ethernet Library
- SPI Ethernet ENC24J600 Library
- SPI Graphic Lcd Library
- SPI Lcd Library
- SPI Lcd8 Library
- SPI T6963C Graphic Lcd Library
- T6963C Graphic Lcd Library
- TFT Display Library
- Touch Panel Library
- Touch Panel TFT Library
- UART Library
- USB Library
ADC Library
ADC (Analog to Digital Converter) module is available with a number of dsPIC30/33 and PIC24 MCU modules.
ADC is an electronic circuit that converts continuous signals to discrete digital numbers. ADC Library provides you a
comfortable work with the module.
269
MikroElektronika
ADCx_Init
Prototype
void ADCx_Init();
Description This routines configures ADC module to work with default settings.
The internal ADC module is set to:
- single channel conversion
- 10-bit conversion resolution
- unsigned integer data format
- auto-convert
- VRef+ : AVdd, VRef- : AVss
- instruction cycle clock
- conversion clock : 32*Tcy
- auto-sample time : 31TAD
Parameters None.
Returns
Nothing.
Requires
Example
ADC1_Init();
Notes
- Number of ADC modules per MCU differs from chip to chip. Please, read the appropriate
datasheet before utilizing this library.
MikroElektronika
270
Description This routine configures the internal ADC module to work with user defined settings.
Parameters - ADCMode: resolution of the ADC module.
- Reference: voltage reference used in ADC process.
Description
10-bit resolution
_ADC_10bit
12-bit resolution
_ADC_12bit
Voltage reference
Internal voltage reference
_ADC_INTERNAL_REF
_ADC_EXTERNAL_REF
Returns
Nothing.
Requires
Example
Notes
- Number of ADC modules per MCU differs from chip to chip. Please, read the appropriate
datasheet before utilizing this library.
- Not all MCUs support advanced configuration. Please, read the appropriate datasheet
before utilizing this library.
271
MikroElektronika
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
Requires
Example
unsigned adc_value;
...
adc_value = ADC1_Get_Sample(10);
channel 10
Notes
- Number of ADC modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
- The function sets the appropriate bit in the ADPCFG registers to enable analog function of the
chosen pin.
- Refer to the appropriate Datasheet for channel-to-pin mapping.
ADCx_Read
Prototype
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 or 12-bit (depending on the MCU) unsigned value from the specified channel.
Requires
Example
unsigned adc_value;
...
adc_value = ADC1_Read(10);
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
272
Nothing.
Requires
Example
Notes
None.
Library Example
This code snippet reads analog value from the channel 1 and sends readings as a text over UART1.
Copy Code To Clipboard
unsigned adcRes;
char txt[6];
void main() {
PORTB = 0x0000;
TRISB.F1 = 1;
ADC1_Init();
UART1_Init(9600);
while (1) {
adcRes = ADC1_Get_Sample(1);
WordToStr(adcRes, txt);
UART1_Write_Text(txt);
Delay_ms(50);
}
}
273
MikroElektronika
ADC HW connection
MikroElektronika
274
CAN Library
The mikroC PRO for dsPIC30/33 and PIC24 provides a library (driver) for working with the dsPIC30F CAN module.
The CAN is a very robust protocol that has error detection and signalization, selfchecking and fault confinement.
Faulty CAN data and remote frames are re-transmitted automatically, similar to the Ethernet.
Data transfer rates depend on distance. For example, 1 Mbit/s can be achieved at network lengths below 40m while
250 Kbit/s can be achieved at network lengths below 250m. The greater distance the lower maximum bitrate that can
be achieved. The lowest bitrate defined by the standard is 200Kbit/s. Cables used are shielded twisted pairs.
CAN supports two message formats:
- Standard format, with 11 identifier bits and
- Extended format, with 29 identifier bits
Important:
- Consult the CAN standard about CAN bus termination resistance.
- CAN library routines require you to specify the module you want to use. To use the desired CAN module,
simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of CAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet before
utilizing this library.
Library Routines
- CANxSetOperationMode
- CANxGetOperationMode
- CANxInitialize
- CANxSetBaudRate
- CANxSetMask
- CANxSetFilter
- CANxRead
- CANxWrite
275
MikroElektronika
Nothing.
Requires
Example
//
set
the
CAN1
module
into
configuration
CAN1SetOperationMode until this mode is set)
CAN1SetOperationMode(_CAN_MODE_CONFIG, 0xFF);
mode
(wait
inside
Notes
- CAN library routine require you to specify the module you want to use. To use the desired CAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of CAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
CANxGetOperationMode
Prototype
Description The function returns current operation mode of the CAN module. See CAN_OP_MODE constants
or device datasheet for operation mode codes.
Parameters None.
Returns
Requires
Example
Notes
- CAN library routine require you to specify the module you want to use. To use the desired CAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of CAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
276
void CANxInitialize(unsigned int SJW, unsigned int BRP, unsigned int PHSEG1,
unsigned int PHSEG2, unsigned int PROPSEG, unsigned int CAN_CONFIG_FLAGS);
Nothing.
Requires
Example
// initialize the CAN1 module with appropriate baud rate and message
acceptance flags along with the sampling rules
unsigned int can_config_flags;
...
can_config_flags = _CAN_CONFIG_SAMPLE_THRICE & // Form value to be used
_CAN_CONFIG_PHSEG2_PRG_ON &
// with
CAN1Initialize
_CAN_CONFIG_STD_MSG &
_CAN_CONFIG_DBL_BUFFER_ON &
_CAN_CONFIG_MATCH_MSG_TYPE &
_CAN_CONFIG_LINE_FILTER_OFF;
CAN1Initialize(1,3,3,3,1,can_config_flags); // initialize the CAN1 module
Notes
277
MikroElektronika
void CANxSetBaudRate(unsigned int SJW, unsigned int BRP, unsigned int PHSEG1,
unsigned int PHSEG2, unsigned int PROPSEG, unsigned int CAN_CONFIG_FLAGS);
Description Sets CAN baud rate. Due to complexity of the CAN protocol, you can not simply force a bps value.
Instead, use this function when CAN is in Config mode. Refer to datasheet for details.
SAM, SEG2PHTS and WAKFIL bits are set according to CAN_CONFIG_FLAGS value. Refer to
datasheet for details.
Parameters - SJW as defined in MCUs datasheet (CAN Module)
- BRP as defined in MCUs datasheet (CAN Module)
- PHSEG1 as defined in MCUs datasheet (CAN Module)
- PHSEG2 as defined in MCUs datasheet (CAN Module)
- PROPSEG as defined in MCUs datasheet (CAN Module)
- CAN_CONFIG_FLAGS is formed from predefined constants. See CAN_CONFIG_FLAGS constants.
Returns
Nothing.
Requires
Example
- CAN library routine require you to specify the module you want to use. To use the desired CAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of CAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
278
Description Function sets mask for advanced filtering of messages. Given value is bit adjusted to appropriate
buffer mask registers.
Parameters - CAN_MASK: CAN module mask number. Valid values: CAN_MASK constants. See CAN_MASK
constants.
- val: mask register value. This value is bit-adjusted to appropriate buffer mask registers
- CAN_CONFIG_FLAGS: selects type of message to filter. Valid values:
- _CAN_CONFIG_ALL_VALID_MSG,
- _CAN_CONFIG_MATCH_MSG_TYPE & _CAN_CONFIG_STD_MSG,
- _CAN_CONFIG_MATCH_MSG_TYPE & _CAN_CONFIG_XTD_MSG.
See CAN_CONFIG_FLAGS constants.
Returns
Nothing.
Requires
Example
Notes
279
- CAN library routine require you to specify the module you want to use. To use the desired CAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of CAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
Description Function sets message filter. Given value is bit adjusted to appropriate buffer mask registers.
Parameters - CAN_FILTER: CAN module filter number. Valid values: CAN_FILTER constants. See CAN_FILTER
constants.
- val: filter register value. This value is bit-adjusted to appropriate filter registers
- CAN_CONFIG_FLAGS: selects type of message to filter. Valid values: _CAN_CONFIG_STD_MSG and
_CAN_CONFIG_XTD_MSG. See CAN_CONFIG_FLAGS constants.
Returns
Nothing.
Requires
Example
Notes
- CAN library routine require you to specify the module you want to use. To use the desired CAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of CAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
280
unsigned int CANxRead(unsigned long *id, char *data_, unsigned int *dataLen,
unsigned int *CAN_RX_MSG_FLAGS);
Description If at least one full Receive Buffer is found, it will be processed in the following way :
- Message ID is retrieved and stored to location pointed by id pointer
- Message data is retrieved and stored to array pointed by data pointer
- Message length is retrieved and stored to location pointed by dataLen pointer
- Message flags are retrieved and stored to location pointed by CAN_RX_MSG_FLAGS pointer
Parameters - id: message identifier address
- data: an array of bytes up to 8 bytes in length
- dataLen: data length address
- CAN_RX_MSG_FLAGS: message flags address. For message receive flags format refer to CAN_RX_
MSG_FLAGS constants. See CAN_RX_MSG_FLAGS constants.
Returns
- 0 if nothing is received
- 0xFFFF if one of the Receive Buffers is full (message received)
Requires
Example
// check the CAN1 module for received messages. If any was received do
something.
unsigned int msg_rcvd, rx_flags, data_len;
char data[8];
unsigned long msg_id;
...
CAN1SetOperationMode(_CAN_MODE_NORMAL,0xFF);
// set NORMAL
mode (CAN1 module must be in mode in which receive is possible)
...
rx_flags = 0;
// clear message flags
if (msg_rcvd = CAN1Read(&msg_id, data, &data_len, &rx_flags)) {
...
}
Notes
- CAN library routine require you to specify the module you want to use. To use the desired CAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of CAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
281
MikroElektronika
unsigned int CANxWrite(long id, char *data_, unsigned int DataLen, unsigned
int CAN_TX_MSG_FLAGS);
Description If at least one empty Transmit Buffer is found, the function sends message in the queue for
transmission.
Parameters - id: CAN message identifier. Valid values: 11 or 29 bit values, depending on message type (standard
or extended)
- data: data to be sent
- dataLen: data length. Valid values: 0..8
- CAN_RX_MSG_FLAGS: message flags. Valid values: CAN_TX_MSG_FLAGS constants. See CAN_TX_
MSG_FLAGS constants.
Returns
Requires
Example
Notes
- CAN library routine require you to specify the module you want to use. To use the desired CAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of CAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
282
CAN_OP_MODE Constants
CAN_OP_MODE constants define CAN operation mode. Function CANxSetOperationMode expects one of these as its
argument:
Copy Code To Clipboard
const unsigned int
_CAN_MODE_BITS
_CAN_MODE_NORMAL
_CAN_MODE_SLEEP
_CAN_MODE_LOOP
_CAN_MODE_LISTEN
_CAN_MODE_CONFIG
=
=
=
=
=
=
0xE0,
0x00,
0x20,
0x40,
0x60,
0x80;
bits
CAN_CONFIG_FLAGS Constants
CAN_CONFIG_FLAGS constants define flags related to CAN module configuration. Functions CANxInitialize and
CANxSetBaudRate expect one of these (or a bitwise combination) as their argument:
Copy Code To Clipboard
const unsigned int
_CAN_CONFIG_DEFAULT
= 0xFF,
// 11111111
= 0x01,
= 0xFF,
= 0xFE,
// XXXXXXX1
// XXXXXXX0
_CAN_CONFIG_LINE_FILTER_BIT = 0x02,
_CAN_CONFIG_LINE_FILTER_ON = 0xFF,
_CAN_CONFIG_LINE_FILTER_OFF = 0xFD,
// XXXXXX1X
// XXXXXX0X
_CAN_CONFIG_SAMPLE_BIT
_CAN_CONFIG_SAMPLE_ONCE
_CAN_CONFIG_SAMPLE_THRICE
= 0x04,
= 0xFF,
= 0xFB,
// XXXXX1XX
// XXXXX0XX
_CAN_CONFIG_MSG_TYPE_BIT
_CAN_CONFIG_STD_MSG
_CAN_CONFIG_XTD_MSG
= 0x08,
= 0xFF,
= 0xF7,
// XXXX1XXX
// XXXX0XXX
_CAN_CONFIG_DBL_BUFFER_BIT
_CAN_CONFIG_DBL_BUFFER_ON
_CAN_CONFIG_DBL_BUFFER_OFF
= 0x10,
= 0xFF,
= 0xEF,
// XXX1XXXX
// XXX0XXXX
_CAN_CONFIG_PHSEG2_PRG_BIT
_CAN_CONFIG_PHSEG2_PRG_ON
_CAN_CONFIG_PHSEG2_PRG_OFF
283
MikroElektronika
=
=
=
=
=
0x60,
0xFF,
0xDF,
0xBF,
0x9F;
//
//
//
//
X11XXXXX
X10XXXXX
X01XXXXX
X00XXXXX
You may use bitwise AND (&) to form config byte out of these values. For example:
Copy Code To Clipboard
init = _CAN_CONFIG_SAMPLE_THRICE &
_CAN_CONFIG_PHSEG2_PRG_ON &
_CAN_CONFIG_STD_MSG
&
_CAN_CONFIG_DBL_BUFFER_ON &
_CAN_CONFIG_VALID_XTD_MSG &
_CAN_CONFIG_LINE_FILTER_OFF;
...
CANInitialize(1, 1, 3, 3, 1, init);
// initialize CAN
CAN_TX_MSG_FLAGS Constants
CAN_TX_MSG_FLAGS are flags related to transmission of a CAN message:
Copy Code To Clipboard
const unsigned int
_CAN_TX_PRIORITY_BITS
_CAN_TX_PRIORITY_0
_CAN_TX_PRIORITY_1
_CAN_TX_PRIORITY_2
_CAN_TX_PRIORITY_3
=
=
=
=
=
0x03,
0xFC,
0xFD,
0xFE,
0xFF,
//
//
//
//
XXXXXX00
XXXXXX01
XXXXXX10
XXXXXX11
_CAN_TX_FRAME_BIT
_CAN_TX_STD_FRAME
_CAN_TX_XTD_FRAME
= 0x08,
= 0xFF,
= 0xF7,
// XXXXX1XX
// XXXXX0XX
_CAN_TX_RTR_BIT
_CAN_TX_NO_RTR_FRAME
_CAN_TX_RTR_FRAME
= 0x40,
= 0xFF,
= 0xBF;
// X1XXXXXX
// X0XXXXXX
You may use bitwise AND (&) to adjust the appropriate flags. For example:
Copy Code To Clipboard
// form value to be used with CANSendMessage:
send_config = _CAN_TX_PRIORITY_0 &
_CAN_TX_XTD_FRAME &
_CAN_TX_NO_RTR_FRAME;
...
CANSendMessage(id, data, 1, send_config);
MikroElektronika
284
=
=
=
=
=
=
=
=
=
=
=
=
0x07,
0x00,
0x01,
0x02,
0x03,
0x04,
0x05,
0x08,
0x10,
0x20,
0x40,
0x80;
//
//
//
//
//
Set
Set
Set
Set
Set
if
if
if
if
if
You may use bitwise AND (&) to adjust the appropriate flags. For example:
Copy Code To Clipboard
if (MsgFlag & _CAN_RX_OVERFLOW != 0) {
...
// Receiver overflow has occurred.
// We have lost our previous message.
}
CAN_MASK Constants
CAN_MASK constants define mask codes. Function CANxSetMask expects one of these as its argument:
Copy Code To Clipboard
const unsigned int
_CAN_MASK_B1 = 0,
_CAN_MASK_B2 = 1;
285
MikroElektronika
=
=
=
=
=
=
0,
1,
2,
3,
4,
5;
Library Example
The example demonstrates CAN protocol. The 1st node initiates the communication with the 2nd node by sending
some data to its address. The 2nd node responds by sending back the data incremented by 1. The 1st node then does
the same and sends incremented data back to the 2nd node, etc.
Code for the first CAN node:
Copy Code To Clipboard
unsigned int Can_Init_Flags, Can_Send_Flags, Can_Rcv_Flags; // can flags
unsigned int Rx_Data_Len;
// received data length in
bytes
char RxTx_Data[8];
// can rx/tx data buffer
char Msg_Rcvd;
// reception flag
unsigned long Tx_ID, Rx_ID;
// can rx and tx ID
void main() {
ADPCFG = 0xFFFF;
PORTB = 0;
TRISB = 0;
Can_Init_Flags = 0;
Can_Send_Flags = 0;
Can_Rcv_Flags = 0;
//
// clear flags
//
MikroElektronika
286
CAN2SetOperationMode(_CAN_MODE_CONFIG,0xFF);
// set
Tx_ID = 12111;
transmit ID
// set
287
// send
//
// receive
// if
// id
// increment
// send
MikroElektronika
//
// clear flags
//
CAN2Initialize(1,3,3,3,1,Can_Init_Flags);
CAN2SetOperationMode(_CAN_MODE_CONFIG,0xFF);
// initialize CAN2
// set CONFIGURATION mode
Tx_ID = 3;
// set tx ID
while(1) {
// endless loop
Msg_Rcvd = CAN2Read(&Rx_ID , RxTx_Data , &Rx_Data_Len, &Can_Rcv_Flags);
// receive
message
if ((Rx_ID == 12111u) && Msg_Rcvd) {
// if message received check id
PORTB = RxTx_Data[0];
// id correct, output data at PORTB
RxTx_Data[0]++;
// increment received data
CAN2Write(Tx_ID, RxTx_Data, 1, Can_Send_Flags); // send incremented data back
}
}
}
MikroElektronika
288
289
MikroElektronika
CANSPI Library
The SPI module is available with a number of the dsPIC30/33 and PIC24 MCUs. The mikroC PRO for dsPIC30/33
and PIC24 provides a library (driver) for working with mikroElektronika's CANSPI Add-on boards (with MCP2515 or
MCP2510) via SPI interface.
In the mikroC PRO for dsPIC30/33 and PIC24, each routine of the CAN library has its own CANSPI counterpart with
identical syntax. For more information on Controller Area Network, consult the CAN Library. Note that an effective
communication speed depends on SPI and certainly is slower than "real" CAN.
Important :
- Consult the CAN standard about CAN bus termination resistance.
- An effective CANSPI communication speed depends on SPI and certainly is slower than real CAN.
- The library uses the SPI module for communication. User must initialize appropriate SPI module before using
the CANSPI Library.
- For MCUs with multiple SPI modules it is possible to initialize both of them and then switch by using the
SPI_Set_Active routine.
- Number of SPI modules per MCU differs from chip to chip. Please, read the appropriate datasheet before
utilizing this library.
Example :
sbit CanSpi_CS at
RF0_bit;
Reset line.
sbit CanSpi_Rst at
RF1_bit;
sbit
CanSpi_CS_Direction
at TRISF0_bit;
sbit
CanSpi_Rst_Direction
at TRISF1_bit;
MikroElektronika
290
CANSPISetOperationMode
Prototype
Nothing.
Requires
The CANSPI routines are supported only by MCUs with the SPI module.
MCU has to be properly connected to mikroElektronikas CANSPI Extra Board or similar hardware.
See connection example at the bottom of this page.
Example
//
set
the
CANSPI
module
into
configuration
CANSPISetOperationMode until this mode is set)
CANSPISetOperationMode(_CANSPI_MODE_CONFIG, 0xFF);
Notes
None.
291
mode
(wait
inside
MikroElektronika
char CANSPIGetOperationMode();
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
Requires
The CANSPI routines are supported only by MCUs with the SPI module.
MCU has to be properly connected to mikroElektronikas CANSPI Extra Board or similar hardware.
See connection example at the bottom of this page.
Example
Notes
None.
CANSPIInitialize
Prototype
void CANSPIInitialize(char SJW, char BRP, char PHSEG1, char PHSEG2, char
PROPSEG, char CANSPI_CONFIG_FLAGS);
Nothing.
MikroElektronika
292
Global variables :
- CanSpi_CS: Chip Select line
- CanSpi_Rst: Reset line
- CanSpi_CS_Direction: Direction of the Chip Select pin
- CanSpi_Rst_Direction: Direction of the Reset pin
must be defined before using this function.
The CANSPI routines are supported only by MCUs with the SPI module.
The SPI module needs to be initialized. See the SPIx_Init and SPIx_Init_Advanced routines.
MCU has to be properly connected to mikroElektronikas CANSPI Extra Board or similar hardware.
See connection example at the bottom of this page.
Example
Notes
293
MikroElektronika
void CANSPISetBaudRate(char SJW, char BRP, char PHSEG1, char PHSEG2, char
PROPSEG, char CANSPI_CONFIG_FLAGS);
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 MCUs datasheet (CAN Module)
- BRP as defined in MCUs datasheet (CAN Module)
- PHSEG1 as defined in MCUs datasheet (CAN Module)
- PHSEG2 as defined in MCUs datasheet (CAN Module)
- PROPSEG as defined in MCUs 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 mikroElektronikas CANSPI Extra Board or similar hardware.
See connection example at the bottom of this page.
Example
Notes
None.
MikroElektronika
294
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 mikroElektronikas CANSPI Extra Board or similar hardware.
See connection example at the bottom of this page.
Example
Notes
295
None.
MikroElektronika
CANSPISetFilter
Prototype
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 mikroElektronikas CANSPI Extra Board or similar hardware.
See connection example at the bottom of this page.
Example
Notes
None.
MikroElektronika
296
Description If at least one full Receive Buffer is found, it will be processed in the following way:
- Message ID is retrieved and stored to location provided by the id parameter
- Message data is retrieved and stored to a buffer provided by the data parameter
- Message length is retrieved and stored to location provided by the dataLen parameter
- Message flags are retrieved and stored to location provided by the CANSPI_RX_MSG_FLAGS
parameter
Parameters - id: message identifier address
- data: an array of bytes up to 8 bytes in length
- dataLen: data length address
- CANSPI_RX_MSG_FLAGS: message flags address. For message receive flags format refer to
CANSPI_RX_MSG_FLAGS constants. See CANSPI_RX_MSG_FLAGS constants.
Returns
- 0 if nothing is received
- 0xFFFF if one of the Receive Buffers is full (message received)
Requires
be
in
mode
in
which
receiving
is
possible.
See
The CANSPI routines are supported only by MCUs with the SPI module.
MCU has to be properly connected to mikroElektronikas CANSPI Extra Board or similar hardware.
See connection example at the bottom of this page.
Example
// check the CANSPI module for received messages. If any was received do
something.
unsigned short msg_rcvd, rx_flags, data_len;
char data[8];
unsigned long msg_id;
...
CANSPISetOperationMode(_CANSPI_MODE_NORMAL,0xFF);
// set
NORMAL mode (CANSPI 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)) {
...
}
Notes
None.
297
MikroElektronika
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
Requires
be
in
mode
in
which
transmission
is
possible.
See
The CANSPI routines are supported only by MCUs with the SPI module.
MCU has to be properly connected to mikroElektronikas 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
unsigned short tx_flags;
char data[8];
long msg_id;
...
CANSPISetOperationMode(CANSPI_MODE_NORMAL,0xFF);
// set
NORMAL mode (CANSPI must be in mode in which transmission is possible)
tx_flags = _CANSPI_TX_PRIORITY_0 & _CANSPI_TX_XTD_FRAME;
flags
CANSPIWrite(msg_id, data, 2, tx_flags);
Notes
// set message
None.
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
298
=
=
=
=
=
=
0xE0,
0x00,
0x20,
0x40,
0x60,
0x80;
bits
CANSPI_CONFIG_FLAGS Constants
The CANSPI_CONFIG_FLAGS constants define flags related to the CANSPI module configuration. The functions
CANSPIInit, CANSPISetBaudRate, CANSPISetMask and CANSPISetFilter expect one of these (or a bitwise
combination) as their argument:
Copy Code To Clipboard
const unsigned int
_CANSPI_CONFIG_DEFAULT
= 0xFF,
// 11111111
_CANSPI_CONFIG_PHSEG2_PRG_BIT = 0x01,
_CANSPI_CONFIG_PHSEG2_PRG_ON = 0xFF,
_CANSPI_CONFIG_PHSEG2_PRG_OFF = 0xFE,
// XXXXXXX1
// XXXXXXX0
_CANSPI_CONFIG_LINE_FILTER_BIT = 0x02,
_CANSPI_CONFIG_LINE_FILTER_ON = 0xFF,
_CANSPI_CONFIG_LINE_FILTER_OFF = 0xFD,
// XXXXXX1X
// XXXXXX0X
_CANSPI_CONFIG_SAMPLE_BIT
_CANSPI_CONFIG_SAMPLE_ONCE
_CANSPI_CONFIG_SAMPLE_THRICE
= 0x04,
= 0xFF,
= 0xFB,
// XXXXX1XX
// XXXXX0XX
_CANSPI_CONFIG_MSG_TYPE_BIT
_CANSPI_CONFIG_STD_MSG
_CANSPI_CONFIG_XTD_MSG
= 0x08,
= 0xFF,
= 0xF7,
// XXXX1XXX
// XXXX0XXX
_CANSPI_CONFIG_DBL_BUFFER_BIT
_CANSPI_CONFIG_DBL_BUFFER_ON
_CANSPI_CONFIG_DBL_BUFFER_OFF
= 0x10,
= 0xFF,
= 0xEF,
// XXX1XXXX
// XXX0XXXX
_CANSPI_CONFIG_MSG_BITS
_CANSPI_CONFIG_ALL_MSG
_CANSPI_CONFIG_VALID_XTD_MSG
_CANSPI_CONFIG_VALID_STD_MSG
_CANSPI_CONFIG_ALL_VALID_MSG
=
=
=
=
=
//
//
//
//
299
0x60,
0xFF,
0xDF,
0xBF,
0x9F;
X11XXXXX
X10XXXXX
X01XXXXX
X00XXXXX
MikroElektronika
CANSPI_TX_MSG_FLAGS Constants
CANSPI_TX_MSG_FLAGS are flags related to transmission of a CANSPI message:
Copy Code To Clipboard
const unsigned int
_CANSPI_TX_PRIORITY_BITS
_CANSPI_TX_PRIORITY_0
_CANSPI_TX_PRIORITY_1
_CANSPI_TX_PRIORITY_2
_CANSPI_TX_PRIORITY_3
=
=
=
=
=
0x03,
0xFC,
0xFD,
0xFE,
0xFF,
//
//
//
//
XXXXXX00
XXXXXX01
XXXXXX10
XXXXXX11
_CANSPI_TX_FRAME_BIT
_CANSPI_TX_STD_FRAME
_CANSPI_TX_XTD_FRAME
= 0x08,
= 0xFF,
= 0xF7,
// XXXXX1XX
// XXXXX0XX
_CANSPI_TX_RTR_BIT
_CANSPI_TX_NO_RTR_FRAME
_CANSPI_TX_RTR_FRAME
= 0x40,
= 0xFF,
= 0xBF;
// X1XXXXXX
// X0XXXXXX
You may use bitwise AND (&) to adjust the appropriate flags. For example:
Copy Code To Clipboard
// form value to be used as sending message flag :
send_config = _CANSPI_TX_PRIORITY_0 &
_CANSPI_TX_XTD_FRAME &
_CANSPI_TX_NO_RTR_FRAME;
...
CANSPIWrite(id, data, 1, send_config);
CANSPI_RX_MSG_FLAGS Constants
CANSPI_RX_MSG_FLAGS are flags related to reception of CANSPI message. If a particular bit is set then corresponding
meaning is TRUE or else it will be FALSE.
MikroElektronika
300
=
=
=
=
=
=
=
0x07,
0x00,
0x01,
0x02,
0x03,
0x04,
0x05,
=
=
=
=
=
0x08,
// Set if Overflowed else cleared
0x10,
// Set if invalid else cleared
0x20,
// Set if XTD message else cleared
0x40, // Set if RTR message else cleared
0x80;// Set if this message was hardware double-buffered
You may use bitwise AND (&) to adjust the appropriate flags. For example:
Copy Code To Clipboard
if (MsgFlag & _CANSPI_RX_OVERFLOW != 0) {
...
// Receiver overflow has occurred.
// We have lost our previous message.
}
CANSPI_MASK Constants
The CANSPI_MASK constants define mask codes. Function CANSPISetMask expects one of these as its argument:
Copy Code To Clipboard
const unsigned int
_CANSPI_MASK_B1 = 0,
_CANSPI_MASK_B2 = 1;
CANSPI_FILTER Constants
The CANSPI_FILTER constants define filter codes. Functions CANSPISetFilter expects one of these as its
argument:
Copy Code To Clipboard
const unsigned int
_CANSPI_FILTER_B1_F1
_CANSPI_FILTER_B1_F2
_CANSPI_FILTER_B2_F1
_CANSPI_FILTER_B2_F2
_CANSPI_FILTER_B2_F3
_CANSPI_FILTER_B2_F4
301
=
=
=
=
=
=
0,
1,
2,
3,
4,
5;
MikroElektronika
CanSpi_CS at RF0_bit;
CanSpi_Rst at RF1_bit;
CanSpi_CS_Direction at TRISF0_bit;
CanSpi_Rst_Direction at TRISF1_bit;
//
//
//
//
//
// Clear flags
//
SPI1_Init();
CANSPIInitialize(1,3,3,3,1,Can_Init_Flags);
CANSPISetOperationMode(_CANSPI_MODE_CONFIG,0xFF);
MikroElektronika
302
Tx_ID = 12111;
// Set transmit ID
while(1) {
// Endless loop
Msg_Rcvd = CANSPIRead(&Rx_ID , RxTx_Data , &Rx_Data_Len, &Can_Rcv_Flags); // Receive
message
if ((Rx_ID == 3u) && Msg_Rcvd) {
// If message received check id
PORTB = RxTx_Data[0];
// Id correct, output data at PORTB
RxTx_Data[0]++;
// Increment received data
Delay_ms(10);
CANSPIWrite(Tx_ID, RxTx_Data, 1, Can_Send_Flags); // Send incremented data back
}
}
}
Code for the second CANSPI node:
Copy Code To Clipboard
sbit
sbit
sbit
sbit
CanSpi_CS at RF0_bit;
CanSpi_Rst at RF1_bit;
CanSpi_CS_Direction at TRISF0_bit;
CanSpi_Rst_Direction at TRISF1_bit;
//
//
//
//
//
// Clear flags
//
303
MikroElektronika
CANSPISetOperationMode(_CANSPI_MODE_CONFIG,0xFF);
CANSPISetMask(_CANSPI_MASK_B1,-1,_CANSPI_CONFIG_XTD_MSG);
// Set all mask1
bits to ones
CANSPISetMask(_CANSPI_MASK_B2,-1,_CANSPI_CONFIG_XTD_MSG);
// Set all mask2
bits to ones
CANSPISetFilter(_CANSPI_FILTER_B2_F3,12111,_CANSPI_CONFIG_XTD_MSG); // Set id of
filter B1_F1 to 3
CANSPISetOperationMode(_CANSPI_MODE_NORMAL,0xFF);
Tx_ID = 3;
// Set tx ID
while (1) {
// Endless loop
Msg_Rcvd = CANSPIRead(&Rx_ID , RxTx_Data , &Rx_Data_Len, &Can_Rcv_Flags);
//
Receive message
if ((Rx_ID == 12111u) && Msg_Rcvd) {
// If message received check id
PORTB = RxTx_Data[0];
// Id correct, output data at PORTB
RxTx_Data[0]++;
// Increment received data
CANSPIWrite(Tx_ID, RxTx_Data, 1, Can_Send_Flags); // Send incremented data back
}
}
}
MikroElektronika
304
Example of interfacing CAN transceiver MCP2510 with MCU via SPI interface
305
MikroElektronika
MikroElektronika
306
Example :
Address pin 2.
Address pin 1.
Address pin 0.
extern sfr
direction;
sbit
CF_RDY_direction
TRISD7_bit;
at
sbit
CF_WE_direction
TRISDB6_bit;
at
sbit
CF_OE_direction
TRISD5_bit;
at
sbit
CF_CD1_direction
TRISD4_bit;
at
sbit
CF_CE1_direction
TRISD3_bit;
at
sbit
CF_A2_direction
TRISD2_bit;
at
sbit
CF_A1_direction
TRISD1_bit;
at
sbit
CF_A0_direction
TRISD0_bit;
at
sbit
CF_RDY_
extern sfr
direction;
sbit
CF_WE_
extern sfr
direction;
sbit
CF_OE_
extern sfr
direction;
sbit
CF_CD1_
extern sfr
direction;
sbit
CF_CE1_
extern sfr
direction;
sbit
CF_A2_
extern sfr
direction;
sbit
CF_A1_
extern sfr
direction;
sbit
CF_A0_
307
MikroElektronika
MikroElektronika
308
void Cf_Init();
Nothing.
Requires
Global variables :
- CF_Data_Port : Compact Flash data port
- CF_RDY : Ready signal line
- CF_WE : Write enable signal line
- CF_OE : Output enable signal line
- CF_CD1 : Chip detect signal line
- CF_CE1 : Enable signal line
- CF_A2 : Address pin 2
- CF_A1 : Address pin 1
- CF_A0 : Address pin 0
- CF_RDY_direction : Direction of the Ready pin
- CF_WE_direction : Direction of the Write enable pin
- CF_OE_direction : Direction of the Output enable pin
- CF_CD1_direction : Direction of the Chip detect pin
- CF_CE1_direction : Direction of the Chip enable pin
- CF_A2_direction : Direction of the Address 2 pin
- CF_A1_direction : Direction of the Address 1 pin
- CF_A0_direction : Direction of the Address 0 pin
must be defined before using this function.
Example
CF_RDY
CF_WE
CF_OE
CF_CD1
CF_CE1
CF_A2
CF_A1
CF_A0
at
at
at
at
at
at
at
at
RD7_bit;
RD6_bit;
RD5_bit;
RD4_bit;
RD3_bit;
RD2_bit;
RD1_bit;
RD0_bit;
309
None.
MikroElektronika
Description Checks for presence of CF card by reading the chip detect pin.
Parameters None.
Returns
Requires
The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
Example
Notes
dsPIC30 family MCU and CF card voltage levels are different. The user must ensure that MCUs pin
connected to CD line can read CF card Logical One correctly.
Cf_Enable
Prototype
void 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
Notes
None.
Cf_Disable
Prototype
void 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
Notes
None.
MikroElektronika
310
Nothing.
Requires
The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
Example
Notes
None.
Cf_Read_Byte
Prototype
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
Requires
The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
CF card must be initialized for reading operation. See Cf_Read_Init.
Example
Notes
Cf_Write_Init
Prototype
Nothing.
Requires
The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
Example
Notes
None.
311
MikroElektronika
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 card must be initialized for writing operation. See Cf_Write_Init.
Example
Notes
None.
Cf_Read_Sector
Prototype
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
unsigned short data[512];
...
Cf_Read_Sector(22, data);
Notes
None.
Cf_Write_Sector
Prototype
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
unsigned short data[512];
...
Cf_Write_Sector(22, data);
Notes
None.
MikroElektronika
312
Description Initializes CF card, reads CF FAT16 boot sector and extracts necessary data needed by the library.
Parameters None.
Returns
Requires
Nothing.
Example
Notes
None.
Cf_Fat_QuickFormat
Prototype
Requires
Nothing.
Example
Notes
313
MikroElektronika
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
0x01
Read Only
0x02
Hidden
0x04
System
0x08
Volume Label
0x10
Subdirectory
0x20
Archive
0x40
0x80
File creation flag. If the file does not exist and this
flag is set, a new file with specified name will be
created.
Returns
Requires
CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
Example
Notes
MikroElektronika
314
Nothing.
Requires
CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
File must be previously assigned. See Cf_Fat_Assign.
Example
Notes
None.
Cf_Fat_Read
Prototype
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.
File must be previously assigned. See Cf_Fat_Assign.
File must be open for reading. See Cf_Fat_Reset.
Example
char character;
...
Cf_Fat_Read(&character);
Notes
None.
315
MikroElektronika
void 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.
The file must be previously assigned. See Cf_Fat_Assign.
Example
Notes
None.
Cf_Fat_Append
Prototype
void 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.
File must be previously assigned. See Cf_Fat_Assign.
Example
Notes
None.
Cf_Fat_Delete
Prototype
void Cf_Fat_Delete();
Nothing.
Requires
CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
File must be previously assigned. See Cf_Fat_Assign.
Example
Notes
None.
MikroElektronika
316
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.
File must be previously assigned. See Cf_Fat_Assign.
File must be open for writing. See Cf_Fat_Rewrite or Cf_Fat_Append.
Example
char file_contents[42];
...
Cf_Fat_Write(file_contents, 42); // write data to the assigned file
Notes
None.
Cf_Fat_Set_File_Date
Prototype
Description Sets the date/time stamp. Any subsequent file writing operation will write this stamp to currently
assigned files 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.
File must be previously assigned. See Cf_Fat_Assign.
File must be open for writing. See Cf_Fat_Rewrite or Cf_Fat_Append.
Example
Cf_Fat_Set_File_Date(2005,9,30,17,41,0);
Notes
None.
317
MikroElektronika
Nothing.
Requires
CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
File must be previously assigned. See Cf_Fat_Assign.
Example
unsigned year;
char month, day, hours, mins;
...
Cf_Fat_Get_File_Date(&year, &month, &day, &hours, &mins);
Notes
None.
Cf_Fat_Get_File_Date_Modified
Prototype
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.
File must be previously assigned. See Cf_Fat_Assign.
Example
unsigned year;
char month, day, hours, mins;
...
Cf_Fat_Get_File_Date_Modified(&year, &month, &day, &hours, &mins);
Notes
None.
MikroElektronika
318
Requires
CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
File must be previously assigned. See Cf_Fat_Assign.
Example
Notes
None.
Cf_Fat_Get_Swap_File
Prototype
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. Its 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:
319
MikroElektronika
Bit
Mask
Description
0x01
Read Only
0x02
Hidden
0x04
System
0x08
Volume Label
0x10
Subdirectory
0x20
Archive
0x40
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
unsigned long size;
...
size = Cf_Fat_Get_Swap_File(1000, mikroE.txt, 0x20);
if (size) {
UART1_Write(0xAA);
UART1_Write(Lo(size));
UART1_Write(Hi(size));
UART1_Write(Higher(size));
UART1_Write(Highest(size));
UART1_Write(0xAA);
}
Notes
MikroElektronika
320
CF_RDY
CF_WE
CF_OE
CF_CD1
CF_CE1
CF_A2
CF_A1
CF_A0
at
at
at
at
at
at
at
at
RD7_bit;
RD6_bit;
RD5_bit;
RD4_bit;
RD3_bit;
RD2_bit;
RD1_bit;
RD0_bit;
sbit CF_RDY_direction
sbit CF_WE_direction
sbit CF_OE_direction
sbit CF_CD1_direction
sbit CF_CE1_direction
sbit CF_A2_direction
sbit CF_A1_direction
sbit CF_A0_direction
// end of cf pinout
at
at
at
at
at
at
at
at
TRISD7_bit;
TRISD6_bit;
TRISD5_bit;
TRISD4_bit;
TRISD3_bit;
TRISD2_bit;
TRISD1_bit;
TRISD0_bit;
char SignalPort
at PORTB;
char SignalPort_direction at TRISB;
void InitCF() {
CF_CD1_direction = 1;
while (Cf_Detect() == 0)
;
Cf_Init();
while (!CF_RDY)
;
Delay_ms(2000);
}
void TestBytes() {
unsigned int i;
///// Write numbers 0..511 to sector 590
Cf_Write_Init(590,1);
// Initialize write at sector address 590
//
for 1 sector
SignalPort = 0x03;
// Notify that write has started
Delay_ms(1000);
for (i=0; i<=511; i++)
// Write 512 bytes to sector 590
Cf_Write_Byte(i);
321
MikroElektronika
SignalPort = 0x07;
Delay_ms(1000);
Cf_Read_Init(590,1);
//
//
//
//
//
//
Cf_Read_Init(590,1);
//
//
//
//
//
//
}
// Main program
void main() {
ADPCFG = 0xFFFF;
SignalPort_direction = 0;
SignalPort = 0x01;
InitCF();
TestBytes();
SignalPort = 0x0F;
MikroElektronika
322
323
MikroElektronika
ECAN Library
The mikroC PRO for dsPIC30/33 and PIC24 provides a library (driver) for working with the dsPIC33FJ and pic24HJ
ECAN module.
ECAN is a very robust protocol that has error detection and signalling, selfchecking and fault confinement. Faulty
ECAN data and remote frames are re-transmitted automatically, similar to the Ethernet.
Data transfer rates depend on distance. For example, 1 Mbit/s can be achieved at network lengths below 40m while
250 Kbit/s can be achieved at network lengths below 250m. The greater distance the lower maximum bitrate that can
be achieved . The lowest bitrate defined by the standard is 200Kbit/s. Cables used are shielded twisted pairs.
ECAN supports two message formats:
- Standard format, with 11 identifier bits, and
- Extended format, with 29 identifier bits
ECAN message format and DMA RAM buffer definiton can be found in the ECan_Defs.h header file located in the
ECAN project folder. Read this file carefully and make appropriate adjustments for mcu in use. Also, if a new project
is to be created this file has to be copied, adjusted and included into the project via include pragma directive with
corresponding Search Path updating.
Important :
ECAN buffers are located in DMA RAM, so two DMA channels are used for message transfer, one for each direction
(ECAN->DMA RAM, DMA RAM->ECAN). See the ECANxDmaChannelInit routine.
Consult CAN standard about CAN bus termination resistance.
CAN library routines require you to specify the module you want to use. To select the desired CAN module, simply
change the letter x in the routine prototype for a number from 1 to 2.
Number of CAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet before utilizing this
library.
Library Routines
- ECANxDmaChannelInit
- ECANxSetOperationMode
- ECANxGetOperationMode
- ECANxInitialize
- ECANxSelectTxBuffers
- ECANxFilterDisable
- ECANxFilterEnable
- ECANxSetBufferSize
- ECANxSetBaudRate
- ECANxSetMask
- ECANxSetFilter
- ECANxRead
- ECANxWrite
MikroElektronika
324
Description The function preforms initialization of the DMA module for ECAN.
Parameters - DmaChannel: DMA Channel number. Valid values: 0..7.
- ChannelDir: transfer direction. Valid values: 1 (DMA RAM to peripheral) and 0 (peripheral to DMA
RAM).
- DmaRamBuffAdd: DMA RAM buffer address. DMA RAM location is MCU dependent, refer to
datasheet for valid address range.
Returns
Requires
The ECAN routines are supported only by MCUs with the ECAN module.
Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus.
Example
Notes
- ECAN library routine require you to specify the module you want to use. To select the desired
ECAN module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of ECAN modules per MCU differs from chip to chip. Please, read the appropriate
datasheet before utilizing this library.
ECANxSetOperationMode
Prototype
Nothing.
Requires
The ECAN routines are supported only by MCUs with the ECAN module.
Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus.
Example
// set the ECAN1 module into configuration mode (wait inside ECAN1SetOperationMode
until this mode is set)
ECAN1SetOperationMode(_ECAN_MODE_CONFIG, 0xFF);
Notes
- ECAN library routine require you to specify the module you want to use. To select the desired ECAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of ECAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
325
MikroElektronika
Description The function returns current operation mode of the ECAN module. See ECAN_OP_MODE constants or
device datasheet for operation mode codes.
Parameters None.
Returns
Requires
The ECAN routines are supported only by MCUs with the ECAN module.
Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus.
Example
Notes
- ECAN library routine require you to specify the module you want to use. To select the desired ECAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of ECAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
326
Nothing.
Requires
The ECAN routines are supported only by MCUs with the ECAN module.
Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus.
Example
// initialize the ECAN1 module with appropriate baud rate and message
acceptance flags along with the sampling rules
unsigned int ecan_config_flags;
...
ecan_config_flags = _ECAN_CONFIG_SAMPLE_THRICE &
// Form value to be
used
_ECAN_CONFIG_PHSEG2_PRG_ON &
//
with
ECANInitialize
_ECAN_CONFIG_XTD_MSG &
_ECAN_CONFIG_MATCH_MSG_TYPE &
_ECAN_CONFIG_LINE_FILTER_OFF;
ECAN1Initialize(1, 3, 3, 3, 1, ecan_config_flags);
module
Notes
327
MikroElektronika
Requires
The ECAN routines are supported only by MCUs with the ECAN module.
Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus.
The ECAN module must be initialized. See the ECANxInitialize routine.
Example
Notes
- ECAN library routine require you to specify the module you want to use. To select the desired ECAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of ECAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
ECANxFilterDisable
Prototype
Nothing.
Requires
The ECAN routines are supported only by MCUs with the ECAN module.
Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus.
The ECAN module must be initialized. See the ECANxInitialize routine.
Example
Notes
- ECAN library routine require you to specify the module you want to use. To select the desired ECAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of ECAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
328
Nothing.
Requires
The ECAN routines are supported only by MCUs with the ECAN module.
Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus.
The ECAN module must be initialized. See the ECANxInitialize routine.
Example
Notes
- ECAN library routine require you to specify the module you want to use. To select the desired ECAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of ECAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
ECANxSetBufferSize
Prototype
Description The function configures the total number of receive and transmit buffers in DMA RAM.
Parameters - Ecan1BuffSize: Number of ECAN DMA RAM receive and transmit buffers. Valid values: 4, 6, 8,
12, 16, 24, 32. Each buffer is 16 bytes long.
Returns
Requires
The ECAN routines are supported only by MCUs with the ECAN module.
Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus.
The ECAN module must be initialized. See the ECANxInitialize routine.
Example
Notes
- The same value should be used for DMA RAM buffer definition in the ECan_Defs.h header file
located in the ECAN project folder.
- ECAN library routine require you to specify the module you want to use. To select the desired ECAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of ECAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
329
MikroElektronika
Description Sets ECAN module baud rate. Due to complexity of the ECAN protocol, you can not simply force the
bps value. Instead, use this function when ECAN is in Config mode. Refer to datasheet for details.
SAM, SEG2PHTS and WAKFIL bits are set according to the ECAN_CONFIG_FLAGS value.
Parameters - SJW as defined in MCUs datasheet (ECAN Module)
- BRP as defined in MCUs datasheet (ECAN Module)
- PHSEG1 as defined in MCUs datasheet (ECAN Module)
- PHSEG2 as defined in MCUs datasheet (ECAN Module)
- PROPSEG as defined in MCUs datasheet (ECAN Module)
- ECAN_CONFIG_FLAGS ECAN module configuration flags. Each bit corresponds to the appropriate
ECAN module parameter. Should be formed out of predefined ECAN flag constants. See ECAN_
CONFIG_FLAGS constants
Returns
Nothing.
Requires
The ECAN routines are supported only by MCUs with the ECAN module.
Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus.
The ECAN module must be in Config mode, otherwise the function will be ignored. See
ECANxSetOperationMode.
Example
Notes
// Form value to
//
with
- ECAN library routine require you to specify the module you want to use. To select the desired ECAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of ECAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
330
Description The function configures appropriate mask for advanced message filtering.
Parameters - ECAN_MASK: ECAN module mask number. Valid values: ECAN_MASK constants. See ECAN_MASK
constants.
- val: mask register value. This value is bit-adjusted to appropriate buffer mask registers
- ECAN_CONFIG_FLAGS: selects type of messages to filter. Valid values:
- _ECAN_CONFIG_ALL_VALID_MSG,
- _ECAN_CONFIG_MATCH_MSG_TYPE & _ECAN_CONFIG_STD_MSG,
- _ECAN_CONFIG_MATCH_MSG_TYPE & _ECAN_CONFIG_XTD_MSG.
See ECAN_CONFIG_FLAGS constants.
Returns
Nothing.
Requires
The ECAN routines are supported only by MCUs with the ECAN module.
Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus.
The ECAN module must be in Config mode, otherwise the function will be ignored. See
ECANxSetOperationMode.
Example
Notes
331
- ECAN library routine require you to specify the module you want to use. To select the desired ECAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of ECAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
Nothing.
Requires
The ECAN routines are supported only by MCUs with the ECAN module.
Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus.
The ECAN module must be in Config mode, otherwise the function will be ignored. See
ECANxSetOperationMode.
Example
Notes
ECAN library routine require you to specify the module you want to use. To select the desired ECAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
Number of ECAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
332
unsigned int ECANxRead(unsigned long *id, char *data, unsigned int *dataLen,
unsigned int *ECAN_RX_MSG_FLAGS);
Description If at least one full Receive Buffer is found, it will be processed in the following way:
- Message ID is retrieved and stored to location pointed by the id pointer
- Message data is retrieved and stored to array pointed by the data pointer
- Message length is retrieved and stored to location pointed by the dataLen pointer
- Message flags are retrieved and stored to location pointed by the ECAN_RX_MSG_FLAGS pointer
Parameters - id: message identifier address
- data: an array of bytes up to 8 bytes in length
- dataLen: data length address
- ECAN_RX_MSG_FLAGS: message flags address. For message receive flags format refer to the
ECAN_RX_MSG_FLAGS constants. See ECAN_RX_MSG_FLAGS constants.
Returns
Requires
The ECAN routines are supported only by MCUs with the ECAN module.
Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus.
The ECAN module must be in a mode in which receiving is possible. See ECANxSetOperationMode.
Example
// check the ECAN1 module for received messages. If any was received do
something.
unsigned int msg_rcvd, rx_flags, data_len;
char data[8];
unsigned long msg_id;
...
ECAN1SetOperationMode(_ECAN_MODE_NORMAL,0xFF);
// set NORMAL
mode (ECAN1 module must be in a mode in which receiving is possible)
...
rx_flags = 0;
// clear
message flags
if (msg_rcvd = ECAN1Read(&msg_id, data, &data_len, &rx_flags)) {
...
}
Notes
- ECAN library routine require you to specify the module you want to use. To select the desired ECAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of ECAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
333
MikroElektronika
unsigned int ECANxWrite(long id, char *Data, unsigned int DataLen, unsigned
int ECAN_TX_MSG_FLAGS);
Description If at least one empty Transmit Buffer is found, the function sends message in the queue for
transmission.
Parameters - id: ECAN message identifier. Valid values: all 11 or 29 bit values, depending on message type
(standard or extended)
- Data: data to be sent
- DataLen: data length. Valid values: 0..8
- ECAN_TX_MSG_FLAGS: message flags. Valid values: ECAN_TX_MSG_FLAGS constants. See ECAN_
TX_MSG_FLAGS constants.
Returns
Requires
The ECAN routines are supported only by MCUs with the ECAN module.
Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus.
The ECAN module must
ECANxSetOperationMode.
Example
be
in
mode
which
transmission
is
possible.
See
Notes
in
- ECAN library routine require you to specify the module you want to use. To select the desired ECAN
module, simply change the letter x in the routine prototype for a number from 1 to 2.
- Number of ECAN modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
334
ECAN_OP_MODE Constants
The ECAN_OP_MODE constants define ECAN operation mode. The routine ECANxSetOperationMode expect one of
these as their argument:
Copy Code To Clipboard
const unsigned int
_ECAN_MODE_BITS
_ECAN_MODE_NORMAL
_ECAN_MODE_DISABLE
_ECAN_MODE_LOOP
_ECAN_MODE_LISTEN
_ECAN_MODE_CONFIG
_ECAN_MODE_LISTEN_ALL
=
=
=
=
=
=
=
0x00E0,
0x00,
0x01,
0x02,
0x03,
0x04,
0x07;
bits
ECAN_CONFIG_FLAGS Constants
The ECAN_CONFIG_FLAGS constants define flags related to the ECAN module configuration. The routines
ECANxInitialize and ECANxSetBaudRate expect one of these (or a bitwise combination) as their argument:
Copy Code To Clipboard
const unsigned int
_ECAN_CONFIG_DEFAULT
= 0xFF,
// 11111111
= 0x01,
= 0xFF,
= 0xFE,
// XXXXXXX1
// XXXXXXX0
_ECAN_CONFIG_LINE_FILTER_BIT = 0x02,
_ECAN_CONFIG_LINE_FILTER_ON = 0xFF,
_ECAN_CONFIG_LINE_FILTER_OFF = 0xFD,
// XXXXXX1X
// XXXXXX0X
_ECAN_CONFIG_SAMPLE_BIT
_ECAN_CONFIG_SAMPLE_ONCE
_ECAN_CONFIG_SAMPLE_THRICE
= 0x04,
= 0xFF,
= 0xFB,
// XXXXX1XX
// XXXXX0XX
_ECAN_CONFIG_MSG_TYPE_BIT
_ECAN_CONFIG_STD_MSG
_ECAN_CONFIG_XTD_MSG
= 0x08,
= 0xFF,
= 0xF7,
// XXXX1XXX
// XXXX0XXX
_ECAN_CONFIG_MATCH_TYPE_BIT
_ECAN_CONFIG_ALL_VALID_MSG
_ECAN_CONFIG_MATCH_MSG_TYPE
= 0x20,
= 0xDF,
= 0xFF;
// XX0XXXXX
// XX1XXXXX
_ECAN_CONFIG_PHSEG2_PRG_BIT
_ECAN_CONFIG_PHSEG2_PRG_ON
_ECAN_CONFIG_PHSEG2_PRG_OFF
335
MikroElektronika
// initialize ECAN1
ECAN_TX_MSG_FLAGS Constants
ECAN_TX_MSG_FLAGS are flags related to transmission of ECAN message. The routine ECANxWrite expect one of
these (or a bitwise combination) as their argument:
Copy Code To Clipboard
const unsigned int
_ECAN_TX_PRIORITY_BITS
_ECAN_TX_PRIORITY_0
_ECAN_TX_PRIORITY_1
_ECAN_TX_PRIORITY_2
_ECAN_TX_PRIORITY_3
_ECAN_TX_FRAME_BIT
_ECAN_TX_STD_FRAME
_ECAN_TX_XTD_FRAME
=
=
=
=
=
0x03,
0xFC,
0xFD,
0xFE,
0xFF,
//
//
//
//
XXXXXX00
XXXXXX01
XXXXXX10
XXXXXX11
= 0x08,
= 0xFF,
= 0xF7,
// XXXXX1XX
// XXXXX0XX
_ECAN_TX_RTR_BIT
= 0x40,
_ECAN_TX_NO_RTR_FRAME = 0xFF,
_ECAN_TX_RTR_FRAME
= 0xBF;
// X1XXXXXX
// X0XXXXXX
You may use bitwise AND (&) to adjust the appropriate flags. For example:
Copy Code To Clipboard
// form value to be used with CANSendMessage:
send_config = _ECAN_TX_PRIORITY_0 &
_ECAN_TX_XTD_FRAME &
_ECAN_TX_NO_RTR_FRAME;
...
ECAN1SendMessage(id, data, 1, send_config);
ECAN_RX_MSG_FLAGS Constants
ECAN_RX_MSG_FLAGS are flags related to reception of ECAN message. If a particular bit is set then corresponding
meaning is TRUE or else it will be FALSE.
MikroElektronika
336
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
0x000F,
0x00,
0x01,
0x02,
0x03,
0x04,
0x05,
0x06,
0x07,
0x08,
0x09,
0x0A,
0x0B,
0x0C,
0x0D,
0x0E,
0x0F,
//
//
//
//
_ECAN_RX_OVERFLOW
_ECAN_RX_INVALID_MSG
_ECAN_RX_XTD_FRAME
_ECAN_RX_RTR_FRAME
=
=
=
=
0x10,
0x20,
0x40,
0x80;
//
//
//
//
// ...
// filter15 match
Set
Set
Set
Set
if
if
if
if
You may use bitwise AND (&) to extract received message status. For example:
Copy Code To Clipboard
if (MsgFlag & _ECAN_RX_OVERFLOW != 0) {
...
// Receiver overflow has occurred.
// We have lost our previous message.
}
ECAN_MASK Constants
The ECAN_MASK constants define mask codes. The routine ECANxSetMask expect one of these as their argument:
Copy Code To Clipboard
const unsigned int
_ECAN_MASK_0 = 0,
_ECAN_MASK_1 = 1,
_ECAN_MASK_2 = 2;
ECAN_FILTER Constants
The ECAN_FILTER constants define filter codes. The routine ECANxSetFilter expect one of these as their argument:
337
MikroElektronika
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15;
ECAN_RX_BUFFER Constants
The ECAN_RX_BUFFER constants define RX bufer codes codes. The routine ECANxSetFilter expect one of these as
their argument:
Copy Code To Clipboard
const unsigned int
_ECAN_RX_BUFFER_0
_ECAN_RX_BUFFER_1
_ECAN_RX_BUFFER_2
_ECAN_RX_BUFFER_3
_ECAN_RX_BUFFER_4
_ECAN_RX_BUFFER_5
_ECAN_RX_BUFFER_6
_ECAN_RX_BUFFER_7
_ECAN_RX_BUFFER_8
_ECAN_RX_BUFFER_9
_ECAN_RX_BUFFER_10
_ECAN_RX_BUFFER_11
_ECAN_RX_BUFFER_12
_ECAN_RX_BUFFER_13
_ECAN_RX_BUFFER_14
_ECAN_RX_BUFFER_15
MikroElektronika
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15;
338
//
//
//
//
// was it rx interrupt?
// if yes clear rx interrupt flag
}
void main() {
// Set PLL : Fosc = ((Fin/PLLPRE)*PLLDIV)/PLLPOST ; (((10MHz/2)*32)/4) = 20MHz
// refer the pic24 family datasheet for more details
CLKDIV &= 0xFFE0; //CLKDIVbits.PLLPRE = 0;
PLLFBD = 0x1E;
//PLLFBDbits.PLLDIV = 0x1E;
CLKDIV &= 0xFF3F; //CLKDIVbits.PLLPOST = 1;
CLKDIV |= 0x00C0;
AD1PCFGH = 0xFFFF;
AD1PCFGL = 0xFFFF;
AD2PCFGL = 0xFFFF;
//
// all ports digital I/O
//
339
MikroElektronika
PORTB = 0;
TRISB = 0;
// clear PORTB
// set PORTB as output,
// for received message data
displaying
Can_Init_Flags = 0;
Can_Send_Flags = 0;
Can_Rcv_Flags = 0;
//
// clear flags
//
RxTx_Data[0] = 9;
ECAN1DmaChannelInit(0, 1, &ECAN1RxTxRAMBuffer);
ECAN1DmaChannelInit(2, 0, &ECAN1RxTxRAMBuffer);
ECAN1Initialize(1, 3, 3, 3, 1, Can_Init_Flags);
ECAN1SetBufferSize(ECAN1RAMBUFFERSIZE);
DMA RAM
ECAN1SelectTxBuffers(0x000F);
MikroElektronika
// set transmit ID
340
while (1) {
// endless loop
Msg_Rcvd = ECAN1Read(&Rx_ID , RxTx_Data , &Rx_Data_Len, &Can_Rcv_Flags); // receive
message
if ((Rx_ID == 3u) && Msg_Rcvd) {
// if message received check id
PORTB = RxTx_Data[0];
// id correct, output data at PORTB
RxTx_Data[0]++ ;
// increment received data
Delay_ms(10);
ECAN1Write(Tx_ID, RxTx_Data, 1, Can_Send_Flags); // send incremented data back
}
}
}
Code for the second ECAN node:
Copy Code To Clipboard
#include "__Lib_ECAN1_Defs.h"
unsigned int Can_Init_Flags, Can_Send_Flags, Can_Rcv_Flags; // can flags
unsigned int Rx_Data_Len;
// received data length in
bytes
char RxTx_Data[8];
// can rx/tx data buffer
char Msg_Rcvd;
// reception flag
unsigned long Tx_ID, Rx_ID;
// can rx and tx ID
void C1Interrupt(void) org 0x005A {
IFS2bits.C1IF = 0;
if(C1INTFbits.TBIF) {
C1INTFbits.TBIF = 0;
}
if(C1INTFbits.RBIF) {
C1INTFbits.RBIF = 0;
}
}
void main() {
// Set PLL : Fosc = ((Fin/PLLPRE)*PLLDIV)/PLLPOST ; (((10MHz/2)*32)/4) = 20MHz
// refer the pic24 family datasheet for more details
CLKDIV &= 0xFFE0; //CLKDIVbits.PLLPRE = 0;
PLLFBD = 0x1E;
//PLLFBDbits.PLLDIV = 0x1E;
CLKDIV &= 0xFF3F; //CLKDIVbits.PLLPOST = 1;
CLKDIV |= 0x00C0;
AD1PCFGH = 0xFFFF;
AD1PCFGL = 0xFFFF;
AD2PCFGL = 0xFFFF;
341
//
// all ports digital I/O
//
MikroElektronika
Can_Init_Flags = 0;
Can_Send_Flags = 0;
Can_Rcv_Flags = 0;
//
// clear flags
//
ECAN1DmaChannelInit(0, 1, &ECAN1RxTxRAMBuffer);
// set tx ID
while (1) {
Msg_Rcvd = ECAN1Read(&Rx_ID , RxTx_Data , &Rx_Data_Len, &Can_Rcv_Flags); // receive
message
if ((Rx_ID == 12111u) && Msg_Rcvd) {
// if message received check id
PORTB = RxTx_Data[0];
// id correct, output data at PORTB
RxTx_Data[0]++ ;
// increment received data
ECAN1Write(Tx_ID, RxTx_Data, 1, Can_Send_Flags); // send incremented data back
}
}
}
MikroElektronika
342
EEPROM Library
EEPROM data memory is available with a number of dsPIC30 family and some PIC24 family MCU's. The mikroC PRO
for dsPIC30/33 and PIC24 includes a library for comfortable work with MCU's internal EEPROM.
Important : Only PIC24F08KA102 and PIC24F16KA102 of PIC24 family of MCUs have EEPROM memory.
Library Routines
- EEPROM_Erase
- EEPROM_Erase_Block
- EEPROM_Read
- EEPROM_Write
- EEPROM_Write_Block
343
MikroElektronika
Nothing.
Requires
Nothing.
Example
Notes
CPU is not halted for the Data Erase cycle. The user can poll WR bit, use NVMIF or Timer IRQ to
detect the end of erase sequence.
EEPROM_Erase_Block
Prototype
Description Erases one EEPROM row from EEPROM memory; For dsPIC30 family it is 16 words long, for
24F04KA201 and 24F16KA102 family it is 8 words long.
Parameters - address: starting address of the EEPROM memory block to be erased.
Returns
Nothing.
Requires
Nothing.
Example
Notes
CPU is not halted for the Data Erase cycle. The user can poll WR bit, use NVMIF or Timer IRQ to
detect the end of erase sequence.
EEPROM_Read
Prototype
Requires
It is the users responsibility to obtain proper address parity (in this case, even).
Example
Notes
None.
MikroElektronika
344
Nothing.
Requires
Nothing.
Example
Notes
EEPROM_Write_Block
Prototype
Nothing.
Requires
It is the users responsibility to maintain proper address alignment. In this case, address has to be a
multiply of 32, which is the size (in bytes) of one row of MCUs EEPROM memory.
Example
Notes
Library Example
This project demonstrates usage of EEPROM library functions for dsPIC30F4013. Each EEPROM (16-bit) location can
be written to individually, or in 16-word blocks, which is somewhat faster than the former. If Writing in blocks, EEPROM
data start address must be a multiply of 16. Please read Help for more details on the library functions!
Copy Code To Clipboard
unsigned int eeData;
unsigned long eeAddr;
unsigned int dArr[16];
void main() {
unsigned i;
345
MikroElektronika
TRISB = 0;
LATB = 0xFFFF;
eeAddr = 0x7FFC00;
eeData = 0;
// PORTB as output
// Start address of EEPROM
// Data to be written
//
//
//
//
//
eeAddr += 2;
Delay_ms(30);
}
Delay_ms(1000);
eeData = 0xAAAA;
for (i=0; i<16; i++){
dArr[i] = eeData;
eeData = ~eeData;
}
// Wait 1 second.
// Initializing array of 16 integers with data
EEPROM_Write_Block(0x7FFC20, dArr);
while(WR_bit)
;
eeAddr = 0x7FFC20;
for (i=0; i<16; i++){
LATB = EEPROM_Read(eeAddr);
eeAddr += 2;
Delay_ms(500);
}
MikroElektronika
346
Example :
extern
DATA;
sfr
char
S1D13700_
extern
RES;
sfr
sbit
S1D13700_
Reset signal.
sbit S1D13700_WR_Direction
TRISC2_bit;
at
sbit S1D13700_RD_Direction
TRISC1_bit;
at
at
sbit S1D13700_RES_Direction
TRISC0_bit;
at
extern sfr sbit S1D13700_CS_ Direction of the Chip select sbit S1D13700_CS_Direction
Direction;
TRISC4_bit;
pin.
at
347
S1D13700_
the
MikroElektronika
MikroElektronika
348
Returns
Nothing.
Global variables :
- S1D13700_Data_Port: Data Bus Port.
- S1D13700_WR: Write signal pin.
- S1D13700_RD: Read signal pin.
- S1D13700_A0: Command/Data signal pin.
- S1D13700_RES: Reset signal pin.
- S1D13700_CS: Chip Select signal pin.
- S1D13700_Data_Port_Direction: Data Bus Port Direction.
- S1D13700_WR_Direction: Direction of Write signal pin.
- S1D13700_RD_Direction: Direction of Read signal pin.
- S1D13700_A0_Direction: Direction of Command/Data signal pin.
- S1D13700_RES_Direction: Direction of Reset signal pin.
- S1D13700_CS_Direction: Direction of Chip Select signal pin.
must be defined before using this function.
Example
349
MikroElektronika
Returns
Nothing.
Description
S1D13700_SYSTEM_SET
S1D13700_POWER_SAVE
S1D13700_DISP_ON
S1D13700_DISP_OFF
S1D13700_SCROLL
S1D13700_CS_RIGHT
S1D13700_CS_LEFT
S1D13700_CS_UP
S1D13700_CS_DOWN
S1D13700_OVLAY
S1D13700_CGRAM_ADR
S1D13700_HDOT_SCR
S1D13700_CSRW
S1D13700_CSRR
S1D13700_GRAYSCALE
S1D13700_MEMWRITE
S1D13700_MEMREAD
Requires
Example
MikroElektronika
350
Returns
Nothing.
Example
S1D13700_Read_Parameter
Prototype
char S1D13700_Read_Parameter();
Returns
Nothing.
Example
parameter = S1D13700_Read_Parameter();
S1D13700_Fill
Prototype
Returns
Nothing.
Example
// from the starting address of 0x3000, fill the memory block size of 0x7FFF
with 0x20
S1D13700_Fill(0x20, 0x3000, 0x7FFF);
351
MikroElektronika
Returns
Nothing.
Example
S1D13700_TxtFill
Prototype
Returns
Nothing.
Example
S1D13700_Display_GrLayer
Prototype
Returns
Nothing.
Description
S1D13700_LAYER_OFF
S1D13700_LAYER_ON
S1D13700_LAYER_FLASH_2Hz
S1D13700_LAYER_FLASH_16Hz
Requires
Example
MikroElektronika
352
Returns
Nothing.
Description
S1D13700_LAYER_OFF
S1D13700_LAYER_ON
S1D13700_LAYER_FLASH_2Hz
S1D13700_LAYER_FLASH_16Hz
Requires
Example
S1D13700_Set_Cursor
Prototype
Returns
Nothing.
Description
S1D13700_CURSOR_UNDERSCORE
S1D13700_CURSOR_BLOCK
Requires
Example
// set cursor with the following properties : width 5px, height 10px, cursor
shape - block
S1D13700_Set_Cursor(5, 10, S1D13700_CURSOR_BLOCK);
353
MikroElektronika
Returns
Nothing.
Description
S1D13700_CURSOR_OFF
S1D13700_CURSOR_ON
S1D13700_CURSOR_FLASH_2Hz
S1D13700_CURSOR_FLASH_16Hz
Requires
Example
// set cursor on
S1D13700_Display_Cursor(S1D13700_CURSOR_ON);
S1D13700_Write_Char
Prototype
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
S1D13700_OVERLAY_OR
S1D13700_OVERLAY_XOR
In this mode, the text and graphics data are combined via the
logical exclusive OR.
S1D13700_OVERLAY_AND
The text and graphic data shown on display are combined via the
logical AND function.
Requires
Example
S1D13700_Write_Char(A,22,23,S1D13700_OVERLAY_OR);
MikroElektronika
354
Returns
Nothing.
Description Writes text in the current text panel of Glcd at coordinates (x, y).
Parameters :
- str: text to be written.
- x: text position on x-axis (column).
- y: text position on y-axis (row).
- mode: mode parameter. Valid values :
Value
Description
S1D13700_OVERLAY_OR
S1D13700_OVERLAY_XOR
In this mode, the text and graphics data are combined via the
logical exclusive OR.
S1D13700_OVERLAY_AND
The text and graphic data shown on display are combined via the
logical AND function.
Requires
Example
S1D13700_Dot
Prototype
Returns
Nothing.
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 :
Value
Description
S1D13700_BLACK
Black color.
S1D13700_WHITE
White color.
Requires
Example
355
MikroElektronika
void S1D13700_Line(unsigned int x0, unsigned int y0, unsigned int x1,
unsigned int y1, unsigned char pcolor);
Returns
Nothing.
Description
S1D13700_BLACK
Black color.
S1D13700_WHITE
White color.
Requires
Example
S1D13700_H_Line
Prototype
Returns
Nothing.
Description
S1D13700_BLACK
Black color.
S1D13700_WHITE
White color.
Requires
Example
MikroElektronika
356
Returns
Nothing.
Description
S1D13700_BLACK
Black color.
S1D13700_WHITE
White color.
Requires
Example
S1D13700_Rectangle
Prototype
void S1D13700_Rectangle(unsigned int x0, unsigned int y0, unsigned int x1,
unsigned int y1, unsigned char pcolor);
Returns
Nothing.
Description
S1D13700_BLACK
Black color.
S1D13700_WHITE
White color.
Requires
Example
357
MikroElektronika
void S1D13700_Rectangle(unsigned int x0, unsigned int y0, unsigned int x1,
unsigned int y1, unsigned char pcolor);
Returns
Nothing.
Description
S1D13700_BLACK
Black color.
S1D13700_WHITE
White color.
Requires
Example
S1D13700_Rectangle_Round_Edges
Prototype
Returns
Nothing.
Description
S1D13700_BLACK
Black color.
S1D13700_WHITE
White color.
Requires
Example
MikroElektronika
358
Returns
Nothing.
Description
S1D13700_BLACK
Black color.
S1D13700_WHITE
White color.
Requires
Example
S1D13700_Circle
Prototype
Returns
Nothing.
Description
S1D13700_BLACK
Black color.
S1D13700_WHITE
White color.
Requires
Example
359
MikroElektronika
Returns
Nothing.
Description
S1D13700_BLACK
Black color.
S1D13700_WHITE
White color.
Requires
Example
S1D13700_Image
Prototype
Returns
Nothing.
Example
S1D13700_Image(image);
MikroElektronika
360
Returns
Nothing.
Example
// Draws a 10x15 part of the image starting from the upper left corner on
the coordinate (10,12). Original image size is 16x32.
S1D13700_PartialImage(10, 12, 10, 15, 16, 32, image);
361
MikroElektronika
dsPIC30:
- Erasing can be done only in 32-instructions (64 addresses, 96 bytes) memory blocks. This means that the
block start address should be a multiply of 64 (i.e. have 6 lower bits set to zero).
- Data is read and written in 4-instructions (8 addresses, 12 bytes) blocks.This means that the block start
address should be a multiply of 8 (i.e. have 3 lower bits set to zero).
- On the dsPIC30s, 2 address locations are assigned on every 3 bytes of (flash) program memory. Due to
this specific and non-one-to-one address mapping, the mikroC PRO for dsPIC30/33 and PIC24 offers two
sets of Flash handling functions: "regular" and "compact".
Using the "regular" set, the user can write one byte of data to a single address, which means that each
byte of written data has its own address, but on every 2 written bytes one byte of Flash memory remains
empty.
Using the "compact" set, every byte of Flash memory, including those non-addressable, is filled with data;
this method can only be used for data organized in bytes.
The "compact" functions have _Compact as name suffix.
- For run-time FLASH read/write, the dsPIC30's RTSP module is being used. It organizes data into rows
and panels. Each row contains write latches that can hold 4 instructions (12 bytes). The number of panels
varies from one dsPIC30 MCU model to another. Because of that, the flash write sequence has been split
into several operations (_Write_Init(), _Write_LoadLatch4(), _Write_DoWrite()), in order
to be usable on all dsPICs.
MikroElektronika
362
Library Routines
dsPIC30 Functions
- FLASH_Erase32
- FLASH_Write_Block
- FLASH_Write_Compact
- FLASH_Write_Init
- FLASH_Write_Loadlatch4
- FLASH_Write_Loadlatch4_Compact
- FLASH_Write_DoWrite
- FLASH_Read4
- FLASH_Read4_Compact
dsPIC30 Functions
363
MikroElektronika
Description Erases one block (32 instructions, 64 addresses, 96 bytes)from the program FLASH memory.
Parameters - address: starting address of the FLASH memory block
Returns
Nothing.
Requires
Nothing.
Example
Notes
The user should take care about the address alignment (see the explanation at the beginning of this
page).
FLASH_Write_Block
Prototype
Description Fills one writeable block of Flash memory (4 instructions, 8 addresses, 12 bytes) in the regular mode.
Addresses and data are being mapped 1-on-1. This also means that 3rd byte of each program location
remains unused.
Parameters - address: starting address of the FLASH memory block
- data_: data to be written
Returns
Nothing.
Requires
The block to be written to must be erased first, either from the user code (through the RTSP), or during
the programming of MCU. Please note that block size that is to be erased is different from the one that
can be written with this function!
Example
Notes
The user should take care about the address alignment (see the explanation at the beginning of this
page).
MikroElektronika
364
void FLASH_Write_Compact(unsigned
bytes);
long
address,
void
*data_,
unsigned
Description Fills a portion of Flash memory using the dsPIC30 RTSP module, in the compact manner. In this way,
several blocks of RTSPs latch can be written in one pass. One latch block contains 4 instructions (8
addresses, 12 bytes). Up to 8 latch blocks can be written in one round, resulting in a total of 8*12 = 96
bytes. This method uses all available bytes of the program FLASH memory, including those that are
not mapped to address space (every 3rd byte).
Parameters - address: starting address of the FLASH memory block
- data_: data to be written
- bytes: number of bytes to be written. The amount of bytes to be written must be a multiply of 12,
since this is the size of the RTSPs write latch(es).
Returns
Nothing.
Requires
The block to be written to must be erased first, either from the user code FLASH_Erase32, or during
the programming of MCU. Please note that block size that is to be erased is different from the one that
can be written with this function!
Example
Notes
The user should take care about the address alignment (see the explanation at the beginning of this
page).
FLASH_Write_Init
Prototype
Nothing.
Requires
The block to be written to must be erased first, either from the user code FLASH_Erase32, or during
the programming of MCU. Please note that block size that is to be erased is different from the one that
can be written with this function!
Example
Notes
The user should take care about the address alignment (see the explanation at the beginning of this
page).
365
MikroElektronika
void FLASH_Write_Loadlatch4();
Description Loads the current RTSP write latch with data (4 instructions, 8 addresses, 12 bytes). The data is filled
in the regular mode.
Parameters None.
Returns
Nothing.
Requires
The block to be written to must be erased first, either from the user code FLASH_Erase32, or during
the programming of MCU. Please note that block size that is to be erased is different from the one that
can be written with this function!
This function is used as a part of the Flash write sequence, therefore the FLASH_Write_Init function
must be called before this one.
This function can be called several times before commiting the actual write-to-Flash operation FLASH_
Write_DoWrite. This depends on the organization of the RTSP module for the certain dsPIC30. Please
consult the Datasheet for particular dsPIC30 on this subject.
Example
Notes
None.
MikroElektronika
366
void FLASH_Write_Loadlatch4_Compact();
Description Loads the current RTSP write latch with data (4 instructions, 8 addresses, 12 bytes). The data is filled
in the compact mode.
Parameters None.
Returns
Nothing.
Requires
The block to be written to must be erased first, either from the user code FLASH_Erase32, or during
the programming of MCU. Please note that block size that is to be erased is different from the one that
can be written with this function!
This function is used as a part of the Flash write sequence, therefore the FLASH_Write_Init function
must be called before this one.
This function can be called several times before committing actual write-to-Flash operation FLASH_
Write_DoWrite. This depends on the organization of the RTSP module for the certain dsPIC30. Please
consult the Datasheet for particular dsPIC30 on this subject.
Example
Notes
None.
367
MikroElektronika
void FLASH_Write_DoWrite();
Nothing.
Requires
The block to be written to must be erased first, either from the user code FLASH_Erase32, or during
the programming of MCU. Please note that block size that is to be erased is different from the one that
can be written with this function!
This function is used as a part of the Flash write sequence, therefore FLASH_Write_Init and certain
number of FLASH_Write_Loadlatch4 or FLASH_Write_Loadlatch4_Compact function calls must be
made before this one.
This function is to be called once, at the and of the FLASH write sequence.
Example
Notes
None.
FLASH_Read4
Prototype
Description Reads one latch row (4 instructions, 8 addresses) in the regular mode.
Parameters - address: starting address of the FLASH memory block to be read
- write_to: starting address of RAM buffer for storing read data
Returns
Requires
Nothing.
Example
Notes
The user should take care of the address alignment (see the explanation at the beginning of this
page).
MikroElektronika
368
Description Reads one latch row (4 instructions, 8 addresses) in the compact mode.
Parameters - address: starting address of the FLASH memory block to be read
- write_to: starting address of RAM buffer for storing read data
Returns
Requires
Nothing.
Example
Notes
The user should take care of the address alignment (see the explanation at the beginning of this
page).
Description Erases one block (512 instructions, 1024 addresses, 1536 bytes) from the program FLASH memory.
Parameters - address: starting address of the FLASH memory block
Returns
Nothing.
Requires
Nothing.
Example
//--- erase the flash memory block, starting from address 0x006400
unsigned long flash_address = 0x006400;
...
FLASH_Erase(flash_address);
Notes
The user should take care about the address alignment (see the explanation at the beginning of this
page).
369
MikroElektronika
Description Fills one writeable block of Flash memory (64 instructions, 128 addresses, 192 bytes) in the regular
mode. Addresses and data are being mapped 1-on-1. This also means that 3rd byte of each program
location remains unused.
Parameters - address: starting address of the FLASH memory block
- data_: data to be written
Returns
Nothing.
Requires
The block to be written to must be erased first, either from the user code (through the RTSP), or during
the programming of MCU. Please note that block size that is to be erased is different from the one that
can be written with this function!
Example
Notes
The user should take care about the address alignment (see the explanation at the beginning of this
page).
FLASH_Write_Compact
Prototype
Description Fills a portion of Flash memory (64 instructions, 128 addresses, 192 bytes) using the dsPIC33 and
PIC24s RTSP (Run Time Self Programming) module, in the compact manner. This method uses all
available bytes of the program FLASH memory, including those that are not mapped to address space
(every 3rd byte).
Parameters - address: starting address of the FLASH memory block
- data_: data to be written
Returns
Nothing.
Requires
The block to be written to must be erased first, either from the user code (FLASH_Erase), or during
the programming of MCU. Please note that block size that is to be erased is different from the one that
can be written with this function!
Example
char
cArr[]
supercalifragillisticexpialidotiousABCDEFGHIJKLMNOPRSTUVWXYZ1234;
void * pv1;
...
pv1 = cArr;
FLASH_Write_Compact(0x006400, pv1);
Notes
The user should take care of the address alignment (see the explanation at the beginning of this
page).
MikroElektronika
370
Description Reads required number of words from the flash memory in the regular mode.
Parameters - address: starting address of the FLASH memory block to be read
- write_to: starting address of RAM buffer for storing read data
- NoWords: number of words to be read
Returns
Requires
Example
unsigned Buffer[64];
unsigned long start_address = 0x6500;
...
FLASH_Read(start_address, Buffer, 10);
Notes
The user should take care of the address alignment (see the explanation at the beginning of this
page).
FLASH_Read_Compact
Prototype
Description Reads required number of bytes from the flash memory in the compact mode.
Parameters - address: starting address of the FLASH memory block to be read
- write_to: starting address of RAM buffer for storing read data
- NoBytes: number of bytes to be read
Returns
Requires
Example
char Buffer[64];
unsigned long start_address = 0x6500;
...
FLASH_Read_Compact(start_address, Buffer, 10);
Notes
The user should take care of the address alignment (see the explanation at the beginning of this
page).
371
MikroElektronika
MikroElektronika
372
//
373
MikroElektronika
Example :
Data 0 line.
Data 1 line.
Data 2 line.
Data 3 line.
Data 4 line.
Data 5 line.
Data 6 line.
Data 7 line.
Read/Write line.
Enable line.
Reset line.
extern sfr
Direction;
sbit
GLCD_D0_
extern sfr
Direction;
sbit
GLCD_D1_
extern sfr
Direction;
sbit
GLCD_D3_
extern sfr
Direction;
sbit
GLCD_D4_
extern sfr
Direction;
sbit
GLCD_D5_
extern sfr
Direction;
sbit
GLCD_D6_
extern sfr
Direction;
sbit
GLCD_D7_
extern sfr
Direction;
sbit
at
extern sfr
Direction;
sbit
at
extern sfr
Direction;
sbit
extern sfr
Direction;
sbit
extern sfr
Direction;
sbit
GLCD_EN_
extern sfr
Direction;
MikroElektronika
sbit
GLCD_RST_
sbit
GLCD_RST_Direction
TRISF5_bit;
at
374
Glcd_Init
Prototype
void 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 :
- GLCD_D0 : Data pin 0
- GLCD_D1 : Data pin 1
- GLCD_D2 : Data pin 2
- GLCD_D3 : Data pin 3
- GLCD_D4 : Data pin 4
- GLCD_D5 : Data pin 5
- GLCD_D6 : Data pin 6
- GLCD_D7 : Data pin 7
- GLCD_CS1 : Chip select 1 signal pin
- GLCD_CS2 : Chip select 2 signal pin
- GLCD_RS : Register select signal pin
- GLCD_RW : Read/Write Signal pin
375
MikroElektronika
Example
Notes
None.
MikroElektronika
376
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
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
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
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
Nothing.
Requires
Example
Glcd_Set_Page(5);
Notes
For side, x axis and page layout explanation see schematic at the bottom of this page.
377
MikroElektronika
Description Reads data from from the current location of Glcd memory and moves to the next location.
Parameters None.
Returns
Requires
Example
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
Returns
Nothing.
Description Writes one byte to the current location in Glcd memory and moves to the next location.
Parameters :
- data_: data to be written
Requires
Example
MikroElektronika
378
Nothing.
Requires
Example
// Clear screen
Glcd_Fill(0);
Notes
None.
Glcd_Dot
Prototype
Nothing.
Requires
Example
Notes
For x and y axis layout explanation see schematic at the bottom of this page.
Glcd_Line
Prototype
void Glcd_Line(int x_start, int y_start, int x_end, int y_end, unsigned
short color);
Nothing.
Requires
Example
Notes
None.
379
MikroElektronika
Nothing.
Requires
Example
Notes
None.
Glcd_H_Line
Prototype
Nothing.
Requires
Example
Notes
None.
MikroElektronika
380
Nothing.
Requires
Example
Notes
None.
Glcd_Rectangle_Round_Edges
Prototype
Nothing.
Requires
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.
381
MikroElektronika
Nothing.
Requires
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
Nothing.
Requires
Example
Notes
None.
MikroElektronika
382
Nothing.
Requires
Example
Notes
None.
Glcd_Circle_Fill
Prototype
Nothing.
Requires
Example
Notes
None.
383
MikroElektronika
short
aFontWidth,
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 mikroC PRO for dsPIC30/33 and PIC24
character set and regular ASCII set (eg. if A is 65 in ASCII character, and A is 45 in the mikroC PRO
for dsPIC30/33 and PIC24 character set, aFontOffs is 20). Demo fonts supplied with the library have
an offset of 32, which means that they start with space.
The user can use fonts given in the file __Lib_GLCDFonts file located in the Uses folder or create
his own fonts.
List of supported fonts:
- Font_Glcd_System3x5
- Font_Glcd_System5x7
- Font_Glcd_5x7
- Font_Glcd_Character8x7
For the sake of the backward compatibility, these fonts are supported also:
- System3x5 (equivalent to Font_Glcd_System3x5)
- FontSystem5x7_v2 (equivalent to Font_Glcd_System5x7)
- font5x7 (equivalent to Font_Glcd_5x7)
- Character8x7 (equivalent to Font_Glcd_Character8x7)
Returns
Nothing.
Requires
Example
// Use the custom 5x7 font myfont which starts with space (32):
Glcd_Set_Font(&myfont, 5, 7, 32);
Notes
None.
MikroElektronika
384
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
Notes
For x axis and page layout explanation see schematic at the bottom of this page.
Glcd_Write_Text
Prototype
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
Notes
For x axis and page layout explanation see schematic at the bottom of this page.
385
MikroElektronika
Nothing.
Requires
Example
Notes
Use the mikroC PRO for dsPIC30/33 and PIC24 integrated Glcd Bitmap Editor, Tools > Glcd Bitmap
Editor, to convert image to a constant array suitable for displaying on Glcd.
Glcd_PartialImage
Prototype
Nothing.
Requires
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 mikroC PRO for dsPIC30/33 and PIC24 integrated Glcd Bitmap Editor, Tools > Glcd Bitmap
Editor, to convert image to a constant array suitable for displaying on Glcd.
MikroElektronika
386
void main() {
unsigned short ii;
char *someText;
#define COMPLETE_EXAMPLE
ADPCFG = 0xFFFF;
387
MikroElektronika
// Initialize GLCD
// Clear GLCD
while(1) {
#ifdef COMPLETE_EXAMPLE
Glcd_Image(truck_bmp);
delay2S(); delay2S();
#endif
// Draw image
Glcd_Fill(0x00);
// Clear GLCD
Glcd_Box(62,40,124,56,1);
Glcd_Rectangle(5,5,84,35,1);
Glcd_Line(0, 0, 127, 63, 1);
delay2S();
// Draw box
// Draw rectangle
// Draw line
delay2S();
Glcd_Fill(0x00);
#ifdef COMPLETE_EXAMPLE
Glcd_Set_Font(Character8x7, 8, 7, 32);
in Uses folder
#endif
Glcd_Write_Text("mikroE", 1, 7, 2);
// Clear GLCD
// Choose font, see __Lib_GLCDFonts.c
// Write string
// Draw circles
// Draw box
#ifdef COMPLETE_EXAMPLE
Glcd_Fill(0xFF);
// Fill GLCD
Glcd_Set_Font(Character8x7, 8, 7, 32);
someText = 8x7 Font;
Glcd_Write_Text(someText, 5, 0, 2);
delay2S();
// Change font
Glcd_Set_Font(System3x5, 3, 5, 32);
someText = 3X5 CAPITALS ONLY;
Glcd_Write_Text(someText, 60, 2, 2);
delay2S();
// Change font
MikroElektronika
// Write string
// Write string
388
// Change font
// Write string
HW Connection
Glcd HW connection
389
MikroElektronika
IC Library
The IC full master IC module is available with a number of the dsPIC30/33 and PIC24 MCU models. The mikroC PRO
for dsPIC30/33 and PIC24 provides a library which supports the master IC mode.
Important :
- IC library routines require you to specify the module you want to use. To select the desired IC module, simply
change the letter x in the routine prototype for a number from 1 to 3.
- Number of IC modules per MCU differs from chip to chip. Please, read the appropriate datasheet before utilizing
this library.
Library Routines
- I2Cx_Init
- I2Cx_Start
- I2Cx_Restart
- I2Cx_Is_Idle
- I2Cx_Read
- I2Cx_Write
- I2Cx_Stop
I2Cx_Init
Prototype
Description Configures and initializes the desired IC module with default settings.
This function enables the IC module by setting the I2CEN bit. The rest of the bits in IC control register
remains unchanged. Default initialization (after reset) of IC module is:
- continue operation in IDLE mode
- IPMI mode disabled
- 7-bit slave address
- slew rate control enabled
- general call address disabled
- software or receive clock stretching disabled
Parameters - scl: requested serial clock rate.
Returns
Nothing.
Requires
Example
Notes
Refer to the MCUs datasheet for correct values of the scl in respect with Fosc.
IC library routines require you to specify the module you want to use. To select the desired IC
module, simply change the letter x in the routine prototype for a number from 1 to 3.
Number of IC modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
390
void I2Cx_Start();
Nothing.
Requires
Example
Notes
IC library routines require you to specify the module you want to use. To select the desired IC
module, simply change the letter x in the routine prototype for a number from 1 to 3.
Number of IC modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
I2Cx_Restart
Prototype
void I2Cx_Restart();
Nothing.
Requires
Example
Notes
IC library routines require you to specify the module you want to use. To select the desired IC
module, simply change the letter x in the routine prototype for a number from 1 to 3.
Number of IC modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
391
MikroElektronika
unsigned I2Cx_Is_Idle();
Description Waits for the IC bus to become free. This is a blocking function.
Parameters None.
Returns
- 0 if IC bus is free.
- 1 if IC bus is not free.
Requires
Example
Notes
IC library routines require you to specify the module you want to use. To select the desired IC
module, simply change the letter x in the routine prototype for a number from 1 to 3.
Number of IC modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
I2Cx_Read
Prototype
Received data.
Requires
Example
Notes
IC library routines require you to specify the module you want to use. To select the desired IC
module, simply change the letter x in the routine prototype for a number from 1 to 3.
Number of IC modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
392
Requires
Example
Notes
IC library routines require you to specify the module you want to use. To select the desired IC
module, simply change the letter x in the routine prototype for a number from 1 to 3.
Number of IC modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
I2Cx_Stop
Prototype
void I2Cx_Stop();
Nothing.
Requires
Example
Notes
IC library routines require you to specify the module you want to use. To select the desired IC
module, simply change the letter x in the routine prototype for a number from 1 to 3.
Number of IC modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
393
MikroElektronika
LATB = 0;
TRISB = 0;
I2C1_Init(100000);
I2C1_Start();
I2C1_Write(0xA2);
I2C1_Write(2);
I2C1_Write(0xF0);
I2C1_Stop();
//
//
//
//
//
//
//
//
//
//
//
//
//
Delay_100ms();
I2C1_Start();
I2C1_Write(0xA2);
I2C1_Write(2);
I2C1_Restart();
I2C1_Write(0xA3);
LATB = I2C1_Read(0u);
I2C1_Stop();
}
HW Connection
MikroElektronika
394
Keypad Library
The mikroC PRO for dsPIC30/33 and PIC24 provides a library for working with 4x4 keypad. The library routines can
also be used with 4x1, 4x2, or 4x3 keypad. For connections explanation see schematic at the bottom of this page.
Example :
extern
sfr
keypadPort;
unsigned
int
Keypad Port.
Library Routines
- Keypad_Init
- Keypad_Key_Press
- Keypad_Key_Click
Keypad_Init
Prototype
void Keypad_Init();
Nothing.
Requires
Global variable :
- keypadPort - Keypad port
must be defined before using this function.
Example
Notes
395
MikroElektronika
unsigned Keypad_Key_Press();
Description Reads the key from keypad when key gets pressed.
Parameters None.
Returns
Requires
Port needs to be initialized for working with the Keypad library, see Keypad_Init.
Example
unsigned kp;
...
kp = Keypad_Key_Press();
Notes
None
Keypad_Key_Click
Prototype
unsigned Keypad_Key_Click();
Description Call to Keypad_Key_Click is a blocking call: the function waits until some key is pressed and
released. When released, the function returns 1 to 16, depending on the key. If more than one key is
pressed simultaneously the function will wait until all pressed keys are released. After that the function
will return the code of the first pressed key.
Parameters None.
Returns
Requires
Port needs to be initialized for working with the Keypad library, see Keypad_Init.
Example
kp = Keypad_Key_Click();
Notes
None
MikroElektronika
396
// Initialize Keypad
do {
kp = 0;
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
kp
kp
kp
kp
kp
kp
kp
kp
kp
kp
kp
kp
kp
kp
kp
kp
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
}
UART1_Write(kp);
} while (1);
397
49;
50;
51;
65;
52;
53;
54;
66;
55;
56;
57;
67;
42;
48;
35;
68;
break;
break;
break;
break;
break;
break;
break;
break;
break;
break;
break;
break;
break;
break;
break;
break;
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
1
2
3
A
4
5
6
B
7
8
9
C
*
0
#
D
MikroElektronika
MikroElektronika
398
Lcd Library
The mikroC PRO for dsPIC30/33 and PIC24 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.
Keypad_Key_Click
The following variables must be
defined in all projects using Lcd Description :
Library :
Example :
Enable line.
Data 4 line.
Data 5 line.
Data 6 line.
Data 7 line.
extern
sfr
Direction;
sbit
LCD_RS_
extern
sfr
Direction;
sbit
LCD_EN_
extern
sfr
Direction;
sbit
LCD_D4_
extern
sfr
Direction;
sbit
LCD_D5_
extern
sfr
Direction;
sbit
LCD_D6_
extern
sfr
Direction;
sbit
LCD_D7_
Library Routines
- Lcd_Init
- Lcd_Out
- Lcd_Out_Cp
- Lcd_Chr
- Lcd_Chr_Cp
- Lcd_Cmd
399
MikroElektronika
void Lcd_Init();
Nothing.
Requires
Global variables:
- LCD_RS: Register Select (data/instruction) signal pin
- LCD_EN: Enable signal pin
- LCD_D4: Data bit 4
- LCD_D5: Data bit 5
- LCD_D6: Data bit 6
- LCD_D7: Data bit 7
- LCD_RS_Direction: Direction of the Register Select pin
- LCD_EN_Direction: Direction of the Enable signal pin
- LCD_D4_Direction: Direction of the Data 4 pin
- LCD_D5_Direction: Direction of the Data 5 pin
- LCD_D6_Direction: Direction of the Data 6 pin
- LCD_D7_Direction: Direction of the Data 7 pin
must be defined before using this function.
Example
Notes
None
MikroElektronika
400
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
Example
Notes
None
Lcd_Out_Cp
Prototype
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
Example
Notes
None
Lcd_Chr
Prototype
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
Example
Notes
None
401
MikroElektronika
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
Example
Notes
None
Lcd_Cmd
Prototype
Nothing.
Requires
Example
Notes
Predefined constants can be passed to the function, see Available Lcd Commands.
Purpose
_LCD_FIRST_ROW
_LCD_SECOND_ROW
_LCD_THIRD_ROW
_LCD_FOURTH_ROW
_LCD_CLEAR
Clear display
_LCD_RETURN_HOME
_LCD_CURSOR_OFF
_LCD_UNDERLINE_ON
Underline cursor on
_LCD_BLINK_CURSOR_ON
Blink cursor on
_LCD_MOVE_CURSOR_LEFT
_LCD_MOVE_CURSOR_RIGHT
_LCD_TURN_ON
_LCD_TURN_OFF
_LCD_SHIFT_LEFT
_LCD_SHIFT_RIGHT
MikroElektronika
402
txt1[]
txt2[]
txt3[]
txt4[]
=
=
=
=
"mikroElektronika";
"EasydsPIC4A";
"Lcd4bit";
"example";
char i;
// Loop variable
void Move_Delay() {
Delay_ms(500);
}
void main(){
ADPCFG = 0xFFFF;
Lcd_Init();
// Initialize LCD
Lcd_Cmd(_LCD_CLEAR);
Lcd_Cmd(_LCD_CURSOR_OFF);
Lcd_Out(1,6,txt3);
// Clear display
// Cursor off
// Write text in first row
Lcd_Out(2,6,txt4);
Delay_ms(2000);
Lcd_Cmd(_LCD_CLEAR);
Lcd_Out(1,1,txt1);
Lcd_Out(2,5,txt2);
// Clear display
Delay_ms(2000);
403
MikroElektronika
// Endless loop
// Move text to the left 7 times
}
}
Lcd HW connection
MikroElektronika
404
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.
Keypad_Key_Click
The following variables must
be defined in all projects using Description :
Manchester Code Library:
Example :
Receive line.
Transmit line.
extern sfr
Direction;
sbit
MANRXPIN_
sbit
MANRXPIN_Direction
TRISF0_bit;
at
extern sfr
Direction;
sbit
MANTXPIN_
sbit
MANTXPIN_Direction
TRISF1_bit;
at
405
MikroElektronika
Man_Receive_Init
Prototype
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
Requires
Global variables :
- MANRXPIN : Receive line
- MANRXPIN_Direction : Direction of the receive pin
must be defined before using this function.
Example
Initialize Receiver
sbit MANRXPIN at RF0_bit;
sbit MANRXPIN_Direction at TRISF0s_bit;
...
if (Man_Receive_Init() == 0) {
...
}
Notes
In case of multiple persistent errors on reception, the user should call this routine once again or
Man_Synchro routine to enable synchronization.
MikroElektronika
406
Requires
To use this function, the user must prepare the MCU for receiving. See Man_Receive_Init routines.
Example
Notes
None.
Man_Send_Init
Prototype
void Man_Send_Init();
Nothing.
Requires
Global variables :
- MANTXPIN : Transmit line
- MANTXPIN_Direction : Direction of the transmit pin
must be defined before using this function.
Example
// Initialize Transmitter:
sbit MANTXPIN at LATF1_bit;
sbit MANTXPIN_Direction at TRISF1_bit;
...
Man_Send_Init();
Notes
None.
407
MikroElektronika
Nothing.
Requires
To use this function, the user must prepare the MCU for sending. See Man_Send_Init routine.
Example
Notes
Man_Synchro
Prototype
Description Measures half of the manchester bit length with 10us resolution.
Parameters None.
Returns
Requires
To use this function, you must first prepare the MCU for receiving. See Man_Receive_Init.
Example
Notes
None.
MikroElektronika
408
void 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
// reset counter
else
counter++;
// increment counter
T1IF_bit = 0;
void main() {
...
if (Man_Receive_Init() == 0) {
...
}
...
// try Man_Receive with blocking prevention mechanism
IPC0
= IPC0 | 0x1000;
// Interrupt priority level = 1
T1IE_bit= 1;
// Enable Timer1 interrupts
T1CON = 0x8030;
// Timer1 ON, internal clock FCY, prescaler
1:256
}
Notes
409
data1 = Man_Receive(&error);
T1IE_bit= 0;
Interrupts should be disabled before using Manchester routines again (see note at the top of this
page).
MikroElektronika
Lcd_Init();
Lcd_Cmd(_LCD_CLEAR);
// Initialize LCD
// Clear LCD display
Man_Receive_Init();
// Initialize Receiver
while (1) {
// Endless loop
Lcd_Cmd(_LCD_FIRST_ROW);
while (1) {
temp = Man_Receive(&error);
if (temp == 0x0B)
break;
if (error)
break;
}
//
//
//
//
//
MikroElektronika
410
}
}
The following code is code for the Manchester receiver, it shows how to use the Manchester Library for receiving
data:
Copy Code To Clipboard
// Manchester module connections
sbit MANRXPIN at RF0_bit;
sbit MANRXPIN_Direction at TRISF0_bit;
sbit MANTXPIN at LATF1_bit;
sbit MANTXPIN_Direction at TRISF1_bit;
// End Manchester module connections
char index, character;
char s1[] = "mikroElektronika";
void main() {
ADPCFG = 0xFFFF;
TRISB = 0;
LATB = 0;
Man_Send_Init();
// Initialize transmitter
while (1) {
Man_Send(0x0B);
Delay_ms(100);
// Endless loop
// Send "start" byte
// Wait for a while
character = s1[0];
index = 0;
411
MikroElektronika
//
//
//
//
//
}
}
Connection Example
MikroElektronika
412
413
MikroElektronika
Example :
extern sfr
Select;
sbit
Mmc_Chip_
Library Routines
- Mmc_Init
- Mmc_Read_Sector
- Mmc_Write_Sector
- Mmc_Read_Cid
- Mmc_Read_Csd
Routines for file handling:
- Mmc_Fat_Init
- Mmc_Fat_QuickFormat
- Mmc_Fat_Assign
- Mmc_Fat_Reset
- Mmc_Fat_Read
- Mmc_Fat_Rewrite
- Mmc_Fat_Append
- Mmc_Fat_Delete
- Mmc_Fat_Write
- Mmc_Fat_Set_File_Date
- Mmc_Fat_Get_File_Date
- Mmc_Fat_Get_File_Date_Modified
- Mmc_Fat_Get_File_Size
- Mmc_Fat_Get_Swap_File
MikroElektronika
414
Requires
Example
Notes
None.
415
MikroElektronika
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
Requires
Example
Notes
None.
Mmc_Write_Sector
Prototype
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
Requires
Example
Notes
None.
MikroElektronika
416
Requires
Example
Notes
None.
Mmc_Read_Csd
Prototype
Requires
Example
Notes
None.
417
MikroElektronika
Description Initializes MMC/SD card, reads MMC/SD FAT16 boot sector and extracts necessary data needed by
the library.
Parameters None.
Returns
Requires
Global variables :
- Mmc_Chip_Select: Chip Select line
- Mmc_Chip_Select_Direction: Direction of the Chip Select pin
must be defined before using this function.
The appropriate hardware SPI module must be previously initialized. See the SPIx_Init, SPIx_Init_
Advanced routines.
Example
Notes
MikroElektronika
418
Requires
Example
Notes
419
MikroElektronika
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
0x01
Read Only
0x02
Hidden
0x04
System
0x08
Volume Label
0x10
Subdirectory
0x20
Archive
0x40
0x80
File creation flag. If file does not exist and this flag is
set, a 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
Notes
MikroElektronika
420
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.
The file must be previously assigned. See Mmc_Fat_Assign.
Example
Notes
None.
Mmc_Fat_Read
Prototype
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.
The file must be previously assigned. See Mmc_Fat_Assign.
The file must be opened for reading. See Mmc_Fat_Reset.
Example
char character;
...
Mmc_Fat_Read(&character);
Notes
None.
421
MikroElektronika
void 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.
The file must be previously assigned. See Mmc_Fat_Assign.
Example
Notes
None.
Mmc_Fat_Append
Prototype
void 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.
The file must be previously assigned. See Mmc_Fat_Assign.
Example
Notes
None.
Mmc_Fat_Delete
Prototype
void Mmc_Fat_Delete();
Nothing.
Requires
MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
The file must be previously assigned. See Mmc_Fat_Assign.
Example
Notes
None.
MikroElektronika
422
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.
The file must be previously assigned. See Mmc_Fat_Assign.
The file must be opened for writing. See Mmc_Fat_Rewrite or Mmc_Fat_Append.
Example
char file_contents[42];
...
Mmc_Fat_Write(file_contents, 42); // write data to the assigned file
Notes
None.
Mmc_Fat_Set_File_Date
Prototype
Description Sets the date/time stamp. Any subsequent file write operation will write this stamp to the currently
assigned files 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.
The file must be previously assigned. See Mmc_Fat_Assign.
The file must be opened for writing. See Mmc_Fat_Rewrite or Mmc_Fat_Append.
Example
Notes
None.
423
MikroElektronika
Nothing.
Requires
MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
The file must be previously assigned. See Mmc_Fat_Assign.
Example
Notes
None.
MikroElektronika
424
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
Example
Mmc_Fat_Get_File_Size
Prototype
Description This function reads size of the currently assigned file in bytes.
Parameters None.
Returns
Requires
MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
The file must be previously assigned. See Mmc_Fat_Assign.
Example
Notes
None
425
MikroElektronika
long
sectors_cnt,
char*
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. Its 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:
Bit
Mask
Description
0x01
Read Only
0x02
Hidden
0x04
System
0x08
Volume Label
0x10
Subdirectory
0x20
Archive
0x40
0x80
Not used
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
426
MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
Example
Notes
Library Example
The following example demonstrates usage of the MMC and MMC_FAT routines.
Copy Code To Clipboard
// MMC module connections
sbit Mmc_Chip_Select
at LATF0_bit; // for writing to output pin always use latch
sbit Mmc_Chip_Select_Direction at TRISF0_bit;
// eof MMC module connections
const LINE_LEN = 43;
char err_txt[20]
= FAT16 not found;
char file_contents[LINE_LEN] = XX MMC/SD FAT16 library by Anton Rieckertn;
char
filename[14] = MIKRO00x.TXT;
// File names
unsigned short loop, loop2;
unsigned long i, size;
char
Buffer[512];
// UART1 write text and new line (carriage return + line feed)
void UART1_Write_Line(char *uart_text) {
UART1_Write_Text(uart_text);
UART1_Write(13);
UART1_Write(10); for(loop = 1; loop <= 99; loop++) {
UART1_Write(.);
file_contents[0] = loop / 10 + 48;
file_contents[1] = loop % 10 + 48;
Mmc_Fat_Write(file_contents, LINE_LEN-1); // write data to the assigned file
}
}
427
MikroElektronika
MikroElektronika
428
429
MikroElektronika
if (size) {
LongToStr((signed long)size, err_txt);
UART1_Write_Line(err_txt);
for(i=0; i<5000; i++) {
Mmc_Write_Sector(size++, Buffer);
UART1_Write('.');
}
}
}
//-------------- Main. Uncomment the function(s) to test the desired operation(s)
void main() {
#define COMPLETE_EXAMPLE
// comment this line to make simpler/smaller example
PORTD = 0;
TRISD = 0;
PORTF = 0;
TRISF = 0;
ADPCFG = 0xFFFF;
// initialize AN pins as digital
//--- set up USART for the file read
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);
UART1_Init(19200);
Delay_ms(100);
MikroElektronika
430
HW Connection
431
MikroElektronika
OneWire Library
The OneWire library provides routines for communication via the Dallas OneWire protocol, e.g. with DS18x20 digital
thermometer. OneWire is a Master/Slave protocol, and all communication cabling required is a single wire. OneWire
enabled devices should have open collector drivers (with single pull-up resistor) on the shared data line.
Slave devices on the OneWire bus can even get their power supply from data line. For detailed schematic see device
datasheet.
Some basic characteristics of this protocol are:
- single master system,
- low cost,
- low transfer rates (up to 16 kbps),
- fairly long distances (up to 300 meters),
- small data transfer packages.
Each OneWire device also has a unique 64-bit registration number (8-bit device type, 48-bit serial number and 8-bit
CRC), so multiple slaves can co-exist on the same bus.
Important :
- Oscillator frequency Fosc needs to be at least 4MHz in order to use the routines with Dallas digital thermometers.
- This library implements time-based activities, so interrupts need to be disabled when using OneWire library.
Library Routines
- Ow_Reset
- Ow_Read
- Ow_Write
Ow_Reset
Prototype
Requires
Example
Notes
None.
MikroElektronika
432
Requires
Example
Notes
None.
Ow_Write
Prototype
void Ow_Write(unsigned int *port, unsigned int pin, unsigned short data_);
Nothing.
Requires
Example
Notes
None.
433
MikroElektronika
MikroElektronika
434
//
//
//
//
Extract
Extract
Extract
Extract
thousands digit
hundreds digit
tens digit
ones digit
Lcd_Init();
// Initialize LCD
Lcd_Cmd(_LCD_CLEAR);
// Clear LCD
Lcd_Cmd(_LCD_CURSOR_OFF);
// Turn cursor off
Lcd_Out(1, 1, " Temperature:
");
// Print degree character, 'C' for Centigrades
Lcd_Chr(2,13,223); // different LCD displays have different char code for degree
// if you see greek alpha letter try typing 178 instead of 223
Lcd_Chr(2,14,'C');
//--- main loop
do {
//--- perform temperature reading
Ow_Reset(&PORTF, 6);
Ow_Write(&PORTF, 6, 0xCC);
Ow_Write(&PORTF, 6, 0x44);
Delay_us(120);
Ow_Reset(&PORTF, 6);
Ow_Write(&PORTF, 6, 0xCC);
Ow_Write(&PORTF, 6, 0xBE);
Delay_ms(400);
435
MikroElektronika
MikroElektronika
436
Library Routines
- Unlock_IOLOCK
- Lock_IOLOCK
- PPS_Mapping
Unlock_IOLOCK
Prototype
void Unlock_IOLOCK();
Nothing.
Requires
Nothing.
Example
Unlock_IOLOCK();
Notes
None.
Lock_IOLOCK
Prototype
void Lock_IOLOCK();
Nothing.
Requires
Nothing.
Example
Lock_IOLOCK();
437
MikroElektronika
unsigned PPS_Mapping(unsigned
unsigned short funct_name);
short
rp_num,
unsigned
short
direction,
Description Sets desired internal MCU module to be mapped on the requested pins.
Parameters - rp_num: Remappable pin number. Consult the appropriate datasheet for adequate values.
- direction: Sets requested pin to be used as an input or output. See Direction Parameters for
adequate values.
- funct_name: Selects internal MCU module function for usage. See Input Functions or Output
Functions for adequate values.
Returns
Requires
Nothing.
Example
Notes
None.
Direction Parameters
Direction Parameter
Description
_INPUT
_OUTPUT
Input Functions
Function Name
Description
_IC2
Input Capture 2
_CIRX
ECAN1 Receive
_IC3
Input Capture 3
_COFSI
_IC4
Input Capture 4
_CSCKI
_IC5
Input Capture 5
_CSDI
_IC6
Input Capture 6
_FLTA1
PWM1 Fault
_IC7
Input Capture 7
_FLTA2
PWM2 Fault
_IC8
Input Capture 8
_FLTA3
PWM3 Fault
_IC9
Input Capture 9
_FLTA4
PWM4 Fault
_INDX1
QEI1 Index
_FLTA5
PWM5 Fault
_INDX2
QEI2 Index
_FLTA6
PWM6 Fault
_INT1
External Interrupt 1
_FLTA7
PWM7 Fault
_INT2
External Interrupt 2
_FLTA8
PWM8 Fault
_INT3
External Interrupt 3
_IC1
Input Capture 1
_INT4
External Interrupt 4
MikroElektronika
438
QEI1 Phase A
_T1CK
_QEA2
QEI2 Phase A
_T2CK
_QEB1
QEI1 Phase B
_T3CK
_QEB2
QEI2 Phase B
_T4CK
_SCK1IN
_T5CK
_SCK2IN
_U1CTS
_SCK3IN
_U2CTS
_SDI1
_U3CTS
_SDI2
_U4CTS
_SDI3
_U1RX
UART1 Receive
_SS1IN
_U2RX
UART2 Receive
_SS2IN
_U3RX
UART3 Receive
_U4RX
UART4 Receive
_SS3IN
Output Functions
Function Name
Description
_NULL
The NULL function is assigned to all RPn outputs at device Reset and disables the RPn
output function.
_ACMP1
_ACMP2
_ACMP3
_ACMP4
_C1OUT
Comparator 1 Output
_C2OUT
Comparator 2 Output
_C3OUT
Comparator 3 Output
_COFSOS
_CSCKO
_CSDO
_CTPLS
_C1TX
ECAN1 Transmit
_OC1
Output Compare 1
_OC2
Output Compare 2
_OC3
Output Compare 3
_OC4
Output Compare 4
_OC5
Output Compare 5
_OC6
Output Compare 6
_OC7
Output Compare 7
_OC8
Output Compare 8
439
MikroElektronika
Output Compare 9
_OCFA
_OCFB
_PWM4H
_PWM4L
_REFCLKO
_SCK1OUT
_SCK2OUT
_SCK3OUT
_SDO1
_SDO2
_SDO3
_SS1OUT
_SS2OUT
_SS3OUT
_SYNCI1
_SYNCI2
_SYNCO1
RPn tied to external device synchronization signal via PWM master time base
_U1RTS
_U2RTS
_U3RTS
_U4RTS
_U1TX
UART1 Transmit
_U2TX
UART2 Transmit
_U3TX
UART3 Transmit
_U4TX
UART4 Transmit
_UPDN
_UPDN1
_UPDN2
MikroElektronika
440
Example :
Reset line.
sbit SPExpanderRST_Direction at
TRISF0_bit;
at
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
441
MikroElektronika
Nothing.
Requires
Global variables :
- SPExpanderCS: Chip Select line
- SPExpanderRST: Reset line
- SPExpanderCS_Direction: Direction of the Chip Select pin
- SPExpanderRST_Direction: Direction of the Reset pin
must be defined before using this function.
SPI module needs to be initialized. See SPIx_Init and SPIx_Init_Advanced routines.
Example
Notes
None.
MikroElektronika
442
Nothing.
Requires
Example
Notes
443
None.
MikroElektronika
Byte read.
Requires
Example
Notes
None.
Expander_Write_Byte
Prototype
Byte read.
Requires
Example
Notes
None.
Expander_Read_PortA
Prototype
Byte read.
Requires
Example
Notes
None.
MikroElektronika
444
Byte read.
Requires
Example
Notes
None.
Expander_Read_PortAB
Prototype
Description The function reads word from Port Expanders 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
Example
Notes
None.
445
MikroElektronika
Nothing.
Requires
Example
Notes
None.
Expander_Write_PortB
Prototype
Nothing.
Requires
Example
Notes
None.
MikroElektronika
446
Nothing.
Requires
Example
Notes
None.
Expander_Set_DirectionPortA
Prototype
Nothing.
Requires
Example
Notes
None.
447
MikroElektronika
Nothing.
Requires
Example
Notes
None.
Expander_Set_DirectionPortAB
Prototype
void
Expander_Set_DirectionPortAB(char
Direction);
ModuleAddress,
unsigned
int
Description The function sets Port Expanders 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 Directions higher byte. Data to be written to the PortB direction register are passed
in Directions 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
Example
Notes
None.
Expander_Set_PullUpsPortA
Prototype
Description The function sets Port Expanders 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
Example
Notes
None.
MikroElektronika
448
Description The function sets Port Expanders 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
Example
Notes
None.
Expander_Set_PullUpsPortAB
Prototype
Description The function sets Port Expanders 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 PullUpss higher byte. PortB pull up/down resistors configuration is
passed in PullUpss 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
Example
Notes
None.
449
MikroElektronika
Expander_Init(0);
Expander_Set_DirectionPortA(0, 0x00);
Expander_Set_DirectionPortB(0,0xFF);
Expander_Set_PullUpsPortB(0,0xFF);
pins
while(1) {
Expander_Write_PortA(0, i++);
PORTB = Expander_Read_PortB(0);
Delay_ms(100);
}
MikroElektronika
450
451
MikroElektronika
PS/2 Library
The mikroC PRO for dsPIC30/33 and PIC24 provides a library for communication with the common PS/2 keyboard.
Important :
- The library does not utilize interrupts for data retrieval, and requires the oscillator clock to be at least 6MHz.
- The pins to which a PS/2 keyboard is attached should be connected to the pull-up resistors.
- Although PS/2 is a two-way communication bus, this library does not provide MCU-to-keyboard communication; e.g.
pressing the Caps Lock key will not turn on the Caps Lock LED.
Example :
at
at
extern sfr
Direction;
sbit
Library Routines
- Ps2_Config
- Ps2_Key_Read
MikroElektronika
452
void Ps2_Config();
Description Initializes the MCU for work with the PS/2 keyboard.
Parameters None.
Returns
Nothing.
Requires
Global variables :
- PS2_Data: Data signal line
- PS2_Clock: Clock signal line
- PS2_Data_Direction: Direction of the Data pin
- PS2_Clock_Direction: Direction of the Clock pin
must be defined before using this function.
Example
Notes
None.
Ps2_Key_Read
Prototype
Requires
Example
Notes
None.
453
MikroElektronika
Value returned
F1
F2
F3
F4
F5
F6
F7
F8
F9
F10
10
F11
11
F12
12
Enter
13
Page Up
14
Page Down
15
Backspace
16
Insert
17
Delete
18
Windows
19
Ctrl
20
Shift
21
Alt
22
Print Screen
23
Pause
24
Caps Lock
25
End
26
Home
27
Scroll Lock
28
Num Lock
29
Left Arrow
30
Right Arrow
31
Up Arrow
32
Down Arrow
33
Escape
34
Tab
35
MikroElektronika
454
PS2_Data
PS2_Clock
PS2_Data_Direction
PS2_Clock_Direction
at
at
at
at
RB0_bit;
RB1_bit;
TRISB0_bit;
TRISB1_bit;
UART1_Init(19200);
Ps2_Config();
Delay_ms(100);
UART1_Write_Text("Ready");
UART1_Write(10);
UART1_Write(13);
do {
if (Ps2_Key_Read(&keydata, &special, &down)) {
if (down && (keydata == 16)) {
UART1_Write(0x08);
}
else if (down && (keydata == 13)) {
UART1_Write('r');
terminal
//Usart_Write('n');
terminal also expects line feed
// Line Feed
// Carriage return
// Backspace
// Enter
// send carriage return to usart
// uncomment this line if usart
// for new line transition
}
else if (down && !special && keydata) {
UART1_Write(keydata);
}
}
Delay_ms(1);
} while (1);
// debounce
455
MikroElektronika
PWM Library
The CCP module is available with a number of dsPIC30/33 and PIC24 MCUs. mikroC PRO for dsPIC30/33 and PIC24
provides a library which simplifies using of the PWM HW Module.
Important : PWM module uses either Timer2 or Timer3 module.
Library Routines
- PWM_Init
- PWM_Set_Duty
- PWM_Start
- PWM_Stop
MikroElektronika
456
Requires
Example
Notes
Number of available PWM channels depends on MCU. Refer to MCU datasheet for details.
PWM_Set_Duty
Prototype
Nothing.
Requires
Example
Notes
Number of available PWM channels depends on MCU. Refer to MCU datasheet for details.
457
MikroElektronika
Nothing.
Requires
Example
Notes
Number of available PWM channels depends on MCU. Refer to MCU datasheet for details.
PWM_Stop
Prototype
Nothing.
Requires
Example
Notes
Number of available PWM channels depends on MCU. Refer to MCU datasheet for details.
Library Example
The example changes PWM duty ratio on channels 1 and 2 continuously. If LEDs are connected to channels 1 and 2,
a gradual change of emitted light will be noticeable.
Copy Code To Clipboard
unsigned int current_duty, old_duty, current_duty1, old_duty1;
unsigned int pwm_period1, pwm_period2;
void InitMain() {
ADPCFG = 0xFFFF;
TRISB = 0xFFFF;
PORTD = 0;
TRISD = 0;
}
void main() {
InitMain();
current_duty = 16;
current_duty1 = 16;
MikroElektronika
//
//
//
//
458
}
}
459
MikroElektronika
PWM demonstration
Library Routines
- PWMx_Mc_Init
- PWMx_Mc_Set_Duty
- PWMx_Mc_Start
- PWMx_Mc_Stop
MikroElektronika
460
Description Initializes the Motor Control PWM module with duty ratio 0. The function calculates timer period, writes
it to the MCUs PTPER register and returns it as the function result.
Parameters - freq_hz: PWM frequency in Hz (refer to device datasheet for correct values in respect with Fosc)
- pair_output_mode: output mode for output pin pairs: 1 = independent, 0 = complementary.
If pair_output_mode.B0 is equal to 1 then PWM channels PWM1L and PWM1H will be
independent,
If pair_output_mode.B1 is equal to 0 then PWM channels PWM2L and PWM2H will be
complementary, ...
If pair_output_mode.Bn is equal to 1 then PWM channels PWM(n+1)L and PWM(n+1)H will be
independent,
If pair_output_mode.Bn is equal to 0 then PWM channels PWM(n+1)L and PWM(n+1)H will be
complementary.
- enable_output_x: bits <7..0> are enabling corresponding PWM channels <PWM4H, PWM3H,
PWM2H, PWM1H, PWM4L, PWM3L, PWM2L, PWM1L>.
If bit value is equal to 0 then corresponding PWM channel is disabled (pin is standard I/O).
If bit value is equal to 1 then corresponding PWM channel is enabled (pin is PWM output).
For detalied explanation consult the Motor Control PWM Module section in device datasheet
- clock_prescale_output_postscale: PWM clock prescaler/postscaler settings. Values <0..3>
and <0..15> correspond to prescaler/postscaler <1:1, 1:4, 1:16, 1:64> and <1:1, 1:2,
..., 1:16>
Returns
Requires
The dsPIC30/33 MCU must have the Motor Control PWM module.
Example
Notes
- Number of PWM modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
- PWM library routines require you to specify the module you want to use. To use the desired PWM
module, simply change the letter x in the routine prototype for a number from 1 to 2.
461
MikroElektronika
Nothing.
Requires
The dsPIC30/33 MCU must have the Motor Control PWM module.
The PWM module needs to be initalized. See the PWMx_Mc_Init function.
Example
Notes
- Number of PWM modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
- PWM library routines require you to specify the module you want to use. To use the desired PWM
module, simply change the letter x in the routine prototype for a number from 1 to 2.
PWMx_Mc_Start
Prototype
void PWMx_Mc_Start();
Description Starts the Motor Control PWM module (channels initialized in the PWMx_Mc_Init function).
Parameters None.
Returns
Nothing.
Requires
The dsPIC30/33 MCU must have the Motor Control PWM module.
The PWM module needs to be initalized. See the PWMx_Mc_Init function.
Example
Notes
- Number of PWM modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
- PWM library routines require you to specify the module you want to use. To use the desired PWM
module, simply change the letter x in the routine prototype for a number from 1 to 2.
MikroElektronika
462
void PWMx_Mc_Stop();
Nothing.
Requires
The dsPIC30/33 MCU must have the Motor Control PWM module.
Example
Notes
- Number of PWM modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
- PWM library routines require you to specify the module you want to use. To use the desired PWM
module, simply change the letter x in the routine prototype for a number from 1 to 2.
Library Example
The example changes PWM duty ratio on channel 1 continually. If LED is connected to the channel 1, a gradual change
of emitted light will be noticeable.
Copy Code To Clipboard
unsigned int i;
unsigned int duty_50;
void main(){
ADPCFG = 0xFFFF;
PORTB = 0xAAAA;
TRISB = 0;
Delay_ms(1000);
duty_50 = PWM1_MC_Init(5000, 0, 0x01, 0);
duty
PWM1_MC_Set_Duty(i = duty_50, 1);
PWM1_MC_Start();
do
{
i--;
PWM1_MC_Set_Duty(i, 1);
Delay_ms(10);
if (i == 0)
i = duty_50 * 2 - 1;
PORTB = i;
}
while(1);
463
MikroElektronika
RS-485 Library
RS-485 is a multipoint communication which allows multiple devices to be connected to a single bus. The mikroC PRO
for dsPIC30/33 and PIC24 provides a set of library routines for comfortable work with RS485 system using Master/
Slave architecture. Master and Slave devices interchange packets of information. Each of these packets contains
synchronization bytes, CRC byte, address byte and the data. Each Slave has unique address and receives only
packets addressed to it. The Slave can never initiate communication.
It is the users responsibility to ensure that only one device transmits via 485 bus at a time.
The RS-485 routines require the UART module. Pins of UART need to be attached to RS-485 interface transceiver,
such as LTC485 or similar (see schematic at the bottom of this page).
Library constants:
- START byte value = 150
- STOP byte value = 169
- Address 50 is the broadcast address for all Slaves (packets containing address 50 will be received by all Slaves
except the Slaves with addresses 150 and 169).
Important :
- The library uses the UART module for communication. The user must initialize the appropriate UART module before
using the RS-485 Library.
- For MCUs with multiple UART modules it is possible to initialize them and then switch by using the UART_Set_Active
routine.
MikroElektronika
464
Example :
Library Routines
- RS485Master_Init
- RS485Master_Receive
- RS485Master_Send
- RS485Slave_Init
- RS485Slave_Receive
- RS485Slave_Send
RS485Master_Init
Prototype
void RS485Master_Init();
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.
must be defined before using this routine.
UART HW module needs to be initialized. See UARTx_Init.
Example
Notes
None
465
MikroElektronika
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, 13
- 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
Example
char msg[8];
...
RS485Master_Receive(msg);
Notes
None
RS485Master_Send
Prototype
void RS485Master_Send(char
address);
*data_buffer,
char
datalen,
char
slave_
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
Example
char msg[8];
...
// send 3 bytes of data to Slave with address 0x12
RS485Master_Send(msg, 3, 0x12);
Notes
None
MikroElektronika
466
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. Valid values: 1
(for transmitting) and 0 (for receiving
- RS485_rxtx_pin_direction - direction of the RS-485 Transmit/Receive pin.
must be defined before using this routine.
UART HW module needs to be initialized. See UARTx_Init.
Example
Notes
467
None
MikroElektronika
Description Receives messages from Master. If Slave address and Message address field dont match then the
message will be discarded. Messages are multi-byte, so this routine must be called for each byte
received.
Parameters - data_buffer: 6 byte buffer for storing received data, in the following manner:
- data_buffer[0..2]: message content
- data_buffer[3]: number of message bytes received, 13
- data_buffer[4]: is set to 255 when message is received
- data_buffer[5]: is set to 255 if error has occurred
The routine automatically adjusts data[4] and data[5] upon every received message. These flags
need to be cleared by software.
Returns
Nothing.
Requires
Example
char msg[8];
...
RS485Slave_Read(msg);
Notes
None
RS485Slave_Send
Prototype
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 users
responsibility to ensure (by protocol) that only one device sends data via 485 bus at a time.
Example
char msg[8];
...
// send 2 bytes of data to the Master
RS485Slave_Send(msg, 2);
Notes
None
MikroElektronika
468
// Interrupt routine
void interrupt() org IVT_ADDR_U2RXINTERRUPT {
RS485Master_Receive(dat);
U2RXIF_bit = 0;
// ensure interrupt not pending
}
void main(){
long cnt = 0;
ADPCFG = 0xFFFF;
PORTB
PORTD
TRISB
TRISD
=
=
=
=
0;
0;
0;
0;
UART2_Init(9600);
Delay_ms(100);
RS485Master_Init();
dat[0]
dat[1]
dat[2]
dat[4]
dat[5]
dat[6]
=
=
=
=
=
=
0xAA;
0xF0;
0x0F;
0;
0;
0;
RS485Master_Send(dat,1,160);
469
MikroElektronika
// no nesting of interrupts
// ensure interrupt not pending
// enable intterupt
while (1){
// upon completed valid message receiving
//
data[4] is set to 255
cnt++;
if (dat[5]) {
PORTD = 0xAA;
}
if (dat[4]) {
cnt = 0;
dat[4] = 0;
j = dat[3];
for (i = 1; i <= dat[3]; i++) {
PORTB = dat[i-1];
}
dat[0] = dat[0]+1;
Delay_ms(1);
RS485Master_Send(dat,1,160);
}
if (cnt > 100000) {
PORTD ++;
cnt = 0;
RS485Master_Send(dat,1,160);
if (PORTD > 10)
RS485Master_Send(dat,1,50);
}
}
//
}
RS485 Slave code:
Copy Code To Clipboard
sbit rs485_rxtx_pin at RF2_bit;
sbit rs485_rxtx_pin_direction at TRISF2_bit;
char dat[9];
char i,j;
// Interrupt routine
void interrupt() org IVT_ADDR_U2RXINTERRUPT{
RS485Slave_Receive(dat);
U2RXIF_bit = 0;
// ensure interrupt not pending
}
MikroElektronika
470
=
=
=
=
0;
0;
0;
0;
UART2_Init(9600);
Delay_ms(100);
RS485Slave_Init(160);
dat[0]
dat[1]
dat[2]
dat[4]
dat[5]
dat[6]
=
=
=
=
=
=
0xAA;
0xF0;
0x0F;
0;
0;
0;
URXISEL1_U2STA_bit = 0;
URXISEL1_U2STA_bit = 0;
NSTDIS_bit = 1;
U2RXIF_bit = 0;
U2RXIE_bit = 1;
while (1) {
if (dat[5]) {
PORTD = 0xAA;
dat[5] = 0;
}
if (dat[4]) {
dat[4] = 0;
j = dat[3];
for (i = 1; i <= dat[3];i++){
PORTB = dat[i-1];
}
dat[0] = dat[0]+1;
Delay_ms(1);
RS485Slave_Send(dat,1);
}
}
// no nesting of interrupts
// ensure interrupt not pending
// enable intterupt
// if an error detected, signal it by
//
setting portd to 0xAA
// upon completed valid message receive
//
data[4] is set to 0xFF
471
MikroElektronika
Example of interfacing PC to dsPIC MCU via RS485 bus with LTC485 as RS-485 transceiver
MikroElektronika
472
// if exists
// if exists
// if exists
DATALEN bits
-----------bit7 = 1 MASTER SENDS
0 SLAVE SENDS
bit6 = 1 ADDRESS WAS XORed
0 ADDRESS UNCHANGED
bit5 = 0 FIXED
bit4 = 1 DATA3 (if exists)
0 DATA3 (if exists)
bit3 = 1 DATA2 (if exists)
0 DATA2 (if exists)
bit2 = 1 DATA1 (if exists)
0 DATA1 (if exists)
bit1bit0 = 0 to 3 NUMBER OF
CRC generation :
---------------crc_send = datalen ^ address;
crc_send ^= data[0];
// if exists
crc_send ^= data[1];
// if exists
crc_send ^= data[2];
// if exists
crc_send = ~crc_send;
if ((crc_send == START_BYTE) || (crc_send == STOP_BYTE))
crc_send++;
NOTE: DATALEN<4..0> can not take the START_BYTE<4..0> or STOP_BYTE<4..0> values.
473
MikroElektronika
Software IC Library
The mikroC PRO for dsPIC30/33 and PIC24 provides routines for implementing Software IC communication. These
routines are hardware independent and can be used with any MCU. The Software IC library enables you to use MCU
as Master in IC communication. Multi-master mode is not supported.
Important :
- This library implements time-based activities, so interrupts need to be disabled when using Software IC.
- All IC Library functions are blocking-call functions (they are waiting for IC clock line to become logical one).
- The pins used for the Software IC communication should be connected to the pull-up resistors. Turning off the LEDs
connected to these pins may also be required.
- Every Software IC library routine has its own counterpart in Hardware IC library, except I2C_Repeated_Start.
Soft_I2C_Start is used instead of I2C_Repeated_Start.
- Working clock frequency of the Software IC is 20kHz.
Example :
extern sbit
Direction;
at
extern sbit
Direction;
at
Library Routines
- Soft_I2C_Init
- Soft_I2C_Start
- Soft_I2C_Read
- Soft_I2C_Write
- Soft_I2C_Stop
- Soft_I2C_Break
MikroElektronika
474
void Soft_I2C_Init();
Nothing.
Requires
Global variables :
- Soft_I2C_Scl: Soft IC clock line
- Soft_I2C_Sda: Soft IC data line
- Soft_I2C_Scl_Pin_Direction: Direction of the Soft IC clock pin
- Soft_I2C_Sda_Pin_Direction: Direction of the Soft IC data pin
must be defined before using this function.
Example
Notes
None
Soft_I2C_Start
Prototype
void Soft_I2C_Start();
Nothing.
Requires
Software IC must be configured before using this function. See Soft_I2C_Init routine.
Example
Notes
None
475
MikroElektronika
Requires
Soft IC must be configured before using this function. See Soft_I2C_Init routine.
Also, START signal needs to be issued in order to use this function. See Soft_I2C_Start routine.
Example
Notes
None
Soft_I2C_Write
Prototype
Requires
Soft IC must be configured before using this function. See Soft_I2C_Init routine.
Also, START signal needs to be issued in order to use this function. See Soft_I2C_Start routine.
Example
Notes
None
MikroElektronika
476
void Soft_I2C_Stop();
Nothing.
Requires
Soft IC must be configured before using this function. See Soft_I2C_Init routine.
Example
Notes
None
477
MikroElektronika
void Soft_I2C_Break();
Description All Software IC 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
// reset counter
else
counter++;
// increment counter
T1IF_bit = 0;
void main() {
...
// try Soft_I2C_Init with blocking prevention mechanism
IPC0
= IPC0 | 0x1000;
// Interrupt priority level = 1
T1IE_bit= 1;
// Enable Timer1 interrupts
T1CON = 0x8030;
// Timer1 ON, internal clock FCY, prescaler
1:256
}
Notes
Soft_I2C_Init();
T1IE_bit= 0;
Interrupts should be disabled before using Software IC routines again (see note at the top of this
page).
MikroElektronika
478
479
MikroElektronika
//
//
//
//
//
//
Transform
Transform
Transform
Transform
Transform
Transform
seconds
months
hours
year
day
month
Lcd_Chr(2, 6,
Lcd_Chr(2, 7,
Lcd_Chr(2, 9,
Lcd_Chr(2,10,
Lcd_Chr(2,12,
Lcd_Chr(2,13,
(hours /
(hours %
(minutes
(minutes
(seconds
(seconds
Lcd_Chr(1, 6,
Lcd_Chr(1, 7,
Lcd_Chr(1, 9,
Lcd_Chr(1,10,
Lcd_Chr(1,15,
10)
10)
/ 10)
% 10)
+
+
+
+
+
10)
10)
/ 10)
% 10)
/ 10)
% 10)
48);
48);
48);
48);
56);
+
+
+
+
+
+
48);
48);
48);
48);
48);
48);
Soft_I2C_Init();
Lcd_Init();
Lcd_Cmd(_LCD_CLEAR);
Lcd_Cmd(_LCD_CURSOR_OFF);
//
//
//
//
Lcd_Out(1,1,"Date:");
Lcd_Chr(1,8,':');
Lcd_Chr(1,11,':');
Lcd_Out(2,1,"Time:");
Lcd_Chr(2,8,':');
Lcd_Chr(2,11,':');
Lcd_Out(1,12,"200");
Init_Main();
// Perform initialization
while (1) {
Read_Time();
Transform_Time();
Display_Time();
//
//
//
//
Delay_ms(1000);
MikroElektronika
Endless loop
Read time from RTC(PCF8583)
Format date and time
Prepare and display on LCD
// Wait 1 second
480
Example :
sbit SoftSpi_SDI_Direction
TRISF4_bit;
at
sbit SoftSpi_SDO_Direction
TRISF3_bit;
at
sbit SoftSpi_CLK_Direction
TRISF6_bit;
at
Library Routines
- Soft_SPI_Init
- Soft_SPI_Read
- Soft_SPI_Write
481
MikroElektronika
void Soft_SPI_Init();
Nothing.
Requires
Global variables:
- SoftSpi_SDI: Data in line
- SoftSpi_SDO: Data out line
- SoftSpi_CLK: Data clock line
- SoftSpi_SDI_Direction: Direction of the Data in pin
- SoftSpi_SDO_Direction: Direction of the Data out pin
- SoftSpi_CLK_Direction: Direction of the Data clock pin
must be defined before using this function.
Example
Notes
None
MikroElektronika
482
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
Requires
Soft SPI must be initialized before using this function. See Soft_SPI_Init routine.
Example
Notes
None
Soft_SPI_Write
Prototype
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
Notes
None
Library Example
This code demonstrates using library routines for Soft_SPI communication. Also, this example demonstrates working
with max7219. Eight 7 segment displays are connected to MAX7219. MAX7219 is connected to SDO, SDI, SCK pins
are connected accordingly.
Copy Code To Clipboard
// DAC module connections
sbit Chip_Select at LATF0_bit;
sbit SoftSpi_CLK at LATF6_bit;
sbit SoftSpi_SDI at RF4_bit;
sbit SoftSpi_SDO at LATF3_bit;
sbit Chip_Select_Direction at
sbit SoftSpi_CLK_Direction at
sbit SoftSpi_SDI_Direction at
sbit SoftSpi_SDO_Direction at
// End DAC module connections
483
TRISF0_bit;
TRISF6_bit;
TRISF4_bit;
TRISF3_bit;
MikroElektronika
//
//
//
//
//
Chip_Select = 1;
}
void main() {
ADPCFG = 0xFFFF;
InitMain();
value = 2048;
while (1) {
// Endless loop
DAC_Output(value);
Delay_ms(1);
}
}
MikroElektronika
484
Library Routines
- Soft_UART_Init
- Soft_UART_Read
- Soft_UART_Write
- Soft_UART_Break
Soft_UART_Init
Prototype
char Soft_UART_Init(unsigned int *port, unsigned int rx, unsigned int tx,
unsigned long baud_rate, unsigned int inverted);
Requires
Nothing.
Example
This will initialize software UART and establish the communication at 9600 bps:
char error;
...
error = Soft_UART_Init(&PORTF, 4, 5, 14400, 0);
at 14400 bps
Notes
485
The Software UART library implements time-based activities, so interrupts need to be disabled when
using it.
MikroElektronika
Requires
Software UART must be initialized before using this function. See the Soft_UART_Init routine.
Example
char data_;
char error;
...
// wait until data is received
do
data = Soft_UART_Read(&error);
while (error);
// Now we can work with data:
if (data_) {...}
Notes
The Software UART library implements time-based activities, so interrupts need to be disabled when
using it.
Soft_UART_Write
Prototype
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
Notes
The Software UART library implements time-based activities, so interrupts need to be disabled when
using it.
MikroElektronika
486
void 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
// reset counter
else
counter++;
// increment counter
T1IF_bit = 0;
void main() {
...
if (Soft_UART_Init(&PORTF, 4, 5, 14400, 0) = 0)
Soft_UART_Write(0x55);
...
// try Soft_UART_Read with blocking prevention mechanism
IPC0
= IPC0 | 0x1000;
// Interrupt priority level = 1
T1IE_bit= 1;
// Enable Timer1 interrupts
T1CON = 0x8030;
// Timer1 ON, internal clock FCY, prescaler 1:256
}
Notes
487
data1 = Soft_UART_Read(&error);
T1IE_bit= 0;
// Disable Timer1 interrupts
The Software UART library implements time-based activities, so interrupts need to be disabled when
using it.
MikroElektronika
// Auxiliary variables
void main(){
ADPCFG = 0xFFFF;
TRISB = 0;
LATB = 0;
MikroElektronika
// Endless loop
// Read byte, then test error flag
// If error was detected
//
signal it on PORTB
// If error was not detected, return
488
Sound Library
The mikroC PRO for dsPIC30/33 and PIC24 provides a Sound Library to supply users with routines necessary for sound
signalization in their applications. Sound generation needs additional hardware, such as piezo-speaker (example of
piezo-speaker interface is given on the schematic at the bottom of this page).
Library Routines
- Sound_Init
- Sound_Play
Sound_Init
Prototype
Nothing.
Requires
Nothing.
Example
Notes
None.
Sound_Play
Prototype
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
Notes
None.
489
MikroElektronika
void Tone2() {
Sound_Play(698, 250);
}
void Tone3() {
Sound_Play(784, 250);
}
void Melody() {
Tone1(); Tone2();
Tone1(); Tone2();
Tone1(); Tone2();
Tone1(); Tone2();
Tone1(); Tone2();
Tone3(); Tone3();
}
//
Tone3();
Tone3();
Tone3();
Tone3();
Tone3();
Tone2();
void ToneA() {
Sound_Play( 880, 50);
}
void ToneC() {
Sound_Play(1046, 50);
}
void ToneE() {
Sound_Play(1318, 50);
}
void Melody2() {
unsigned short i;
for (i = 9; i > 0; i--) {
ToneA(); ToneC(); ToneE();
}
}
void main() {
ADPCFG = 0xFFFF;
TRISB = 0xF8;
LATB = 0;
Sound_Init(&PORTD, 3);
Sound_Play(880, 1000);
MikroElektronika
490
if (Button(&PORTB,6,1,1))
Tone2();
while (RB6_bit);
if (Button(&PORTB,5,1,1))
Tone3();
while (RB5_bit);
if (Button(&PORTB,4,1,1))
Melody2();
while (RB4_bit);
if (Button(&PORTB,3,1,1))
Melody();
while (RB3_bit);
}
}
HW Connection
491
MikroElektronika
SPI Library
The SPI module is available with all dsPIC30/33 and PIC24 MCUs. mikroC PRO for dsPIC30/33 and PIC24 provides a
library for initializing the Slave mode and initializing and comfortable work with the Master mode. The dsPIC30/33 and
PIC24 can easily communicate with other devices via SPI: A/D converters, D/A converters, MAX7219, LTC1290, etc.
Important :
SPI library routines require you to specify the module you want to use. To select the desired SPI module, simply change
the letter x in the routine prototype for a number from 1 to 3.
Number of SPI modules per MCU differs from chip to chip. Please, read the appropriate datasheet before utilizing this
library.
Switching between the SPI modules in the SPI library is done by the SPI_Set_Active function (both SPI modules have
to be previously initialized).
Library Routines
- SPIx_Init
- SPIx_Init_Advanced
- SPIx_Read
- SPIx_Write
- SPI_Set_Active
MikroElektronika
492
void SPIx_Init();
Description Configures and initializes the SPI module with default settings.
Default settings:
- Master mode
- 8-bit data mode
- secondary prescaler 1:1
- primary prescaler 64:1
- Slave Select disabled
- input data sampled in the middle of interval
- clock idle state low
- Serial output data changes on transition from active clock state to idle clock state
Parameters None.
Returns
Nothing.
Requires
Example
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).
493
MikroElektronika
Description Configures and initializes the SPI module with user defined settings.
Parameters Parameters master_mode, mode16, sec_prescaler, pri_prescaler, slave_select, data_
sample, clock_idle and determine the working mode for SPI.
The master_mode parameter determines the working mode for SPI module.
Master/Slave mode
Description
Master mode
_SPI_MASTER
Slave mode
_SPI_SLAVE
The parameter mode16 determines the data length mode, which can be 8-bits (per transmitions cycle)
or 16-bits.
Data Length Mode
Description
16-bit mode
_SPI_16_BIT
8-bit mode
_SPI_8_BIT
The parameter sec_prescaler determines the value of the secondary SPI clock prescaler. Used
only in the Master Mode.
Secondary SPI Clock Prescaler Value
Description
_SPI_PRESCALE_SEC_1
_SPI_PRESCALE_SEC_2
_SPI_PRESCALE_SEC_3
_SPI_PRESCALE_SEC_4
_SPI_PRESCALE_SEC_5
_SPI_PRESCALE_SEC_6
_SPI_PRESCALE_SEC_7
_SPI_PRESCALE_SEC_8
The parameter pri_prescaler determines the value of the primary SPI clock prescaler. Used only
in the Master Mode.
Primary SPI Clock Prescaler Value
Description
_SPI_PRESCALE_PRI_1
_SPI_PRESCALE_PRI_4
_SPI_PRESCALE_PRI_16
_SPI_PRESCALE_PRI_64
MikroElektronika
494
The parameter slave_select determines whether the Slave Select (SS) pin is used in communication.
Valid in the Slave Mode only.
Slave Select Enable/Disable
Description
_SPI_SS_ENABLE
_SPI_SS_DISABLE
The parameter data_sample determines the sample moment (phase) of input data.
Data Sampling Moment
Description
_SPI_DATA_SAMPLE_MIDDLE
_SPI_DATA_SAMPLE_END
The parameter clock_idle determines the behaviour of the SPI clock (CLK) line in IDLE phase.
Clock Polarity
Description
_SPI_CLK_IDLE_LOW
_SPI_CLK_IDLE_HIGH
The parameter edge determines on which clock edge data is considered to be valid.
Clock Edge
Description
_SPI_ACTIVE_2_IDLE
_SPI_IDLE_2_ACTIVE
Returns
Nothing.
Requires
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, _SPI_PRESCALE_SEC_1, _SPI_
PRESCALE_PRI_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.
495
MikroElektronika
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
Example
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
Description Writes one word or byte (depending on mode set by init routines) via the SPI bus.
Parameters - data_out: data to be sent
Returns
Received data.
Requires
Example
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
496
void
SPI_Set_Active(unsigned
(unsigned));
(*read_ptr)(unsigned),
void(*write_ptr)
Description Sets the active SPI module which will be used by the SPIx_Read and SPIx_Write routines.
Parameters Parameters :
- read_ptr: SPI1_Read handler
- write_ptr: SPI1_Write handler
Returns
Nothing.
Requires
Example
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.
Copy Code To Clipboard
// DAC module connections
sbit Chip_Select at LATF0_bit;
sbit Chip_Select_Direction at TRISF0_bit;
// End DAC module connections
unsigned int value;
void InitMain() {
TRISB0_bit = 1;
TRISB1_bit = 1;
Chip_Select = 1;
Chip_Select_Direction = 0;
SPI1_Init();
}
//
//
//
//
//
input
input
Output
module
497
MikroElektronika
Chip_Select = 1;
}
void main() {
ADPCFG = 0xFFFF;
InitMain();
value = 2048;
while (1) {
// Endless loop
}
}
HW Connection
SPI HW connection
MikroElektronika
498
499
MikroElektronika
Example :
Examples :
MikroElektronika
500
SPIx_Write
Prototype
Description This is MAC module routine. It initializes ENC28J60 controller. This function is internaly splited into 2
parts to help linker when coming short of memory.
ENC28J60 controller settings (parameters not mentioned here are set to default):
- receive buffer start address : 0x0000.
- receive buffer end address : 0x19AD.
- transmit buffer start address: 0x19AE.
- transmit buffer end address : 0x1FFF.
- RAM buffer read/write pointers in auto-increment mode.
- receive filters set to default: CRC + MAC Unicast + MAC Broadcast in OR mode.
- flow control with TX and RX pause frames in full duplex mode.
- frames are padded to 60 bytes + CRC.
- maximum packet size is set to 1518.
- Back-to-Back Inter-Packet Gap: 0x15 in full duplex mode; 0x12 in half duplex mode.
- Non-Back-to-Back Inter-Packet Gap: 0x0012 in full duplex mode; 0x0C12 in half duplex mode.
- Collision window is set to 63 in half duplex mode to accomodate some ENC28J60 revisions silicon bugs.
- CLKOUT output is disabled to reduce EMI generation.
- half duplex loopback disabled.
- LED configuration: default (LEDA-link status, LEDB-link activity).
501
MikroElektronika
Received data.
Requires
Global variables :
- SPI_Ethernet_CS: Chip Select line
- SPI_Ethernet_CS_Direction: Direction of the Chip Select pin
- SPI_Ethernet_RST: Reset line
- SPI_Ethernet_RST_Direction: Direction of the Reset pin
must be defined before using this function.
The SPI module needs to be initialized. See the SPIx_Init and SPIx_Init_Advanced routines.
Example
#define SPI_Ethernet_HALFDUPLEX
#define SPI_Ethernet_FULLDUPLEX
0
1
None.
MikroElektronika
502
Description This is MAC module routine. This routine enables appropriate network traffic on the ENC28J60 module
by the means of its receive filters (unicast, multicast, broadcast, crc). Specific type of network traffic
will be enabled if a corresponding bit of this routines 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:
Bit
Mask
Description
0x01
_SPI_Ethernet_
BROADCAST
0x02
_SPI_Ethernet_
MULTICAST
0x04
not used
none
0x08
not used
none
0x10
not used
none
0x20
_SPI_Ethernet_CRC
0x40
not used
none
0x80
_SPI_Ethernet_UNICAST
Returns
Nothing.
Requires
Example
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.
503
MikroElektronika
Description This is MAC module routine. This routine disables appropriate network traffic on the ENC28J60 module
by the means of its receive filters (unicast, multicast, broadcast, crc). Specific type of network traffic
will be disabled if a corresponding bit of this routines 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:
Bit
Mask
Description
0x01
_SPI_Ethernet_
BROADCAST
0x02
_SPI_Ethernet_
MULTICAST
0x04
not used
none
0x08
not used
none
0x10
not used
none
0x20
_SPI_Ethernet_CRC
0x40
not used
none
0x80
_SPI_Ethernet_
UNICAST
7
Returns
Nothing.
Requires
Example
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
504
Description This is MAC module routine. It processes next received packet if such exists. Packets are processed
in the following manner:
- ARP & ICMP requests are replied automatically.
- upon TCP request the SPI_Ethernet_UserTCP function is called for further processing.
- upon UDP request the SPI_Ethernet_UserUDP function is called for further processing.
Parameters None.
Returns
- 0 - upon successful packet processing (zero packets received or received packet processed
successfully).
- 1 - upon reception error or receive buffer corruption. ENC28J60 controller needs to be restarted.
- 2 - received packet was not sent to us (not our IP, nor IP broadcast address).
- 3 - received IP packet was not IPv4.
- 4 - received packet was of type unknown to the library.
Requires
Example
if (SPI_Ethernet_doPacket() == 0)(1) {
...
}
Notes
SPI_Ethernet_putByte
Prototype
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
Example
char data_;
...
SPI_Ethernet_putByte(data); // put an byte into ENC28J60 buffer
Notes
None.
505
MikroElektronika
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
Example
Notes
put
an
RAM
array
into
ENC28J60
None.
SPI_Ethernet_putConstBytes
Prototype
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
Example
Notes
None.
SPI_Ethernet_putString
Prototype
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
Requires
Example
Notes
None.
MikroElektronika
506
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
Requires
Example
Notes
None.
SPI_Ethernet_getByte
Prototype
Description This is MAC module routine. It fetches a byte from address pointed to by current ENC28J60 read
pointer (ERDPT).
Parameters None.
Returns
Requires
Example
char buffer;
...
buffer = SPI_Ethernet_getByte(); // read a byte from ENC28J60 buffer
Notes
None.
SPI_Ethernet_getBytes
Prototype
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
Example
char buffer[16];
...
SPI_Ethernet_getBytes(buffer, 0x100, 16); // read 16 bytes, starting from
address 0x100
Notes
None.
507
MikroElektronika
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: clients IP address.
- remotePort: clients TCP port.
- localPort: port to which the request is sent.
- reqLength: TCP request data field length.
- flags: structure consisted of two bit fields :
Copy Code To Clipboard
typedef struct {
unsigned canCloseTCP: 1; // flag which closes socket
unsigned isBroadcast: 1; // flag which denotes that the IP package has
been received via subnet broadcast address
} TEthPktFlags;
Returns
Requires
Example
This function is internally called by the library and should not be called by the users 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
508
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 dont need to reply to the UDP requests, just define this function with
a return(0) as single statement.
Parameters - remoteHost: clients IP address.
- remotePort: clients port.
- localPort: port to which the request is sent.
- reqLength: UDP request data field length.
- flags: structure consisted of two bit fields :
Copy Code To Clipboard
typedef struct {
unsigned canCloseTCP: 1; // flag which closes TCP socket (not relevant
to UDP)
unsigned isBroadcast: 1; // flag which denotes that the IP package has
been received via subnet broadcast address
} TEthPktFlags;
Returns
Requires
Example
This function is internally called by the library and should not be called by the users code.
Notes
The function source code is provided with appropriate example projects. The code should be adjusted
by the user to achieve desired reply.
509
MikroElektronika
Description This routine should be used when DHCP server is present on the network to fetch assigned IP
address.
Parameters None.
Returns
Requires
Example
Notes
User should always copy the IP address from the RAM location returned by this routine into its own IP
address buffer. These locations should not be altered by the user in any case!
SPI_Ethernet_getDnsIpAddress
Prototype
Description This routine should be used when DHCP server is present on the network to fetch assigned DNS IP
address.
Parameters None.
Returns
Requires
Example
Notes
User should always copy the IP address from the RAM location returned by this routine into its own
DNS IP address buffer. These locations should not be altered by the user in any case!
SPI_Ethernet_getIpMask
Prototype
Description This routine should be used when DHCP server is present on the network to fetch assigned IP subnet
mask.
Parameters None.
Returns
Requires
Example
Notes
User should always copy the IP address from the RAM location returned by this routine into its own IP
subnet mask buffer. These locations should not be altered by the user in any case!
MikroElektronika
510
void
SPI_Ethernet_confNetwork(char
*dnsIpAddr);
*ipMask,
char
*gwIpAddr,
char
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
Example
char ipMask[4]
= {255, 255, 255, 0 }; // network mask (for example :
255.255.255.0)
char gwIpAddr[4] = {192, 168,
1, 1 }; // gateway (router) IP address
char dnsIpAddr[4] = {192, 168,
1, 1 }; // DNS server IP address
...
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.
SPI_Ethernet_arpResolve
Prototype
Description This is ARP module routine. It sends an ARP request for given IP address and waits for ARP reply. If
the requested IP address was resolved, an ARP cash entry is used for storing the configuration. ARP
cash can store up to 3 entries. For ARP cash structure refer to eth_enc28j60LibDef.h header
file in the compilers 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
Example
Notes
The Ethernet services are not stopped while this routine waits for ARP reply. The incoming packets will
be processed normaly during this time.
511
MikroElektronika
unsigned
unsigned
int
int
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
Requires
Example
Notes
None.
SPI_Ethernet_dnsResolve
Prototype
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, its 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
Example
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 its own
resolved host IP address buffer. These locations should not be altered by the user in any case!
MikroElektronika
512
Description This is DHCP module routine. It sends an DHCP request for network parameters (IP, gateway, DNS
addresses and IP subnet mask) and waits for DHCP reply. If the requested parameters were obtained
successfully, their values are stored into the library global variables.
These parameters can be fetched by using appropriate library IP get routines:
- SPI_Ethernet_getIpAddress - fetch IP address.
- SPI_Ethernet_getGwIpAddress - fetch gateway IP address.
- SPI_Ethernet_getDnsIpAddress - fetch DNS IP address.
- SPI_Ethernet_getIpMask - fetch IP subnet mask.
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
Requires
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 its code.
513
MikroElektronika
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, its time to contact DHCP server and renew the lease.
Parameters None.
Returns
Requires
Example
while(1) {
...
if (SPI_Ethernet_doDHCPLeaseTime())
... // its time to renew the IP address lease
}
Notes
None.
SPI_Ethernet_renewDHCP
Prototype
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
Requires
Example
while(1) {
...
if (SPI_Ethernet_doDHCPLeaseTime())
SPI_Ethernet_renewDHCP(5);
// its time to renew the IP address lease,
with 5 secs for a reply
...
}
Notes
None.
MikroElektronika
514
0x00
0x01
// half duplex
// full duplex
515
HTTP
MIME
MIME
with
page
MikroElektronika
MikroElektronika
getRequest[15];
dyna[31] ;
httpCounter = 0;
516
517
MikroElektronika
SPI_Ethernet_putString
/*
* 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
*
*/
unsigned int
SPI_Ethernet_UserTCP(unsigned char *remoteHost, unsigned int remotePort,
unsigned int localPort, unsigned int reqLength, TEthPktFlags *flags)
{
unsigned int
len;
// my reply length
// should we close tcp socket after response is sent?
// library closes tcp socket by default if canCloseTCP flag is not reset here
// flags->canCloseTCP = 0; // 0 - do not close socket
// otherwise - close socket
if(localPort != 80)
{
return(0);
}
// get 10 first bytes only of the request, the rest does not matter here
for(len = 0; len < 10; len++)
{
getRequest[len] = SPI_Ethernet_getByte();
}
getRequest[len] = 0;
len = 0;
if(memcmp(getRequest, httpMethod, 5))
{
return(0);
}
httpCounter++;
if(getRequest[5] == s)
// if request path name starts with s, store
dynamic data in transmit buffer
{
// the text string replied by this request can be interpreted as javascript
statements
// by browsers
len = putConstString(httpHeader); // HTTP header
len += putConstString(httpMimeTypeScript);
// with text MIME type
MikroElektronika
518
if(isdigit(getRequest[6]))
// if 0 <= bit number <=
9, bits 8 & 9 does not exist but does not matter
{
bitMask = getRequest[6] - '0';
// convert ASCII to integer
bitMask = 1 << bitMask;
// create bit mask
PORTD ^= bitMask;
// toggle PORTD with xor operator
}
}
if(len == 0)
{
len =
len +=
len +=
len +=
}
// what do to by default
putConstString(httpHeader);
putConstString(httpMimeTypeHTML);
putConstString(indexPage);
putConstString(indexPage2);
return(len);
with the number of bytes to transmit
}
519
//
//
//
//
HTTP
with
HTML
HTML
header
HTML MIME type
page first part
page second part
MikroElektronika
// add separator
MikroElektronika
520
//
PORTB = 0;
TRISB = 0xFFFF;
PORTD = 0;
TRISD = 0;
ADC1_Init();
// Enable ADC module
/*
* starts ENC28J60 with :
* reset bit on RC0
* CS bit on RC1
* my MAC & IP address
* full duplex
*/
SPI1_Init();
// init SPI communication with ethernet board
SPI1_Init_Advanced(_SPI_MASTER, _SPI_8_BIT, _SPI_PRESCALE_SEC_1, _SPI_PRESCALE_
PRI_4,
_SPI_SS_DISABLE, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_LOW,
_SPI_IDLE_2_ACTIVE);
SPI_Ethernet_Init(myMacAddr, myIpAddr, 1); // init ethernet board
// dhcp will not be used here, so use preconfigured addresses
SPI_Ethernet_confNetwork(ipMask, gwIpAddr, dnsIpAddr);
while(1)
// do forever
{
/*
* if necessary, test the return value to get error code
*/
SPI_Ethernet_doPacket();
// process incoming Ethernet packets
/*
* add your stuff here if needed
* Spi_Ethernet_doPacket() must be called as often as possible
* otherwise packets could be lost
*/
}
}
521
MikroElektronika
MikroElektronika
522
523
MikroElektronika
Example :
extern
sfr
sbit
Ethernet_24j600_CS;
sbit SPI_Ethernet_24j600_CS
LATF1_bit;
SPI_
at
extern
sfr
sbit
SPI_
SPI_Ethernet_24j600_CS_
Direction of the ENC24J600 sbit
Ethernet_24j600_CS_
Direction at TRISF1_bit;
chip select pin.
Direction;
The following routines must be
defined in all project using SPI Description :
Ethernet ENC24J600 Library:
Example :
unsigned
int
SPI_
E t h e r n e t _ 2 4 j 6 0 0 _
UserTCP(unsigned
char
*remoteHost, unsigned int
TCP request handler.
remotePort,
unsigned
int
localPort,
unsigned
int
reqLength, TEthj600PktFlags
*flags);
unsigned
int
SPI_
E t h e r n e t _ 2 4 j 6 0 0 _
UserUDP(unsigned
char
*remoteHost, unsigned int
UDP request handler.
remotePort,
unsigned
int
localPort,
unsigned
int
reqLength, TEthj600PktFlags
*flags);
MikroElektronika
524
525
MikroElektronika
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):
- receive buffer start address : 0x0000.
- receive buffer end address : 0x19AD.
- transmit buffer start address: 0x19AE.
- transmit buffer end address : 0x1FFF.
- RAM buffer read/write pointers in auto-increment mode.
- receive filters set to default: CRC + MAC Unicast + MAC Broadcast in OR mode.
- flow control with TX and RX pause frames in full duplex mode.
- frames are padded to 60 bytes + CRC.
- maximum packet size is set to 1518.
- Back-to-Back Inter-Packet Gap: 0x15 in full duplex mode; 0x12 in half duplex mode.
- Non-Back-to-Back Inter-Packet Gap: 0x0012 in full duplex mode; 0x0C12 in half duplex mode.
- Collision window is set to 63 in half duplex mode to accomodate some ENC24J600 revisions silicon bugs.
- CLKOUT output is disabled to reduce EMI generation.
- half duplex loopback disabled.
- LED configuration: default (LEDA-link status, LEDB-link activity).
Parameters - mac: RAM buffer containing valid MAC address.
- ip: RAM buffer containing valid IP address.
- configuration: ethernet negotiation, duplex and speed mode settings. For this purpose, predefined
library constants (see the list below) can be combined using logical AND to form appropriate value :
Description :
Set Auto-negotiation
SPI_Ethernet_24j600_AUTO_NEGOTIATION
SPI_Ethernet_24j600_MANUAL_NEGOTIATION
SPI_Ethernet_24j600_HALFDUPLEX
SPI_Ethernet_24j600_FULLDUPLEX
SPI_Ethernet_24j600_SPD10
Set
transmission
100Mbps
SPI_Ethernet_24j600_SPD100
speed
of
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
526
Nothing.
Requires
Global variables :
- SPI_Ethernet_24j600_CS: Chip Select line
- SPI_Ethernet_24j600_CS_Direction: Direction of the Chip Select pin
must be defined before using this function.
The SPI module needs to be initialized. See the SPIx_Init and SPIx_Init_Advanced routines.
Example
#include
__EthEnc24J600.h
527
None.
MikroElektronika
Description This is MAC module routine. This routine enables appropriate network traffic on the ENC24J600
module by the means of its receive filters (unicast, multicast, broadcast, crc). Specific type of network
traffic will be enabled if a corresponding bit of this routines 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:
Bit
Mask
Description
0x01
_SPI_Ethernet_24j600_
BROADCAST
0x02
_SPI_Ethernet_24j600_
MULTICAST
0x04
not used
none
0x08
not used
none
0x10
not used
none
0x20
_SPI_Ethernet_24j600_
CRC
0x40
not used
none
0x80
_SPI_Ethernet_24j600_
UNICAST
7
Returns
Nothing.
Requires
Example
SPI_Ethernet_24j600_Enable(_SPI_Ethernet_24j600_CRC | _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
528
Description This is MAC module routine. This routine disables appropriate network traffic on the ENC24J600
module by the means of its receive filters (unicast, multicast, broadcast, crc). Specific type of network
traffic will be disabled if a corresponding bit of this routines 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:
Bit
Mask
Description
0x01
_SPI_Ethernet_24j600_
BROADCAST
0x02
_SPI_Ethernet_24j600_
MULTICAST
0x04
not used
none
0x08
not used
none
0x10
not used
none
0x20
_SPI_Ethernet_24j600_
CRC
0x40
not used
none
0x80
_SPI_Ethernet_24j600_
UNICAST
Returns
Nothing.
Requires
Example
SPI_Ethernet_24j600_Disable(_SPI_Ethernet_24j600_CRC | _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.
529
MikroElektronika
Description This is MAC module routine. It processes next received packet if such exists. Packets are processed
in the following manner:
- ARP & ICMP requests are replied automatically.
- upon TCP request the SPI_Ethernet_24j600_UserTCP function is called for further processing.
- upon UDP request the SPI_Ethernet_24j600_UserUDP function is called for further processing.
Parameters None.
Returns
- 0 - upon successful packet processing (zero packets received or received packet processed
successfully).
- 1 - upon reception error or receive buffer corruption. ENC24J600 controller needs to be restarted.
- 2 - received packet was not sent to us (not our IP, nor IP broadcast address).
- 3 - received IP packet was not IPv4.
- 4 - received packet was of type unknown to the library.
Requires
Example
if (SPI_Ethernet_24j600_doPacket() == 0)(1) {
...
}
Notes
SPI_Ethernet_24j600_putByte
Prototype
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
Example
char data_;
...
SPI_Ethernet_24j600_putByte(data); // put an byte into ENC24J600 buffer
Notes
None.
MikroElektronika
530
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
Example
Notes
None.
SPI_Ethernet_24j600_putConstBytes
Prototype
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
Example
Notes
None.
531
MikroElektronika
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
Requires
Example
Notes
None.
SPI_Ethernet_24j600_putConstString
Prototype
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
Requires
Example
Notes
//
put
const
string
into
None.
SPI_Ethernet_24j600_getByte
Prototype
Description This is MAC module routine. It fetches a byte from address pointed to by current ENC24J600 read
pointer (ERDPT).
Parameters None.
Returns
Requires
Example
char buffer;
...
buffer = SPI_Ethernet_24j600_getByte(); // read a byte from ENC24J600
buffer
Notes
None.
MikroElektronika
532
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
Example
char buffer[16];
...
SPI_Ethernet_24j600_getBytes(buffer, 0x100, 16); // read 16 bytes, starting
from address 0x100
Notes
None.
SPI_Ethernet_24j600_UserTCP
Prototype
unsigned
int
SPI_Ethernet_24j600_UserTCP(unsigned
char
*remoteHost,
unsigned int remotePort, unsigned int localPort, unsigned int reqLength,
TEthj600PktFlags *flags);
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: clients IP address.
- remotePort: clients TCP port.
- localPort: port to which the request is sent.
- reqLength: TCP request data field length.
- flags: structure consisted of two bit fields :
Copy Code To Clipboard
typedef struct {
unsigned canCloseTCP: 1; // flag which closes socket
unsigned isBroadcast: 1; // flag which denotes that the IP package has
been received via subnet broadcast address
} TEthj600PktFlags;
Returns
Requires
Example
This function is internally called by the library and should not be called by the users code.
Notes
The function source code is provided with appropriate example projects. The code should be adjusted
by the user to achieve desired reply.
533
MikroElektronika
unsigned
int
SPI_Ethernet_24j600_UserUDP(unsigned
char
*remoteHost,
unsigned int remotePort, unsigned int destPort, unsigned int reqLength,
TEthj600PktFlags *flags);
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 dont need to reply to the UDP requests, just define this
function with a return(0) as single statement.
Parameters - remoteHost: clients IP address.
- remotePort: clients port.
- localPort: port to which the request is sent.
- reqLength: UDP request data field length.
- flags: structure consisted of two bit fields :
Copy Code To Clipboard
typedef struct {
unsigned canCloseTCP: 1; // flag which closes TCP socket (not relevant
to UDP)
unsigned isBroadcast: 1; // flag which denotes that the IP package has
been received via subnet broadcast address
} TEthj600PktFlags;
Returns
Requires
Example
This function is internally called by the library and should not be called by the users code.
Notes
The function source code is provided with appropriate example projects. The code should be adjusted
by the user to achieve desired reply.
SPI_Ethernet_24j600_getIpAddress
Prototype
Description This routine should be used when DHCP server is present on the network to fetch assigned IP
address.
Parameters None.
Returns
Requires
Example
Notes
User should always copy the IP address from the RAM location returned by this routine into its own IP
address buffer. These locations should not be altered by the user in any case!
MikroElektronika
534
Description This routine should be used when DHCP server is present on the network to fetch assigned gateway
IP address.
Parameters None.
Returns
Requires
Example
Notes
User should always copy the IP address from the RAM location returned by this routine into its own
gateway IP address buffer. These locations should not be altered by the user in any case!
SPI_Ethernet_24j600_getDnsIpAddress
Prototype
Description This routine should be used when DHCP server is present on the network to fetch assigned DNS IP
address.
Parameters None.
Returns
Requires
Example
Notes
User should always copy the IP address from the RAM location returned by this routine into its own
DNS IP address buffer. These locations should not be altered by the user in any case!
535
MikroElektronika
Description This routine should be used when DHCP server is present on the network to fetch assigned DNS IP
address.
Parameters None.
Returns
Requires
Example
Notes
User should always copy the IP address from the RAM location returned by this routine into its own
DNS IP address buffer. These locations should not be altered by the user in any case!
SPI_Ethernet_24j600_confNetwork
Prototype
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
Example
char ipMask[4]
= {255, 255, 255, 0 }; // network mask (for example :
255.255.255.0)
char gwIpAddr[4] = {192, 168,
1, 1 }; // gateway (router) IP address
char dnsIpAddr[4] = {192, 168,
1, 1 }; // DNS server IP address
...
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
536
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 __EthEnc24j600.h header file in
the compilers 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
Example
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
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
Requires
Example
Notes
None.
537
MikroElektronika
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, its 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
Example
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 its own
resolved host IP address buffer. These locations should not be altered by the user in any case!
MikroElektronika
538
Description This is DHCP module routine. It sends an DHCP request for network parameters (IP, gateway, DNS
addresses and IP subnet mask) and waits for DHCP reply. If the requested parameters were obtained
successfully, their values are stored into the library global variables.
These parameters can be fetched by using appropriate library IP get routines:
- SPI_Ethernet_24j600_getIpAddress - fetch IP address.
- SPI_Ethernet_24j600_getGwIpAddress - fetch gateway IP address.
- SPI_Ethernet_24j600_getDnsIpAddress - fetch DNS IP address.
- SPI_Ethernet_24j600_getIpMask - fetch IP subnet mask.
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
Requires
Example
...
SPI_Ethernet_24j600_initDHCP(5); //
server, wait 5 sec for the response
...
Notes
get
network
configuration
from
DHCP
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_24j600_userTimerSec is
used to keep track of time. It is user responsibility to increment this variable each second in its code.
539
MikroElektronika
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, its time to contact DHCP server and renew the lease.
Parameters None.
Returns
Requires
Example
while(1) {
...
if (SPI_Ethernet_24j600_doDHCPLeaseTime())
... // its time to renew the IP address lease
}
Notes
None.
SPI_Ethernet_24j600_renewDHCP
Prototype
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
Requires
Example
while(1) {
...
if (SPI_Ethernet_24j600_doDHCPLeaseTime())
SPI_Ethernet_24j600_renewDHCP(5);
// its time to renew the IP address
lease, with 5 secs for a reply
...
}
Notes
None.
Library Example
This code shows how to use the Ethernet mini library :
-the board will reply to ARP & ICMP echo requests
-the board will reply to UDP requests on any port :
- returns the request in upper char with a header made of remote host IP & port number
-the board will reply to HTTP requests on port 80, GET method with pathnames :
- / will return the HTML main page
- /s will return board status as text string
- /t0 ... /t7 will toggle RD0 to RD7 bit and return HTML main page
- all other requests return also HTML main page.
Copy Code To Clipboard
MikroElektronika
540
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
541
MikroElektronika
SPI_Glcd_Init
Prototype
Nothing.
Requires
Global variables :
- SPExpanderCS: Chip Select line
- SPExpanderRST: Reset line
- SPExpanderCS_Direction: Direction of the Chip Select pin
- SPExpanderRST_Direction: Direction of the Reset pin
must be defined before using this function.
The SPI module needs to be initialized. See SPIx_Init and SPIx_Init_Advanced routines.
Example
Notes
None.
MikroElektronika
542
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
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
Requires
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
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
Example
SPI_Glcd_Set_X(25);
Notes
For side, x axis and page layout explanation see schematic at the bottom of this page.
543
MikroElektronika
char SPI_Glcd_Read_Data();
Description Reads data from the current location of Glcd memory and moves to the next location.
Returns
Requires
Parameters None.
Example
char data_;
...
data_ = SPI_Glcd_Read_Data();
Notes
None.
SPI_Glcd_Write_Data
Prototype
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
Example
char data_;
...
SPI_Glcd_Write_Data(data_);
Notes
None.
MikroElektronika
544
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
Example
char data_;
...
SPI_Glcd_Write_Data(data_);
Notes
None.
SPI_Glcd_Dot
Prototype
Nothing.
Requires
Example
Notes
For x and y axis layout explanation see schematic at the bottom of this page..
545
MikroElektronika
void SPI_Glcd_Line(int x_start, int y_start, int x_end, int y_end, char
color);
Nothing.
Requires
Example
Notes
For x and y axis layout explanation see schematic at the bottom of this page..
SPI_Glcd_V_Line
Prototype
Nothing.
Requires
Example
Notes
None.
MikroElektronika
546
Nothing.
Requires
Example
Notes
None.
SPI_Glcd_Rectangle
Prototype
Nothing.
Requires
Example
Notes
None.
547
MikroElektronika
Nothing.
Requires
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
void
SPI_Glcd_Rectangle_Round_Edges_Fill(unsigned
short
x_upper_left,
unsigned short y_upper_left, unsigned short x_bottom_right, unsigned short
y_bottom_right, unsigned short round_radius, unsigned short color);
Nothing.
Requires
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
548
Nothing.
Requires
Example
Notes
None.
SPI_Glcd_Circle
Prototype
Nothing.
Requires
Example
Notes
None.
549
MikroElektronika
Nothing.
Requires
Example
Notes
None.
MikroElektronika
550
Description Sets font that will be used with SPI_Glcd_Write_Char and SPI_Glcd_Write_Text routines.
Parameters None.
Returns
Requires
Example
// Use the custom 5x7 font myfont which starts with space (32):
SPI_Glcd_Set_Font(myfont, 5, 7, 32);
Notes
None.
551
MikroElektronika
void SPI_Glcd_Write_Char(char
color);
chr1,
char
x_pos,
char
page_num,
char
Nothing.
Requires
Example
Notes
For x axis and page layout explanation see schematic at the bottom of this page.
SPI_Glcd_Write_Text
Prototype
void SPI_Glcd_Write_Text(char
color);
text[],
char
x_pos,
char
page_num,
char
Nothing.
Requires
Example
Notes
For x axis and page layout explanation see schematic at the bottom of this page.
MikroElektronika
552
Nothing.
Requires
Example
Notes
Use the mikroC PRO for dsPIC30/33 and PIC24 integrated Glcd Bitmap Editor, Tools > Glcd Bitmap
Editor, to convert image to a constant array suitable for displaying on Glcd.
SPI_Glcd_PartialImage
Prototype
Nothing.
Requires
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_Glcd_PartialImage(10, 12, 10, 15, 16, 32, image);
Notes
Use the mikroC PRO for dsPIC30/33 and PIC24 integrated Glcd Bitmap Editor, Tools > Glcd Bitmap
Editor, to convert image to a constant array suitable for displaying on Glcd.
553
MikroElektronika
void main() {
char counter;
char *someText;
#define COMPLETE_EXAMPLE
ADPCFG = 0xFFFF;
// If Port Expander Library uses SPI1 module
SPI1_Init();
PortExpander
SPI_Glcd_Init(0);
SPI_Glcd_Fill(0x00);
Delay2s();
while(1) {
#ifdef COMPLETE_EXAMPLE
SPI_Glcd_Image(truck_bmp);
Delay2s(); Delay2s();
#endif
SPI_Glcd_Fill(0x00);
Delay2s;
SPI_Glcd_Box(62,40,124,56,1);
SPI_Glcd_Rectangle(5,5,84,35,1);
SPI_Glcd_Line(0, 63, 127, 0,1);
Delay2s();
for(counter = 5; counter < 60; counter+=5 ) {
Delay_ms(250);
SPI_Glcd_V_Line(2, 54, counter, 1);
SPI_Glcd_H_Line(2, 120, counter, 1);
}
MikroElektronika
// Draw image
// Clear Glcd
// Draw box
// Draw rectangle
// Draw line
// Draw horizontal and vertical line
554
// Clear Glcd
// Choose font, see __Lib_GLCDFonts.c
// Write string
// Draw circles
// Draw box
SPI_Glcd_Fill(0xFF);
SPI_Glcd_Set_Font(Character8x7, 8, 7, 32);
someText = "8x7 Font";
SPI_Glcd_Write_Text(someText, 5, 1, 2);
Delay2s();
// Fill Glcd
// Change font
SPI_Glcd_Set_Font(System3x5, 3, 5, 32);
someText = "3X5 CAPITALS ONLY";
SPI_Glcd_Write_Text(someText, 5, 3, 2);
Delay2s();
// Change font
SPI_Glcd_Set_Font(font5x7, 5, 7, 32);
someText = "5x7 Font";
SPI_Glcd_Write_Text(someText, 5, 5, 2);
Delay2s();
// Change font
// Write string
// Write string
// Write string
555
MikroElektronika
MikroElektronika
556
Library Routines
- SPI_Lcd_Config
- SPI_Lcd_Out
- SPI_Lcd_Out_Cp
- SPI_Lcd_Chr
- SPI_Lcd_Chr_Cp
- SPI_Lcd_Cmd
557
MikroElektronika
Nothing.
Requires
Global variables :
- SPExpanderCS: Chip Select line
- SPExpanderRST: Reset line
- SPExpanderCS_Direction: Direction of the Chip Select pin
- SPExpanderRST_Direction: Direction of the Reset pin
must be defined before using this function.
The SPI module needs to be initialized. See SPIx_Init and SPIx_Init_Advanced routines.
Example
Notes
None.
SPI_Lcd_Out
Prototype
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
Example
Notes
None.
MikroElektronika
558
Description Prints text on the 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
Example
Notes
None.
SPI_Lcd_Chr
Prototype
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
Example
Notes
None.
SPI_Lcd_Chr_Cp
Prototype
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
Example
Notes
None.
559
MikroElektronika
Nothing.
Requires
Example
Notes
Predefined constants can be passed to the routine, see Available SPI Lcd Commands.
SPI_Lcd_Cmd
SPI Lcd Command
Purpose
_LCD_FIRST_ROW
_LCD_SECOND_ROW
_LCD_THIRD_ROW
_LCD_FOURTH_ROW
_LCD_CLEAR
Clear display
_LCD_RETURN_HOME
_LCD_CURSOR_OFF
_LCD_UNDERLINE_ON
Underline cursor on
_LCD_BLINK_CURSOR_ON
Blink cursor on
_LCD_MOVE_CURSOR_LEFT
_LCD_MOVE_CURSOR_RIGHT
_LCD_TURN_ON
_LCD_TURN_OFF
_LCD_SHIFT_LEFT
_LCD_SHIFT_RIGHT
MikroElektronika
560
// Loop variable
void Move_Delay() {
Delay_ms(500);
}
void main() {
ADPCFG = 0xFFFF;
Delay_ms(2000);
// Moving text
for(i=0; i<4; i++) {
Spi_Lcd_Cmd(_LCD_SHIFT_RIGHT);
Move_Delay();
}
while(1) {
for(i=0; i<8; i++) {
Spi_Lcd_Cmd(_LCD_SHIFT_LEFT);
Move_Delay();
}
// Endless loop
// Move text to the left 7 times
561
MikroElektronika
MikroElektronika
562
Library Routines
- SPI_Lcd8_Config
- SPI_Lcd8_Out
- SPI_Lcd8_Out_Cp
- SPI_Lcd8_Chr
- SPI_Lcd8_Chr_Cp
- SPI_Lcd8_Cmd
563
MikroElektronika
Nothing.
Requires
Global variables :
- SPExpanderCS: Chip Select line
- SPExpanderRST: Reset line
- SPExpanderCS_Direction: Direction of the Chip Select pin
- SPExpanderRST_Direction: Direction of the Reset pin
must be defined before using this function.
The SPI module needs to be initialized. See SPIx_Init and SPIx_Init_Advanced routines.
Example
Notes
None.
MikroElektronika
564
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
Example
Notes
None.
SPI_Lcd8_Out_Cp
Prototype
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
Example
Notes
None.
SPI_Lcd8_Chr
Prototype
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
Example
Notes
None.
565
MikroElektronika
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
Example
Notes
None.
SPI_Lcd8_Cmd
Prototype
Nothing.
Requires
Example
Notes
Predefined constants can be passed to the routine, see Available SPI Lcd8 Commands.
MikroElektronika
566
Purpose
_LCD_FIRST_ROW
_LCD_SECOND_ROW
_LCD_THIRD_ROW
_LCD_FOURTH_ROW
_LCD_CLEAR
Clear display
_LCD_RETURN_HOME
_LCD_CURSOR_OFF
_LCD_UNDERLINE_ON
Underline cursor on
_LCD_BLINK_CURSOR_ON
Blink cursor on
_LCD_MOVE_CURSOR_LEFT
_LCD_MOVE_CURSOR_RIGHT
_LCD_TURN_ON
_LCD_TURN_OFF
_LCD_SHIFT_LEFT
_LCD_SHIFT_RIGHT
Library Example
This example demonstrates how to communicate Lcd in 8-bit mode via the SPI module, using serial to parallel convertor
MCP23S17.
Copy Code To Clipboard
char *text = "mikroElektronika";
// Port Expander module connections
sbit SPExpanderRST at LATF0_bit;
sbit SPExpanderCS at LATF1_bit;
sbit SPExpanderRST_Direction at TRISF0_bit;
sbit SPExpanderCS_Direction at TRISF1_bit;
// End Port Expander module connections
char i;
// Loop variable
void Move_Delay() {
Delay_ms(500);
}
void main() {
// If Port Expander Library uses SPI1 module
SPI1_Init();
// Initialize SPI module used with PortExpander
567
MikroElektronika
Delay_ms(2000);
// Moving text
for(i=0; i<4; i++) {
Spi_Lcd8_Cmd(_LCD_SHIFT_RIGHT);
Move_Delay();
}
while(1) {
for(i=0; i<8; i++) {
Spi_Lcd8_Cmd(_LCD_SHIFT_LEFT);
Move_Delay();
}
for(i=0; i<8; i++) {
Spi_Lcd8_Cmd(_LCD_SHIFT_RIGHT);
Move_Delay();
}
// Endless loop
// Move text to the left 7 times
}
}
MikroElektronika
568
569
MikroElektronika
T6369C datasheet
RS
C/D
R/W
/RD
/WR
MikroElektronika
570
571
MikroElektronika
/\
|
|
|
|
| PANEL 0
|
\/
/\
|
|
|
|
| PANEL 1
|
|
\/
Nothing.
Requires
Global variables :
- SPExpanderCS: Chip Select line
- SPExpanderRST: Reset line
- SPExpanderCS_Direction: Direction of the Chip Select pin
- SPExpanderRST_Direction: Direction of the Reset pin
must be defined before using this function.
The SPI module needs to be initialized. See the SPIx_Init and SPIx_Init_Advanced routines.
MikroElektronika
572
Notes
None.
SPI_T6963C_writeData
Prototype
Nothing.
Requires
Example
SPI_T6963C_writeData(data_);
Notes
None.
SPI_T6963C_writeCommand
Prototype
Nothing.
Requires
Example
SPI_T6963C_writeCommand(SPI_T6963C_CURSOR_POINTER_SET);
Notes
None.
573
MikroElektronika
Nothing.
Requires
Example
SPI_T6963C_setPtr(SPI_T6963C_grHomeAddr
POINTER_SET);
Notes
None.
start,
SPI_T6963C_ADDRESS_
SPI_T6963C_waitReady
Prototype
void SPI_T6963C_waitReady();
Description Pools the status byte, and loops until Toshiba Glcd module is ready.
Parameters None.
Returns
Nothing.
Requires
Example
SPI_T6963C_waitReady();
Notes
None.
SPI_T6963C_fill
Prototype
Nothing.
Requires
Example
SPI_T6963C_fill(0x33,0x00FF,0x000F);
Notes
None.
MikroElektronika
574
Description Writes a char in the current text panel of Glcd at coordinates (x, y).
Returns
Requires
Example
Notes
None.
SPI_T6963C_write_char
Prototype
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
Mode parameter explanation:
- OR Mode: In the OR-Mode, text and graphics can be displayed and the data is logically OR-ed. This
is the most common way of combining text and graphics for example labels on buttons.
- XOR-Mode: In this mode, the text and graphics data are combined via the logical exclusive OR.
This can be useful to display text in negative mode, i.e. white text on black background.
- AND-Mode: The text and graphic data shown on display are combined via the logical AND
function.
- TEXT-Mode: This option is only available when displaying just a text. The Text Attribute values are
stored in the graphic area of display memory.
For more details see the T6963C datasheet.
Returns
Nothing.
Requires
Example
SPI_T6963C_write_char(A,22,23,SPI_T6963C_ROM_MODE_AND);
Notes
None.
575
MikroElektronika
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
Mode parameter explanation:
- OR Mode: In the OR-Mode, text and graphics can be displayed and the data is logically OR-ed. This
is the most common way of combining text and graphics for example labels on buttons.
- XOR-Mode: In this mode, the text and graphics data are combined via the logical exclusive OR.
This can be useful to display text in negative mode, i.e. white text on black background.
- AND-Mode: The text and graphic data shown on the display are combined via the logical AND
function.
- TEXT-Mode: This option is only available when displaying just a text. The Text Attribute values are
stored in the graphic area of display memory.
For more details see the T6963C datasheet.
Returns
Nothing.
Requires
Example
Notes
None.
MikroElektronika
576
void SPI_T6963C_line(int
pcolor);
x0,
int
y0,
int
x1,
int
y1,
unsigned
char
Nothing.
Requires
Example
Notes
None.
SPI_T6963C_rectangle
Prototype
void SPI_T6963C_rectangle(int x0, int y0, int x1, int y1, unsigned char
pcolor);
Nothing.
Requires
Example
Notes
None.
577
MikroElektronika
void SPI_T6963C_rectangle_round_edges(int x0, int y0, int x1, int y1, int
round_radius, unsigned char pcolor);
Nothing.
Requires
Example
Notes
None.
SPI_T6963C_rectangle_round_edges_fill
Prototype
Nothing.
Requires
Example
SPI_T6963C_rectangle_round_edges_fill(20,
WHITE);
Notes
None.
MikroElektronika
20,
219,
107,
12,
SPI_T6963C_
578
void SPI_T6963C_box(int x0, int y0, int x1, int y1, unsigned char pcolor);
Nothing.
Requires
Example
Notes
None.
SPI_T6963C_circle
Prototype
Nothing.
Requires
Example
Notes
None.
SPI_T6963C_circle_fill
Prototype
Nothing.
Requires
Example
Notes
None.
579
MikroElektronika
Nothing.
Requires
Example
SPI_T6963C_image(my_image);
Notes
SPI_T6963C_PartialImage
Prototype
Nothing.
Requires
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);
Notes
MikroElektronika
580
void SPI_T6963C_sprite(unsigned char px, unsigned char py, const code char
*pic, unsigned char sx, unsigned char sy);
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
Example
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
Nothing.
Requires
Example
SPI_T6963C_set_cursor(cposx, cposy);
Notes
None.
SPI_T6963C_clearBit
Prototype
Nothing.
Requires
Example
Notes
None.
581
MikroElektronika
Nothing.
Requires
Example
Notes
None.
SPI_T6963C_negBit
Prototype
Nothing.
Requires
Example
Notes
None.
SPI_T6963C_displayGrPanel
Prototype
Nothing.
Requires
Example
Notes
None.
MikroElektronika
582
Nothing.
Requires
Example
Notes
None.
SPI_T6963C_setGrPanel
Prototype
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
Example
Notes
None.
SPI_T6963C_setTxtPanel
Prototype
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
Example
Notes
None.
583
MikroElektronika
Description Fill current panel in full (graphic+text) with appropriate value (0 to clear).
Parameters - v: value to fill panel with.
Returns
Nothing.
Requires
Example
Notes
None.
SPI_T6963C_grFill
Prototype
Nothing.
Requires
Example
Notes
None.
SPI_T6963C_txtFill
Prototype
Nothing.
Requires
Example
Notes
None.
MikroElektronika
584
Nothing.
Requires
Example
SPI_T6963C_cursor_height(7);
Notes
None.
SPI_T6963C_graphics
Prototype
Nothing.
Requires
Example
Notes
None.
SPI_T6963C_text
Prototype
Nothing.
Requires
Example
Notes
None.
585
MikroElektronika
Nothing.
Requires
Example
// set cursor on
SPI_T6963C_cursor(1);
Notes
None.
SPI_T6963C_cursor_blink
Prototype
Nothing.
Requires
Example
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 EasydsPIC3 board and dsPIC30F4013.
Copy Code To Clipboard
#include "__SPIT6963C.h"
/*
* bitmap pictures stored in ROM
*/
const code char mikroE_240x128_bmp[];
const code char einstein[];
// Port Expander module connections
sbit SPExpanderRST at LATF0_bit;
sbit SPExpanderCS at LATF1_bit;
sbit SPExpanderRST_Direction at TRISF0_bit;
sbit SPExpanderCS_Direction at TRISF1_bit;
// End Port Expander module connections
void main() {
char txt1[] = " EINSTEIN WOULD HAVE LIKED mE";
char txt[] = " GLCD LIBRARY DEMO, WELCOME !";
MikroElektronika
586
char
int
char
int
panel;
i;
curs;
cposx, cposy;
#define COMPLETE_EXAMPLE
//
//
//
//
Current panel
General purpose register
Cursor visibility
Cursor x-y position
ADPCFG = 0xFFFF;
TRISB0_bit
TRISB1_bit
TRISB2_bit
TRISB3_bit
TRISB4_bit
=
=
=
=
=
1;
1;
1;
1;
1;
//
//
//
//
//
Set
Set
Set
Set
Set
RB0
RB1
RB2
RB3
RB4
as
as
as
as
as
input
input
input
input
input
587
MikroElektronika
// 8 pixel height
// move cursor to top left
// cursor off
/*
* Draw rectangles
*/
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);
/*
* Draw a cross
*/
SPI_T6963C_line(0, 0, 239, 127, SPI_T6963C_WHITE);
SPI_T6963C_line(0, 127, 239, 0, SPI_T6963C_WHITE);
/*
* Draw solid boxes
*/
SPI_T6963C_box(0, 0, 239, 8, SPI_T6963C_WHITE);
SPI_T6963C_box(0, 119, 239, 127, SPI_T6963C_WHITE);
#ifdef COMPLETE_EXAMPLE
/*
* Draw circles
*/
SPI_T6963C_circle(120,
SPI_T6963C_circle(120,
SPI_T6963C_circle(120,
SPI_T6963C_circle(120,
SPI_T6963C_circle(120,
SPI_T6963C_circle(120,
SPI_T6963C_circle(120,
64,
64,
64,
64,
64,
64,
64,
10, SPI_T6963C_WHITE);
30, SPI_T6963C_WHITE);
50, SPI_T6963C_WHITE);
70, SPI_T6963C_WHITE);
90, SPI_T6963C_WHITE);
110, SPI_T6963C_WHITE);
130, SPI_T6963C_WHITE);
// Draw a sprite
// Select other graphic
// Draw an image
#endif
for(;;) {
/*
* If RB0 is pressed, display only graphic panel
*/
MikroElektronika
// Endless loop
588
if(RB0_bit) {
SPI_T6963C_graphics(1);
SPI_T6963C_text(0);
Delay_ms(300);
}
#ifdef COMPLETE_EXAMPLE
/*
* If RB1 is pressed, toggle the display between graphic panel 0 and graphic panel
*/
else if(RB1_bit) {
panel++;
panel &= 1;
SPI_T6963C_displayGrPanel(panel);
Delay_ms(300);
}
#endif
/*
* If RB2 is pressed, display only text panel
*/
else if(RB2_bit) {
SPI_T6963C_graphics(0);
SPI_T6963C_text(1);
Delay_ms(300);
}
/*
* If RB3 is pressed, display text and graphic panels
*/
else if(RB3_bit) {
SPI_T6963C_graphics(1);
SPI_T6963C_text(1);
Delay_ms(300);
}
/*
* If RB4 is pressed, change cursor
*/
else if(RB4_bit) {
curs++;
if(curs == 3) curs = 0;
switch(curs) {
case 0:
// no cursor
SPI_T6963C_cursor(0);
break;
case 1:
// blinking cursor
SPI_T6963C_cursor(1);
SPI_T6963C_cursor_blink(1);
break;
case 2:
// non blinking cursor
SPI_T6963C_cursor(1);
SPI_T6963C_cursor_blink(0);
break;
}
589
MikroElektronika
MikroElektronika
590
591
MikroElektronika
T6369C datasheet
RS
C/D
R/W
/RD
/WR
MikroElektronika
592
Description :
Example :
char T6963C_dataPort
at PORTB;
extern
sfr
T6963C_ctrlwr;
sbit
Write signal.
sbit T6963C_ctrlwr at
LATF2_bit;
extern
sfr
T6963C_ctrlrd;
sbit
Read signal.
sbit T6963C_ctrlrd at
LATF1_bit;
extern
sfr
T6963C_ctrlcd;
sbit
Command/Data signal.
sbit T6963C_ctrlcd at
LATF0_bit;
extern
sfr
T6963C_ctrlrst;
sbit
Reset signal.
sbit
T6963C_ctrlrst
at LATF4_bit;
extern
sfr
sbit
T 6 9 6 3 C _ c t r l w r _ Direction of the Write pin.
Direction;
sbit
T6963C_ctrlwr_
Direction at TRISF2_
bit;
extern
sfr
sbit
T 6 9 6 3 C _ c t r l r d _ Direction of the Read pin.
Direction;
sbit
T6963C_ctrlrd_
Direction at TRISF1_
bit;
extern
sfr
sbit
Direction of the Command/
T6963C_ctrlcd_
Data pin.
Direction;
sbit
T6963C_ctrlcd_
Direction at TRISF0_
bit;
extern
sfr
sbit
T 6 9 6 3 C _ c t r l r s t _ Direction of the Reset pin.
Direction;
sbit T6963C_ctrlrst_
Direction at TRISF4_
bit;
593
MikroElektronika
MikroElektronika
594
/\
|
|
|
|
| PANEL 0
|
\/
/\
|
|
|
|
| PANEL 1
|
|
\/
Nothing.
Requires
Global variables :
- T6963C_dataPort: Data Port
- T6963C_ctrlwr: Write signal pin
- T6963C_ctrlrd: Read signal pin
- T6963C_ctrlcd: Command/Data signal pin
- T6963C_ctrlrst: Reset signal pin
- T6963C_ctrlwr_Direction: Direction of Write signal pin
- T6963C_ctrlrd_Direction: Direction of Read signal pin
- T6963C_ctrlcd_Direction: Direction of Command/Data signal pin
- T6963C_ctrlrst_Direction: Direction of Reset signal pin
must be defined before using this function.
595
MikroElektronika
// DATA port
sbit
sbit
sbit
sbit
sbit
sbit
sbit
sbit
//
//
//
//
//
//
//
//
T6963C_ctrlwr at LATF2_bit;
T6963C_ctrlrd at LATF1_bit;
T6963C_ctrlcd at LATF0_bit;
T6963C_ctrlrst at LATF4_bit;
T6963C_ctrlwr_Direction at TRISF2_bit;
T6963C_ctrlrd_Direction at TRISF1_bit;
T6963C_ctrlcd_Direction at TRISF0_bit;
T6963C_ctrlrst_Direction at TRISF4_bit;
WR write signal
RD read signal
CD command/data signal
RST reset signal
WR write signal
RD read signal
CD command/data signal
RST reset signal
None.
T6963C_writeData
Prototype
Nothing.
Requires
Example
T6963C_writeData(AddrL);
Notes
None.
MikroElektronika
596
Nothing.
Requires
Example
T6963C_writeCommand(T6963C_CURSOR_POINTER_SET);
Notes
None.
T6963C_setPtr
Prototype
Nothing.
Requires
Example
Notes
None.
T6963C_waitReady
Prototype
void T6963C_waitReady();
Description Pools the status byte, and loops until Toshiba Glcd module is ready.
Parameters None.
Returns
Nothing.
Requires
Example
T6963C_waitReady();
Notes
None.
597
MikroElektronika
Nothing.
Requires
Example
T6963C_fill(0x33,0x00FF,0x000F);
Notes
None.
T6963C_dot
Prototype
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
Example
Notes
None.
MikroElektronika
598
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
Mode parameter explanation:
- OR Mode: In the OR-Mode, text and graphics can be displayed and the data is logically OR-ed. This
is the most common way of combining text and graphics for example labels on buttons.
- XOR-Mode: In this mode, the text and graphics data are combined via the logical exclusive OR.
This can be useful to display text in the negative mode, i.e. white text on black background.
- AND-Mode: The text and graphic data shown on display are combined via the logical AND
function.
- TEXT-Mode: This option is only available when displaying just a text. The Text Attribute values are
stored in the graphic area of display memory.
For more details see the T6963C datasheet.
Returns
Nothing.
Requires
Example
T6963C_write_char(A,22,23,T6963C_ROM_MODE_AND);
Notes
None.
599
MikroElektronika
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
Mode parameter explanation:
- OR Mode: In the OR-Mode, text and graphics can be displayed and the data is logically OR-ed. This
is the most common way of combining text and graphics for example labels on buttons.
- XOR-Mode: In this mode, the text and graphics data are combined via the logical exclusive OR.
This can be useful to display text in the negative mode, i.e. white text on black background.
- AND-Mode: The text and graphic data shown on display are combined via the logical AND
function.
- TEXT-Mode: This option is only available when displaying just a text. The Text Attribute values are
stored in the graphic area of display memory.
For more details see the T6963C datasheet.
Returns
Nothing.
Requires
Example
Notes
None.
T6963C_line
Prototype
void T6963C_line(int x0, int y0, int x1, int y1, unsigned char pcolor);
Nothing.
Requires
Example
Notes
None.
MikroElektronika
600
void T6963C_rectangle(int
pcolor);
x0,
int
y0,
int
x1,
int
y1,
unsigned
char
Nothing.
Requires
Example
Notes
None.
T6963C_rectangle_round_edges
Prototype
void T6963C_rectangle_round_edges(int x0, int y0, int x1, int y1, int round_
radius, unsigned char pcolor);
Nothing.
Requires
Example
Notes
None.
601
MikroElektronika
void T6963C_rectangle_round_edges_fill(int x0, int y0, int x1, int y1, int
round_radius, unsigned char pcolor);
Nothing.
Requires
Example
Notes
None.
T6963C_box
Prototype
void T6963C_box(int x0, int y0, int x1, int y1, unsigned char pcolor);
Nothing.
Requires
Example
Notes
None.
T6963C_circle
Prototype
Nothing.
Requires
Example
Notes
None.
MikroElektronika
602
Nothing.
Requires
Example
Notes
None.
T6963C_image
Prototype
Nothing.
Requires
Example
T6963C_image(my_image);
Notes
603
MikroElektronika
Nothing.
Requires
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
T6963C_sprite
Prototype
void T6963C_sprite(unsigned char px, unsigned char py, const code char *pic,
unsigned char sx, unsigned char sy);
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
Example
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
604
Nothing.
Requires
Example
T6963C_set_cursor(cposx, cposy);
Notes
None.
T6963C_clearBit
Prototype
Nothing.
Requires
Example
Notes
None.
T6963C_setBit
Prototype
Nothing.
Requires
Example
Notes
None.
605
MikroElektronika
Nothing.
Requires
Example
Notes
None.
T6963C_displayGrPanel
Prototype
Nothing.
Requires
Example
Notes
None.
T6963C_displayTxtPanel
Prototype
Nothing.
Requires
Example
Notes
None.
MikroElektronika
606
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
Example
Notes
None.
T6963C_setTxtPanel
Prototype
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
Example
Notes
None.
T6963C_panelFill
Prototype
Description Fill current panel in full (graphic+text) with appropriate value (0 to clear).
Parameters - v: value to fill panel with.
Returns
Nothing.
Requires
Example
Notes
None.
607
MikroElektronika
Nothing.
Requires
Example
Notes
None.
T6963C_txtFill
Prototype
Nothing.
Requires
Example
Notes
None.
T6963C_cursor_height
Prototype
Nothing.
Requires
Example
T6963C_cursor_height(7);
Notes
None.
MikroElektronika
608
Nothing.
Requires
Example
Notes
None.
T6963C_text
Prototype
Nothing.
Requires
Example
Notes
None.
T6963C_cursor
Prototype
Nothing.
Requires
Example
// set cursor on
T6963C_cursor(1);
Notes
None.
609
MikroElektronika
Nothing.
Requires
Example
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 dsPICPRO2 board and dsPIC30F6014A.
Copy Code To Clipboard
#include
"__T6963C.h"
// DATA port
sbit
sbit
sbit
sbit
sbit
sbit
sbit
sbit
//
//
//
//
//
//
//
//
T6963C_ctrlwr at LATF2_bit;
T6963C_ctrlrd at LATF1_bit;
T6963C_ctrlcd at LATF0_bit;
T6963C_ctrlrst at LATF4_bit;
T6963C_ctrlwr_Direction at TRISF2_bit;
T6963C_ctrlrd_Direction at TRISF1_bit;
T6963C_ctrlcd_Direction at TRISF0_bit;
T6963C_ctrlrst_Direction at TRISF4_bit;
WR write signal
RD read signal
CD command/data signal
RST reset signal
WR write signal
RD read signal
CD command/data signal
RST reset signal
MikroElektronika
610
char
int
char
int
panel;
i;
curs;
cposx, cposy;
#define COMPLETE_EXAMPLE
//
//
//
//
Current panel
General purpose register
Cursor visibility
Cursor x-y position
ADPCFG = 0xFFFF;
TRISB8_bit = 1;
TRISB9_bit = 1;
TRISB10_bit = 1;
TRISB11_bit = 1;
TRISB12_bit = 1;
//
//
//
//
//
T6963C_ctrlce_Direction = 0;
T6963C_ctrlce = 0;
T6963C_ctrlfs_Direction = 0;
T6963C_ctrlfs = 0;
T6963C_ctrlmd_Direction = 0;
T6963C_ctrlmd = 0;
Set
Set
Set
Set
Set
RF0
RF1
RF2
RF3
RF4
as
as
as
as
as
input
input
input
input
input
// Enable T6963C
// Font Select 8x8
// Column number select
// Initialize T6963C
T6963C_init(240, 128, 8);
/*
* Enable both graphics and text display at the same time
*/
T6963C_graphics(1);
T6963C_text(1);
panel = 0;
i = 0;
curs = 0;
cposx = cposy = 0;
/*
* 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);
T6963C_set_cursor(0, 0);
T6963C_cursor(0);
611
// 8 pixel height
// Move cursor to top left
// Cursor off
MikroElektronika
10, T6963C_WHITE);
30, T6963C_WHITE);
50, T6963C_WHITE);
70, T6963C_WHITE);
90, T6963C_WHITE);
110, T6963C_WHITE);
130, T6963C_WHITE);
// Draw a sprite
T6963C_setGrPanel(1);
T6963C_image(mikroE_240x128_bmp);
// Draw an image
#endif
for(;;) {
// Endless loop
/*
* If RF0 is pressed, display only graphic panel
*/
if(RB8_bit) {
T6963C_graphics(1);
T6963C_text(0);
Delay_ms(300);
}
#ifdef COMPLETE_EXAMPLE
MikroElektronika
612
613
MikroElektronika
HW Connection
MikroElektronika
614
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 mikroC PRO for dsPIC30/33 and PIC24 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.
Description :
Example :
char TFT_DataPort at
LATE;
char
TFT_DataPort_
Direction at TRISE;
sbit TFT_WR_Direction
at TRISD13_bit;
sbit TFT_RD_Direction
at TRISD12_bit;
sbit TFT_CS_Direction
at TRISC3_bit;
sbit TFT_RS_Direction
at TRISB13_bit;
sbit TFT_RST_Direction
at TRISC1_bit;
615
MikroElektronika
MikroElektronika
616
Returns
Nothing
Global variables :
- TFT_DataPort: Data Port
- TFT_WR: Write signal pin
- TFT_RD: Read signal pin
- TFT_CS: Chip Select signal pin
- TFT_RS: Register Select signal pin
- TFT_RST: Reset signal pin
- TFT_DataPort_Direction: Direction of Data Port
- TFT_WR_Direction: Direction of Write signal pin
- TFT_RD_Direction: Direction of Read signal pin
- TFT_CS_Direction: Direction of Chip Select signal pin
- TFT_RS_Direction: Direction of Register Select signal pin
- TFT_RST_Direction: Direction of Reset signal pin
must be defined before using this function.
Example
617
MikroElektronika
Returns
Nothing
Description Accesses register space of the controller and sets the desired register.
Parameters :
- index: desired register number.
Requires
Example
TFT_Write_Command
Prototype
Returns
Nothing
Example
// Write a command
TFT_Write_Command(0x02);
TFT_Write_Data
Prototype
Returns
Nothing
Example
// Send data
TFT_Write_Data(0x02);
MikroElektronika
618
Returns
Nothing
Description This function sets appropriate pointers to a user-defined basic routines in order to enable multiple
working modes.
Parameters :
- Set_Index_Ptr: Set_Index handler.
- Write_Command_Ptr: _Write_Command handler.
- Write_Data_Ptr: Write_Data handler.
Requires
None.
Example
619
MikroElektronika
Returns
Nothing
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
Description
FO_HORIZONTAL
Horizontal orientation
FO_VERTICAL
Vertical orientation
Requires
Example
MikroElektronika
620
Returns
Nothing.
Example
TFT_Write_Char(A,22,23,);
TFT_Write_Text
Prototype
Returns
Nothing.
Example
621
MikroElektronika
Returns
Nothing.
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
Requires
Example
TFT_Fill_Screen(CL_BLACK);
MikroElektronika
622
Returns
Nothing.
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
Requires
Example
623
MikroElektronika
Returns
Nothing.
Description Sets color and thickness parameter for drawing line, circle and rectangle elements.
Parameters :
- pen_color: Sets color.
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
Example
TFT_Set_Pen(CL_BLACK, 10);
MikroElektronika
624
Returns
Nothing.
Description Sets color and gradient which will be used to fill circles or rectangles.
Parameters :
- brush_enabled: enable brush fill.
Value
Description
625
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
Description
Enable gradient.
Disable gradient.
Description
LEFT_TO_RIGHT
TOP_TO_BOTTOM
MikroElektronika
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
626
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
Requires
Example
TFT_Line
Prototype
Returns
Nothing.
Example
627
MikroElektronika
Returns
Nothing.
Example
TFT_V_Line
Prototype
Returns
Nothing.
Example
MikroElektronika
628
Returns
Nothing.
Example
TFT_Circle
Prototype
Returns
Nothing.
Example
TFT_Image
Prototype
void TFT_Image(unsigned int left, unsigned int top, code const far unsigned
short * image, unsigned short stretch);
Returns
Nothing.
Example
629
MikroElektronika
Returns
Nothing.
Example
// Draws a 10x15 part of the image starting from the upper left corner on
the coordinate (10,12)
TFT_PartialImage(10, 12, 10, 15, image, 1);
TFT_Image_Jpeg
Prototype
char TFT_Image_Jpeg(unsigned int left, unsigned int top, code const far
unsigned short *image);
Returns
Example
TFT_Image_Jpeg(0, 0, image);
MikroElektronika
630
Returns
Returns a color value in the following bit-order : 5 bits red, 6 bits green and 5 bits blue color.
Example
TFT_Color16bitToRGB
Prototype
Returns
Nothing.
Example
631
MikroElektronika
TFT HW connection
MikroElektronika
632
Example:
DriveA line.
DriveB line.
sbit
DriveA_Direction
TRISC13_bit;
at
sbit
DriveB_Direction
TRISC14_bit;
at
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
633
MikroElektronika
int
display_height,
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
Example
ADC1_Init();
TP_Init(128, 64, 6, 7);
Notes
None.
TP_Set_ADC_Threshold
Prototype
Description Set custom ADC threshold value, call this function after TP_Init.
Parameters
- threshold: custom ADC threshold value.
Returns
Nothing.
Requires
Example
TP_Set_ADC_Threshold(3900);
Notes
None.
MikroElektronika
634
char TP_Press_Detect();
Requires
Global variables:
- DriveA: DriveA.
- DriveB: DriveB.
- DriveA_Direction: Direction of DriveA pin.
- DriveB_Direction: Direction of DriveB pin.
must be defined before using this function.
Example
Notes
635
None.
MikroElektronika
char TP_Get_Coordinates(unsigned
coordinate);
int
*x_coordinate,
unsigned
int
*y_
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
Requires
Nothing.
Example
if (TP_Get_Coordinates(&x_coord, &y_coord) == 0) {
...
}
Notes
None.
TP_Calibrate_Bottom_Left
Prototype
void TP_Calibrate_Bottom_Left();
Nothing.
Requires
Nothing.
Example
TP_Calibrate_Bottom_Left();
Notes
None.
MikroElektronika
636
void TP_Calibrate_Upper_Right();
Nothing.
Requires
Nothing.
Example
TP_Calibrate_Upper_Right();
Notes
None.
TP_Get_Calibration_Consts
Prototype
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,
calibration constants
Notes
None.
637
&y_min,
&x_max,
&y_max);
//
Get
MikroElektronika
x_min,
unsigned
int
x_max,
Nothing.
Requires
Nothing.
Example
Notes
None.
// Set calibration
Library Example
The following drawing demo tests routines of the Touch Panel library:
Copy Code To Clipboard
// Glcd module connections
sbit GLCD_D7 at RD3_bit;
sbit GLCD_D6 at RD2_bit;
sbit GLCD_D5 at RD1_bit;
sbit GLCD_D4 at RD0_bit;
sbit GLCD_D3 at RB3_bit;
sbit GLCD_D2 at RB2_bit;
sbit GLCD_D1 at RB1_bit;
sbit GLCD_D0 at RB0_bit;
sbit GLCD_D7_Direction at TRISD3_bit;
sbit GLCD_D6_Direction at TRISD2_bit;
sbit GLCD_D5_Direction at TRISD1_bit;
sbit GLCD_D4_Direction at TRISD0_bit;
sbit GLCD_D3_Direction at TRISB3_bit;
sbit GLCD_D2_Direction at TRISB2_bit;
sbit GLCD_D1_Direction at TRISB1_bit;
sbit GLCD_D0_Direction at TRISB0_bit;
MikroElektronika
638
DriveA_Direction = 0;
DriveB_Direction = 0;
Glcd_Init();
Glcd_Fill(0);
// Initialize GLCD
// Clear GLCD
ADC1_Init();
TP_Init(128, 64, 6, 7);
TP_Set_ADC_Threshold(3900);
}
void Calibrate() {
Glcd_Dot(0,63,1);
// Draw bottom left dot
Glcd_Write_Text(TOUCH BOTTOM LEFT,12,3,1);
TP_Calibrate_Bottom_Left();
// Calibration of bottom left corner
Delay_ms(1000);
639
MikroElektronika
Delay_ms(1000);
}
void main() {
Initialize();
Glcd_Write_Text(CALIBRATION,12,3,1);
Delay_ms(1000);
Glcd_Fill(0);
// Clear GLCD
Calibrate();
Glcd_Fill(0);
Glcd_Write_Text(WRITE ON SCREEN, 20, 5, 1) ;
Delay_ms(1000);
Glcd_Fill(0);
// Clear GLCD
Glcd_V_Line(0,7,0,1);
Glcd_Write_Text(clear_msg,1,0,0);
Glcd_V_Line(0,7,97,1);
Glcd_Write_Text(erase_msg,98,0,0);
// Pen Menu:
Glcd_Rectangle(41,0,52,9,1);
Glcd_Box(45,3,48,6,1);
Glcd_Rectangle(63,0,70,7,1);
Glcd_Box(66,3,67,4,1);
Glcd_Rectangle(80,0,86,6,1);
Glcd_Dot(83,3,1);
write_erase = 1;
pen_size = 1;
while (1) {
if (TP_Press_Detect()) {
// After a PRESS is detected read X-Y and convert it to 128x64 space
if (TP_Get_Coordinates(&x_coord, &y_coord) == 0) {
if ((x_coord < 31) && (y_coord < 8)) {
Glcd_Fill(0);
MikroElektronika
640
641
MikroElektronika
MikroElektronika
642
Example:
DriveX_Left line.
sbit DriveX_Left
at LATB13_bit;
DriveX_Right line.
sbit DriveX_Right
at LATB11_bit;
DriveY_Up line.
sbit
DriveY_Up
at LATB12_bit;
DriveY_Down line.
sbit DriveY_Down
at LATB10_bit;
sbit
DriveX_
Left_Direction
at TRISB13_bit;
sbit
DriveX_
Right_Direction
at TRISB11_bit;
extern sfr
Direction;
sbit DriveY_Up_
Direction
at
TRISB12_bit;
sbit
sbit
DriveY_
Down_Direction
at TRISB10_bit;
Library Routines
- TP_TFT_Init
- TP_TFT_Set_ADC_Threshold
- TP_TFT_Press_Detect
- TP_TFT_Get_Coordinates
- TP_TFT_Calibrate_Min
- TP_TFT_Calibrate_Max
- TP_TFT_Get_Calibration_Consts
- TP_TFT_Set_Calibration_Consts
643
MikroElektronika
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
Example
ADC1_Init();
// Initalize ADC module
TP_TFT_Init(320, 240, 13, 12); // Initialize touch panel
Notes
None.
TP_TFT_Set_ADC_Threshold
Prototype
Description Set custom ADC threshold value, call this function after TP_TFT_Init.
Parameters
- threshold: custom ADC threshold value.
Returns
Nothing.
Requires
Example
TP_TFT_Set_ADC_Threshold(900);
Notes
None.
MikroElektronika
644
char TP_TFT_Press_Detect();
Requires
Global variables:
- DriveX_Left: DriveX_Left pin.
- DriveX_Right: DriveX_Right pin.
- DriveY_Up: DriveY_Up pin.
- DriveY_Down: DriveY_Down pin.
- DriveX_Left_Direction: Direction of DriveX_Left pin.
- DriveX_Right_Direction: Direction of DriveX_Right pin.
- DriveY_Up_Direction: Direction of DriveY_Up pin.
- DriveY_Down_Direction: Direction of DriveY_Down pin.
must be defined before using this function.
Example
Notes
645
None.
MikroElektronika
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) {
...
}
Notes
None.
TP_TFT_Calibrate_Min
Prototype
void TP_TFT_Calibrate_Min();
Nothing.
Requires
Nothing.
Example
TP_TFT_Calibrate_Min();
Notes
None.
MikroElektronika
646
void TP_TFT_Calibrate_Max();
Nothing.
Requires
Nothing.
Example
TP_TFT_Calibrate_Max();
Notes
None.
TP_TFT_Get_Calibration_Consts
Prototype
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
Notes
None.
647
MikroElektronika
Nothing.
Requires
Nothing.
Example
Notes
None.
// Set calibration
HW Connection
MikroElektronika
648
UART Library
The UART hardware module is available with a number of dsPIC30/33 and PIC24 MCUs. The mikroC PRO for
dsPIC30/33 and PIC24 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 4.
- Switching between the UART modules in the UART library is done by the UART_Set_Active function (UART modules
have to be previously initialized).
- Number of UART modules per MCU differs from chip to chip. Please, read the appropriate datasheet before utilizing
this library.
Library Routines
- UARTx_Init
- UARTx_Init_Advanced
- UARTx_Data_Ready
- UARTx_Tx_Idle
- UARTx_Read
- UARTx_Read_Text
- UARTx_Write
- UARTx_Write_Text
- UART_Set_Active
649
MikroElektronika
Nothing.
Requires
Example
Notes
Refer to the device data sheet for baud rates allowed for specific Fosc.
For the dsPIC33 and PIC24 MCUs, the compiler will choose for which speed the calculation is to be
performed (high or low). This does not mean that it is the best choice for desired baud rate.
If the baud rate error generated in this way is too big then UARTx_Init_Advanced routine, which allows
speed select be used.
UART library routines require you to specify the module you want to use. To select the desired UART
module, simply change the letter x in the routine prototype for a number from 1 to 4.
Switching between the UART modules in the UART library is done by the UART_Set_Active 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
650
// dsPIC30 prototype
void UARTx_Init_Advanced(unsigned
unsigned int stop_bits);
long
baud_rate,
unsigned
int
parity,
int
parity,
Description Configures and initializes the UART module with user defined settings.
Parameters
_UART_8BIT_NOPARITY
_UART_8BIT_EVENPARITY
_UART_8BIT_ODDPARITY
_UART_9BIT_NOPARITY
_UART_ONE_STOPBIT
_UART_TWO_STOPBITS
- high_low_speed: high/low speed selection parameter. Available only for dsPIC33 and PIC24
MCUs.
Valid values:
High/Low Speed
Description
651
_UART_LOW_SPEED
Hi Speed UART
_UART_HI_SPEED
MikroElektronika
Nothing.
Requires
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 4.
Switching between the UART modules in the UART library is done by the UART_Set_Active function
(UART modules have to be previously initialized).
Number of UART modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
652
unsigned UARTx_Data_Ready();
Description The function tests if data in receive buffer is ready for reading.
Parameters
None.
Returns
Requires
Example
unsigned receive;
...
// read data if ready
if (UART1_Data_Ready())
receive = UART1_Read();
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 4.
Number of UART modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
653
MikroElektronika
char UARTx_Tx_Idle();
Description Use the function to test if the transmit shift register is empty or not.
Parameters
None.
Returns
Requires
Example
// If the previous data has been shifted out, send next data:
if (UART1_Tx_Idle() == 1) {
UART1_Write(_data);
}
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 4.
Number of UART modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
654
unsigned UARTx_Read();
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
Example
unsigned receive;
...
// read data if ready
if (UART1_Data_Ready())
receive = UART1_Read();
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 4.
Number of UART modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
655
MikroElektronika
Description Reads characters received via UART until the delimiter sequence is detected. The read sequence is
stored in the parameter output; delimiter sequence is stored in the parameter delimiter.
This is a blocking call: the delimiter sequence is expected, otherwise the procedure exits (if the
delimiter is not found).
Parameters
- Output: received text
- Delimiter: sequence of characters that identifies the end of a received string
- Attempts: defines number of received characters in which Delimiter sequence is expected. If
Attempts is set to 255, this routine will continuously try to detect the Delimiter sequence.
Returns
Nothing.
Requires
Example
Read text until the sequence OK is received, and send back whats been received:
UART1_Init(4800);
Delay_ms(100);
while (1) {
if (UART1_Data_Ready() == 1) {
UART1_Read_Text(output, OK, 10);
found
UART1_Write_Text(output);
}
}
Notes
// if data is received
// reads text until OK is
// sends back text
UART library routines require you to specify the module you want to use. To select the desired UART
module, simply change the letter x in the routine prototype for a number from 1 to 4.
Number of UART modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
656
Nothing.
Requires
Example
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 4.
Number of UART modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
657
MikroElektronika
Nothing.
Requires
Example
Read text until the sequence OK is received, and send back whats been received:
UART1_Init(4800);
Delay_ms(100);
while (1) {
if (UART1_Data_Ready() == 1) {
UART1_Read_Text(output, OK, 10);
found
UART1_Write_Text(output);
}
}
Notes
// if data is received
// reads text until OK is
// sends back text
UART library routines require you to specify the module you want to use. To select the desired UART
module, simply change the letter x in the routine prototype for a number from 1 to 4.
Number of UART modules per MCU differs from chip to chip. Please, read the appropriate datasheet
before utilizing this library.
MikroElektronika
658
Description Sets active UART module which will be used by UARTx_Data_Ready, UARTx_Read and UARTx_
Write routines.
Parameters
Parameters:
- read_ptr: UARTx_Read handler
- write_ptr: UARTx_Write handler
- ready_ptr: UARTx_Data_Ready handler
- tx_idle_ptr: UARTx_Tx_Idle handler
Returns
Nothing.
Requires
Example
UART1_Init(9600);
UART2_Init(9600);
RS485Master_Init();
659
None.
MikroElektronika
//
U1MODEbits.ALTIO = 1; // un-comment this line to have Rx and Tx pins on their
alternate
// locations. This is used to free the pins for other module,
namely the SPI.
UART1_Write_Text(Start);
UART1_Write(10);
UART1_Write(13);
while (1) {
if (UART1_Data_Ready()) {
uart_rd = UART1_Read();
UART1_Write(uart_rd);
}
}
//
//
//
//
Endless loop
If data is received,
read the received data,
and send data via UART
MikroElektronika
660
RS232 HW connection
661
MikroElektronika
USB Library
Universal Serial Bus (USB) provides a serial bus standard for connecting a wide variety of devices, including computers,
cell phones, game consoles, PDAs, etc.
USB Library contains HID routines that support HID class devices, and also the generic routines that can be used with
vendor specified drivers.
Library Routines
- HID_Enable
- HID_Read
- HID_Write
- HID_Disable
- USB_Interrupt_Proc
- USB_Polling_Proc
- Gen_Enable
- Gen_Read
- Gen_Write
MikroElektronika
662
Nothing.
Requires
Nothing.
Example
HID_Enable(&readbuff,&writebuff);
Notes
This function needs to be called before using other routines of USB HID Library.
HID_Read
Prototype
char HID_Read(void);
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
Notes
None.
663
MikroElektronika
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
Notes
HID_Disable
Prototype
void HID_Disable(void);
None.
Returns
Nothing.
Requires
USB HID needs to be enabled before using this function. See HID_Enable.
Example
HID_Disable();
Notes
None.
MikroElektronika
664
void USB_Interrupt_Proc(void);
Description This routine is used for servicing various USB bus events. Should be called inside USB interrupt
routine.
Parameters
None.
Returns
Nothing.
Requires
Nothing.
Example
Notes
Do not use this function with USB_Polling_Proc, only one should be used. To enable servicing through
interrupt, USB_INTERRUPT constant should be set (it is set by default in descriptor file).
USB_Polling_Proc
Prototype
void USB_Polling_Proc(void);
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(1) {
USB_Polling_Proc();
kk = HID_Read();
if (kk != 0) {
for(cnt=0; cnt < 64; cnt++)
writebuff[cnt]=readbuff[cnt];
HID_Write(&writebuff,64);
}
}
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).
665
MikroElektronika
Nothing.
Requires
Example
Gen_Enable(&readbuff,&writebuff);
Notes
None.
Gen_Read
Prototype
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
Requires
Example
while(Gen_Read(readbuff,64,1)==0)
;
Notes
None.
MikroElektronika
666
Requires
Example
while(Gen_Write(writebuff,64,1)==0)
;
Notes
None.
667
MikroElektronika
while(!HID_Write(&writebuff,64))
;
HW Connection
MikroElektronika
668
DSP Libraries
mikroC PRO for dsPIC30/33 and PIC24 includes various libraries for DSP engine. All DSP routines work with fractional
Q15 format.
669
MikroElektronika
Library Routines
- FIR_Radix
FIR_Radix
Prototype
*ptrCoeffs,
with :
N - buffer length
k - current index
Requires
Nothing.
Example
Notes
MikroElektronika
670
Library Routines
IIR_Radix
IIR_Radix
Prototype
unsigned IIR_Radix (const int BScale, const int AScale, const signed *ptrB,
const signed *ptrA, unsigned FilterOrder, unsigned *ptrInput, unsigned
InputLen, unsigned *ptrOutput, unsigned Index);
Nothing.
Example
Notes
671
MikroElektronika
FFT Library
mikroC PRO for dsPIC30/33 and PIC24 includes a library for FFT calculation. All routines work with fractional Q15 format.
Library Routines
- FFT
FFT
Prototype
Description Function applies FFT transformation to input samples, input samples must be in Y data space.
Nothing.
Requires
Nothing.
Example
Notes
Complex array of FFT samples is placed in Samples parameter. Input Samples are arranged in manner
Re,Im,Re,Im... (where Im is always zero). Output samples are arranged in the same manner but Im
parts are different from zero. Output samples are symmetrical (First half of output samples (index from
0 to N/2) is identical as second half of output samples(index from N/2 to N).
Input data is a complex vector such that the magnitude of the real and imaginary parts of each of its
elements is less than 0.5. If greater or equal to this value the results could produce saturation. Note
that the output values are scaled by a factor of 1/N, with N the length of the FFT. input is expected in
natural ordering, while output is produced in bit reverse ordering.
MikroElektronika
672
0xE707,
0xB8E3,
0x9592,
0x8276,
0x8276,
0x9592,
0xB8E3,
0xE707,
0x7A7D,
0x62F2,
0x3C57,
0x0C8C,
0xDAD8,
0xAECC,
0x8F1D,
0x809E,
0xDAD8,
0xAECC,
0x8F1D,
0x809E,
0x8583,
0x9D0E,
0xC3A9,
0xF374};
0xF374,
0xDAD8,
0xC3A9,
0xAECC,
0x9D0E,
0x8F1D,
0x8583,
0x809E,
0x809E,
0x8583,
0x8F1D,
0x9D0E,
0xAECC,
0xC3A9,
0xDAD8,
0xF374,
0x7E9D,
0x7885,
0x6DCA,
0x5ED7,
0x4C40,
0x36BA,
0x1F1A,
0x0648,
0xED38,
0xD4E1,
0xBE32,
0xAA0A,
0x9930,
0x8C4A,
0x83D6,
0x8027,
0xED38,
0xD4E1,
0xBE32,
0xAA0A,
0x9930,
0x8C4A,
0x83D6,
0x8027,
0x8163,
0x877B,
0x9236,
0xA129,
0xB3C0,
0xC946,
0xE0E6,
0xF9B8};
TwiddleCoeff_128
const unsigned TwiddleCoeff_128[128] = {
0x7FFF, 0x0000, 0x7FD9, 0xF9B8, 0x7F62,
0x7D8A, 0xE707, 0x7C2A, 0xE0E6, 0x7A7D,
0x7642, 0xCF04, 0x73B6, 0xC946, 0x70E3,
0x6A6E, 0xB8E3, 0x66D0, 0xB3C0, 0x62F2,
0x5A82, 0xA57E, 0x55F6, 0xA129, 0x5134,
0x471D, 0x9592, 0x41CE, 0x9236, 0x3C57,
0x30FC, 0x89BE, 0x2B1F, 0x877B, 0x2528,
0x18F9, 0x8276, 0x12C8, 0x8163, 0x0C8C,
0x0000, 0x8000, 0xF9B8, 0x8027, 0xF374,
0xE707, 0x8276, 0xE0E6, 0x83D6, 0xDAD8,
0xCF04, 0x89BE, 0xC946, 0x8C4A, 0xC3A9,
0xB8E3, 0x9592, 0xB3C0, 0x9930, 0xAECC,
0xA57E, 0xA57E, 0xA129, 0xAA0A, 0x9D0E,
0x9592, 0xB8E3, 0x9236, 0xBE32, 0x8F1D,
0x89BE, 0xCF04, 0x877B, 0xD4E1, 0x8583,
0x8276, 0xE707, 0x8163, 0xED38, 0x809E,
673
MikroElektronika
0xF9B8,
0xED38,
0xE0E6,
0xD4E1,
0xC946,
0xBE32,
0xB3C0,
0xAA0A,
0xA129,
0x9930,
0x9236,
0x8C4A,
0x877B,
0x83D6,
0x8163,
0x8027,
0x8027,
0x8163,
0x83D6,
0x877B,
0x8C4A,
0x9236,
0x9930,
0xA129,
0xAA0A,
0xB3C0,
0xBE32,
0xC946,
0xD4E1,
0xE0E6,
0xED38,
0xF9B8,
0x7FA7,
0x7E1E,
0x7B5D,
0x776C,
0x7255,
0x6C24,
0x64E9,
0x5CB4,
0x539B,
0x49B4,
0x3F17,
0x33DF,
0x2827,
0x1C0C,
0x0FAB,
0x0324,
0xF695,
0xEA1E,
0xDDDC,
0xD1EF,
0xC673,
0xBB85,
0xB140,
0xA7BD,
0x9F14,
0x9759,
0x90A1,
0x8AFB,
0x8676,
0x831C,
0x80F6,
0x800A,
0xF695,
0xEA1E,
0xDDDC,
0xD1EF,
0xC673,
0xBB85,
0xB140,
0xA7BD,
0x9F14,
0x9759,
0x90A1,
0x8AFB,
0x8676,
0x831C,
0x80F6,
0x800A,
0x8059,
0x81E2,
0x84A3,
0x8894,
0x8DAB,
0x93DC,
0x9B17,
0xA34C,
0xAC65,
0xB64C,
0xC0E9,
0xCC21,
0xD7D9,
0xE3F4,
0xF055,
0xFCDC};
0xFCDC,
0xF695,
0xF055,
0xEA1E,
0xE3F4,
0xDDDC,
0xD7D9,
0xD1EF,
0xCC21,
0xC673,
0xC0E9,
0xBB85,
0x7FEA,
0x7F87,
0x7ED6,
0x7DD6,
0x7C89,
0x7AEF,
0x790A,
0x76D9,
0x7460,
0x719E,
0x6E97,
0x6B4B,
0xFB4A,
0xF505,
0xEEC6,
0xE892,
0xE26D,
0xDC59,
0xD65C,
0xD079,
0xCAB2,
0xC50D,
0xBF8C,
0xBA33,
TwiddleCoeff_512
const unsigned TwiddleCoeff_512[512] = {
0x7FFF, 0x0000, 0x7FFE, 0xFE6E, 0x7FF6,
0x7FD9, 0xF9B8, 0x7FC2, 0xF827, 0x7FA7,
0x7F62, 0xF374, 0x7F38, 0xF1E4, 0x7F0A,
0x7E9D, 0xED38, 0x7E60, 0xEBAB, 0x7E1E,
0x7D8A, 0xE707, 0x7D3A, 0xE57D, 0x7CE4,
0x7C2A, 0xE0E6, 0x7BC6, 0xDF61, 0x7B5D,
0x7A7D, 0xDAD8, 0x7A06, 0xD958, 0x798A,
0x7885, 0xD4E1, 0x77FB, 0xD367, 0x776C,
0x7642, 0xCF04, 0x75A6, 0xCD92, 0x7505,
0x73B6, 0xC946, 0x7308, 0xC7DB, 0x7255,
0x70E3, 0xC3A9, 0x7023, 0xC248, 0x6F5F,
0x6DCA, 0xBE32, 0x6CF9, 0xBCDA, 0x6C24,
MikroElektronika
674
675
0xB8E3,
0xB3C0,
0xAECC,
0xAA0A,
0xA57E,
0xA129,
0x9D0E,
0x9930,
0x9592,
0x9236,
0x8F1D,
0x8C4A,
0x89BE,
0x877B,
0x8583,
0x83D6,
0x8276,
0x8163,
0x809E,
0x8027,
0x8000,
0x8027,
0x809E,
0x8163,
0x8276,
0x83D6,
0x8583,
0x877B,
0x89BE,
0x8C4A,
0x8F1D,
0x9236,
0x9592,
0x9930,
0x9D0E,
0xA129,
0xA57E,
0xAA0A,
0xAECC,
0xB3C0,
0xB8E3,
0xBE32,
0xC3A9,
0xC946,
0xCF04,
0xD4E1,
0xDAD8,
0xE0E6,
0xE707,
0xED38,
0xF374,
0xF9B8,
0x698C,
0x65DE,
0x61F1,
0x5DC8,
0x5964,
0x54CA,
0x4FFB,
0x4AFB,
0x45CD,
0x4074,
0x3AF3,
0x354E,
0x2F87,
0x29A4,
0x23A7,
0x1D93,
0x176E,
0x113A,
0x0AFB,
0x04B6,
0xFE6E,
0xF827,
0xF1E4,
0xEBAB,
0xE57D,
0xDF61,
0xD958,
0xD367,
0xCD92,
0xC7DB,
0xC248,
0xBCDA,
0xB796,
0xB27F,
0xAD97,
0xA8E2,
0xA463,
0xA01C,
0x9C11,
0x9843,
0x94B5,
0x9169,
0x8E62,
0x8BA0,
0x8927,
0x86F6,
0x8511,
0x8377,
0x822A,
0x812A,
0x8079,
0x8016,
0xB796,
0xB27F,
0xAD97,
0xA8E2,
0xA463,
0xA01C,
0x9C11,
0x9843,
0x94B5,
0x9169,
0x8E62,
0x8BA0,
0x8927,
0x86F6,
0x8511,
0x8377,
0x822A,
0x812A,
0x8079,
0x8016,
0x8002,
0x803E,
0x80C8,
0x81A0,
0x82C6,
0x843A,
0x85FA,
0x8805,
0x8A5A,
0x8CF8,
0x8FDD,
0x9307,
0x9674,
0x9A22,
0x9E0F,
0xA238,
0xA69C,
0xAB36,
0xB005,
0xB505,
0xBA33,
0xBF8C,
0xC50D,
0xCAB2,
0xD079,
0xD65C,
0xDC59,
0xE26D,
0xE892,
0xEEC6,
0xF505,
0xFB4A,
0x68A7,
0x64E9,
0x60EC,
0x5CB4,
0x5843,
0x539B,
0x4EC0,
0x49B4,
0x447B,
0x3F17,
0x398D,
0x33DF,
0x2E11,
0x2827,
0x2224,
0x1C0C,
0x15E2,
0x0FAB,
0x096B,
0x0324,
0xFCDC,
0xF695,
0xF055,
0xEA1E,
0xE3F4,
0xDDDC,
0xD7D9,
0xD1EF,
0xCC21,
0xC673,
0xC0E9,
0xBB85,
0xB64C,
0xB140,
0xAC65,
0xA7BD,
0xA34C,
0x9F14,
0x9B17,
0x9759,
0x93DC,
0x90A1,
0x8DAB,
0x8AFB,
0x8894,
0x8676,
0x84A3,
0x831C,
0x81E2,
0x80F6,
0x8059,
0x800A,
0xB64C,
0xB140,
0xAC65,
0xA7BD,
0xA34C,
0x9F14,
0x9B17,
0x9759,
0x93DC,
0x90A1,
0x8DAB,
0x8AFB,
0x8894,
0x8676,
0x84A3,
0x831C,
0x81E2,
0x80F6,
0x8059,
0x800A,
0x800A,
0x8059,
0x80F6,
0x81E2,
0x831C,
0x84A3,
0x8676,
0x8894,
0x8AFB,
0x8DAB,
0x90A1,
0x93DC,
0x9759,
0x9B17,
0x9F14,
0xA34C,
0xA7BD,
0xAC65,
0xB140,
0xB64C,
0xBB85,
0xC0E9,
0xC673,
0xCC21,
0xD1EF,
0xD7D9,
0xDDDC,
0xE3F4,
0xEA1E,
0xF055,
0xF695,
0xFCDC,
0x67BD,
0x63EF,
0x5FE4,
0x5B9D,
0x571E,
0x5269,
0x4D81,
0x486A,
0x4326,
0x3DB8,
0x3825,
0x326E,
0x2C99,
0x26A8,
0x209F,
0x1A83,
0x1455,
0x0E1C,
0x07D9,
0x0192,
0xFB4A,
0xF505,
0xEEC6,
0xE892,
0xE26D,
0xDC59,
0xD65C,
0xD079,
0xCAB2,
0xC50D,
0xBF8C,
0xBA33,
0xB505,
0xB005,
0xAB36,
0xA69C,
0xA238,
0x9E0F,
0x9A22,
0x9674,
0x9307,
0x8FDD,
0x8CF8,
0x8A5A,
0x8805,
0x85FA,
0x843A,
0x82C6,
0x81A0,
0x80C8,
0x803E,
0x8002,
0xB505,
0xB005,
0xAB36,
0xA69C,
0xA238,
0x9E0F,
0x9A22,
0x9674,
0x9307,
0x8FDD,
0x8CF8,
0x8A5A,
0x8805,
0x85FA,
0x843A,
0x82C6,
0x81A0,
0x80C8,
0x803E,
0x8002,
0x8016,
0x8079,
0x812A,
0x822A,
0x8377,
0x8511,
0x86F6,
0x8927,
0x8BA0,
0x8E62,
0x9169,
0x94B5,
0x9843,
0x9C11,
0xA01C,
0xA463,
0xA8E2,
0xAD97,
0xB27F,
0xB796,
0xBCDA,
0xC248,
0xC7DB,
0xCD92,
0xD367,
0xD958,
0xDF61,
0xE57D,
0xEBAB,
0xF1E4,
0xF827,
0xFE6E};
MikroElektronika
Library Routines
- BitReverseComplex
BitReverseComplex
Prototype
Nothing.
Requires
Nothing.
Example
Notes
MikroElektronika
676
Vectors Library
mikroC PRO for dsPIC30/33 and PIC24 includes a library for working and using vectors. All routines work with fractional
Q15 format.
Library Routines
- Vector_Set
- Vector_Power
- Vector_Subtract
- Vector_Scale
- Vector_Negate
- Vector_Multiply
- Vector_Min
- Vector_Max
- Vector_Dot
- Vector_Correlate
- Vector_Convolve
- Vector_Add
Vector_Set
Prototype
Description Sets size elements of input to value, starting from the first element.
Parameters - input: pointer to original vector
- size: number of vector elements
- value: value written to the elements
Returns
Nothing.
Requires
Nothing.
Example
Notes
677
MikroElektronika
Description Function returns result of power value (powVal) in radix point 1.15
Parameters - numElems: number elements in vector(s)
- srcV: pointer to source vector
Returns
Requires
Nothing.
Example
Notes
Vector_Subtract
Prototype
Returns
Nothing.
Requires
Nothing.
Example
Notes
MikroElektronika
678
Returns
Nothing.
Requires
Nothing.
Example
Notes
Vector_Negate
Prototype
void Vector_Negate(unsigned
numElems);
*srcVector,
unsigned
*DestVector,
unsigned
Nothing.
Requires
Nothing.
Example
unsigned vecDest[3];
unsigned vec1[3] = {1,2,3};
Vector_Negate(vec1, vecDest, 3);
Notes
679
MikroElektronika
Returns
Nothing.
Requires
Nothing.
Example
Notes
Vector_Min
Prototype
unsigned
Vector_Min(unsigned
*MinIndex);
*Vector,
unsigned
numElems,
unsigned
Requires
Nothing.
Example
Notes
MikroElektronika
680
unsigned
Vector_Max(unsigned
*MaxIndex);
*srcV,
unsigned
numElems,
unsigned
Requires
Nothing.
Example
Notes
Vector_Dot
Prototype
Requires
Nothing.
Example
Notes
681
MikroElektronika
where:
x[n] defined for n [0, N)
y[n] defined for n [0, M), M N
r[n] defined for n [0, N+M-1)
Parameters -
Returns
Nothing.
Requires
Nothing.
Example
unsigned vConDest[10];
unsigned vec2[3] = {1,1,1};
Vector_Correlate(vec2,vec2,vConDest,3,3);
Notes
MikroElektronika
682
Returns
Nothing.
Requires
Nothing.
Example
Notes
683
MikroElektronika
void Vector_Add(unsigned
numElems);
*dest,
unsigned
*v1,
unsigned
*v2,
unsigned
Returns
Nothing.
Requires
Nothing.
Example
Notes
MikroElektronika
684
Matrices Library
mikroC PRO for dsPIC30/33 and PIC24 includes a library for operating and working with matrices. All routines work
with fractional Q15 format.
Library Routines
Matrix_Transpose
Matrix_Subtract
Matrix_Scale
Matrix_Multiply
Matrix_Add
Matrix_Transpose
Prototype
void Matrix_Transpose(unsigned
unsigned numCols);
*src,
unsigned
*dest,
unsigned
numRows,
Returns
Nothing.
Requires
Nothing.
Example
Notes
685
MikroElektronika
Returns
Nothing.
Requires
Nothing.
Example
Notes
Matrix_Scale
Prototype
unsigned
*src1,
unsigned
*dest,
Returns
Nothing.
Requires
Nothing.
Example
Notes
MikroElektronika
686
with:
i [0, numRows1-1]
j [0, numCols2-1]
k [0, numCols1Rows2-1]
Parameters
-
Returns
Nothing.
Requires
Nothing.
Example
Notes
687
MikroElektronika
Returns
Nothing.
Requires
Nothing.
Example
Notes
- [W0..W4] used, not restored
- AccuA used, not restored.
- CORCON saved, used, restored.
- numRows1*numCols2 < 214
MikroElektronika
688
Library Functions
- isalnum
- isalpha
- iscntrl
- isdigit
- isgraph
- islower
- ispunct
- isspace
- isupper
- isxdigit
- toupper
- tolower
689
MikroElektronika
Description Function returns 1 if the character is alphanumeric (A-Z, a-z, 0-9), otherwise returns zero.
Example
res = isalnum(o);
res = isalnum(\r);
// returns 1
// returns 0
isalpha
Prototype
Description Function returns 1 if the character is alphabetic (A-Z, a-z), otherwise returns zero.
Example
res = isalpha(A);
res = isalpha(1);
// returns 1
// returns 0
iscntrl
Prototype
Description Function returns 1 if the character is a control or delete character(decimal 0-31 and 127), otherwise
returns zero.
Example
res = iscntrl(\r);
res = iscntrl(o);
// returns 1
// returns 0
isdigit
Prototype
Description Function returns 1 if the character is a digit (0-9), otherwise returns zero.
Example
res = isdigit(o);
res = isdigit(1);
MikroElektronika
// returns 1
// returns 0
690
Description Function returns 1 if the character is a printable, excluding the space (decimal 32), otherwise
returns zero.
Example
res = isgraph(o);
res = isgraph( );
// returns 1
// returns 0
islower
Prototype
Description Function returns 1 if the character is a lowercase letter (a-z), otherwise returns zero.
Example
res = islower(0);
res = islower(A);
// returns 1
// returns 0
ispunct
Prototype
Description Function returns 1 if the character is a punctuation (decimal 32-47, 58-63, 91-96, 123-126),
otherwise returns zero.
Example
res = ispunct(.);
res = ispunct(1);
// returns 1
// returns 0
isspace
Prototype
Description Function returns 1 if the character is a white space (space, tab, CR, HT, VT, NL, FF), otherwise
returns zero.
Example
691
res = isspace( );
res = isspace(1);
// returns 1
// returns 0
MikroElektronika
Description Function returns 1 if the character is an uppercase letter (A-Z), otherwise returns zero.
Example
res = isupper(A);
res = isupper(a);
// returns 1
// returns 0
isxdigit
Prototype
Description Function returns 1 if the character is a hex digit (0-9, A-F, a-f), otherwise returns zero.
Example
res = isxdigit(A);
res = isxdigit(P);
// returns 1
// returns 0
toupper
Prototype
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);
res = toupper(B);
// returns A
// returns B
tolower
Prototype
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);
res = tolower(b);
MikroElektronika
// returns a
// returns b
692
Library Functions
- acos
- asin
- atan
- atan2
- ceil
- cos
- cosh
- exp
-fabs
- floor
- frexp
- ldexp
- log
- log10
- modf
- pow
- sin
- sinh
- sqrt
- tan
acos
Prototype
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
693
doub = acos(0.5);
// doub = 1.047198
MikroElektronika
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
doub = asin(0.5);
// doub = 5.235987e-1
atan
Prototype
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
doub = atan(1.0);
// doub = 7.853982e-1
atan2
Prototype
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
// doub = 4.636475e-1
ceil
Prototype
Description Function returns value of parameter x rounded up to the next whole number.
Example
doub = ceil(0.5);
MikroElektronika
// doub = 1.000000
694
Description Function returns the cosine of f in radians. The return value is from -1 to 1.
Example
doub = cos(PI/3.);
// doub = 0.500008
cosh
Prototype
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
doub = cosh(PI/3.);
// doub = 1.600286
exp
Prototype
Description Function returns the value of e the base of natural logarithms raised to the power x (i.e. ex).
Example
doub = exp(0.5);
// doub = 1.648721
fabs
Prototype
doub = fabs(-1.3);
// doub = 1.3
floor
Prototype
Description Function returns the value of parameter x rounded down to the nearest integer.
Example
695
doub = floor(15.258);
// doub = 15.000000
MikroElektronika
Description Function splits a floating-point value into a normalized fraction and an integral power of 2. The return
value is the normalized fraction and the integer exponent is stored in the object pointed to by eptr.
ldexp
Prototype
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
// doub = 10
log
Prototype
doub = log(10);
// doub = 2.302585E
log10
Prototype
doub = log10(100.);
MikroElektronika
// doub = 2.000000
696
Description Function returns the signed fractional component of val, placing its whole number component into the
variable pointed to by iptr.
Example
pow
Prototype
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
doub = pow(10.,5.);
// doub = 9.999984e+4
sin
Prototype
Description Function returns the sine of f in radians. The return value is from -1 to 1.
Example
doub = sin(PI/2.);
// doub = 1.000000
sinh
Prototype
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
697
doub = sinh(PI/2.);
// doub = 2.301296
MikroElektronika
doub = sqrt(10000.);
// doub = 100.0000
tan
Prototype
Description Function returns the tangent of x in radians. The return value spans the allowed range of floating point
in the mikroC PRO for dsPIC30/33 and PIC24.
Example
doub = tan(PI/4.);
// doub = 0.999998
tanh
Prototype
doub = tanh(-PI/4.);
MikroElektronika
// doub = -0.655793
698
Library Functions
- abs
- atof
- atoi
- atol
- div
- ldiv
- uldiv
- labs
- max
- min
- rand
- srand
- xtoi
abs
Prototype
699
result = abs(-12);
// result = 12
MikroElektronika
Description Function converts the input string s into a double precision value and returns the value. Input string
s should conform to the floating point literal format, with an optional whitespace at the beginning. The
string will be processed one character at a time, until the function reaches a character which it doesnt
recognize (including a null character).
Example
doub = atof(-1.23);
// doub = -1.23
atoi
Prototype
Description Function converts the input string s into an integer value and returns the value. The input string s
should consist exclusively of decimal digits, with an optional whitespace and a sign at the beginning.
The string will be processed one character at a time, until the function reaches a character which it
doesnt recognize (including a null character).
Example
result = atoi(32000);
// result = 32000
atol
Prototype
Description Function converts the input string s into a long integer value and returns the value. The input string s
should consist exclusively of decimal digits, with an optional whitespace and a sign at the beginning.
The string will be processed one character at a time, until the function reaches a character which it
doesnt recognize (including a null character).
Example
result = atol(-32560);
// result = -32560
div
Prototype
Description Function computes the result of division of the numerator number by the denominator denom; the
function returns a structure of type div_t comprising quotient (quot) and remainder (rem), see Div
Structures.
Example
dt = div(1234,100);
MikroElektronika
700
Description Function is similar to the div function, except that the arguments and result structure members all have
type long.
Function computes the result of division of the numerator number by the denominator denom; the
function returns a structure of type ldiv_t comprising quotient (quot) and remainder (rem), see Div
Structures.
Example
dl = ldiv(-123456, 1000);
uldiv
Prototype
Description Function is similar to the div function, except that the arguments and result structure members all have
type unsigned long.
Function computes the result of division of the numerator number by the denominator denom; the
function returns a structure of type uldiv_t comprising quotient (quot) and remainder (rem), see
Div Structures.
Example
dul = uldiv(123456,1000);
labs
Prototype
Description Function returns the absolute (i.e. positive) value of long integer x.
Example
result = labs(-2147483647);
max
Prototype
701
result = max(123,67);
MikroElektronika
result = min(123,67);
// function returns 67
rand
Prototype
int rand();
Description Function returns a sequence of pseudo-random numbers between 0 and 32767. The function will
always produce the same sequence of numbers unless srand is called to seed the start point.
Example
while(1)
result = rand()
;
srand
Prototype
Description Function uses x as a starting point for a new sequence of pseudo-random numbers to be returned by
subsequent calls to rand. No values are returned by this function.
Example
srand(9);
xtoi
Prototype
Description Function converts the input string s consisting of hexadecimal digits into an integer value. The input
parameter s should consist exclusively of hexadecimal digits, with an optional whitespace and a sign
at the beginning. The string will be processed one character at a time, until the function reaches a
character which it doesnt recognize (including a null character).
Example
result = xtoi(1FF);
MikroElektronika
// result = 511
702
703
MikroElektronika
Library Functions
- memchr
- memcmp
- memcpy
- memmove
- memset
- strcat
- strchr
- strcmp
- strcpy
- strlen
- strncat
- strncpy
- strspn
- strncmp
- strstr
- strcspn
- strpbrk
- strrchr
- strtok
memchr
Prototype
Description Function locates the first occurrence of char n in the initial v bytes of memory area starting at the
address p. The function returns the pointer to this location or 0 if the n was not found.
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
MikroElektronika
704
Description Function compares the first n characters of objects pointed to by s1 and s2 and returns zero if
the objects are equal, or returns a difference between the first differing characters (in a left-to-right
evaluation). Accordingly, the result is greater than zero if the object pointed to by s1 is greater than the
object pointed to by s2 and vice versa.
Example
memcpy
Prototype
Description Function copies n characters from the object pointed to by s1 into the object pointed to by d1. If
copying takes place between objects that overlap, the behavior is undefined. The function returns
address of the object pointed to by d1.
Example
memmove
Prototype
Description Function copies n characters from the object pointed to by from into the object pointed to by to. Unlike
memcpy, the memory areas to and from may overlap. The function returns address of the object
pointed to by to.
Example
705
MikroElektronika
Description Function copies the value of the character into each of the first n characters of the object pointed
by p1. The function returns address of the object pointed to by p1.
Example
strcat
Prototype
Description Function appends a copy of the string from to the string to, overwriting the null character at the end
of to. Then, a terminating null character is added to the result. If copying takes place between objects
that overlap, the behavior is undefined. to string must have enough space to store the result. The
function returns address of the object pointed to by to.
Example
strchr
Prototype
Description Function locates the first occurrence of character chr in the string ptr. The function returns a pointer
to the first occurrence of character chr, or a null pointer if chr does not occur in ptr. The terminating
null character is considered to be a part of the string.
Example
MikroElektronika
706
Description Function compares strings s1 and s2 and returns zero if the strings are equal, or returns a difference
between the first differing characters (in a left-to-right evaluation). Accordingly, the result is greater
than zero if s1 is greater than s2 and vice versa.
Example
strcpy
Prototype
Description Function copies the string from into the string to. If copying is successful, the function returns to. If
copying takes place between objects that overlap, the behavior is undefined.
Example
strlen
Prototype
Description Function returns the length of the string s (the terminating null character does not count against
strings length).
Example
707
MikroElektronika
Description Function appends not more than size characters from the string from to to. The initial character of
from overwrites the null character at the end of to. The terminating null character is always appended
to the result. The function returns to.
Example
strncpy
Prototype
Description Function copies not more than size characters from string from to to. If copying takes place
between objects that overlap, the behavior is undefined. If from is shorter than size characters,
then to will be padded out with null characters to make up the difference. The function returns the
resulting string to.
Example
strspn
Prototype
Description Function returns the length of the maximum initial segment of str1 which consists entirely of characters
from str2. The terminating null character at the end of the string is not compared.
Example
MikroElektronika
// routne returns 4
708
Description Function lexicographically compares not more than len characters (characters that follow the null
character are not compared) from the string pointed by s1 to the string pointed by s2. The function
returns a value indicating the s1 and s2 relationship:
Value
< 0
= 0
> 0
Example
Meaning
s1 less than s2
s1 equal to s2
s1 greater than s2
strstr
Prototype
Description Function locates the first occurrence of the string s2 in the string s1 (excluding the terminating null
character).
The function returns pointer to first occurrence of s2 in s1; if no string was found, function returns 0.
If s2 is a null string, the function returns 0.
Example
709
MikroElektronika
Description Function computes the length of the maximum initial segment of the string pointed to by s1 that
consists entirely of characters that are not in the string pointed to by s2.
The function returns the length of the initial segment.
Example
strpbrk
Prototype
Description Function searches s1 for the first occurrence of any character from the string s2. The terminating null
character is not included in the search. The function returns pointer to the matching character in s1. If
s1 contains no characters from s2, the function returns 0.
Example
strrchr
Prototype
Description Function searches the string ptr for the last occurrence of character chr. The null character
terminating ptr is not included in the search. The function returns pointer to the last chr found in
ptr; if no matching character was found, function returns 0.
Example
MikroElektronika
710
Returns
The strtok function returns a pointer to the first character of a token, or a null pointer if there is no
token.
Description A sequence of calls to the strtok function breaks the string pointed to by s1 into a sequence of tokens,
each of which is delimited by a character from the string pointed to by s2. The first call in the sequence
has s1 as its first argument, and is followed by calls with a null pointer as their first argument. The
separator string pointed to by s2 may be different from call to call.
The first call in the sequence searches the string pointed to by s1 for the first character that is not
contained in the current separator string pointed to by s2. If no such character is found, then there are
no tokens in the string pointed to by s1 and the strtok function returns a null pointer. If such character
is found, it is the start of the first token.
The strtok function then searches from there for a character that is contained in the current separator
string. If no such character is found, the current token extends to the end of the string pointed to by
s1, and subsequent searches for a token will return a null pointer. If such a character is found, it is
overwritten by a null character, which terminates the current token. The strtok function saves a pointer
to the following character, from which the next search for a token will start.
Each subsequent call, with a null pointer as the value of the first argument, starts searching from the
saved pointer and behaves as described above.
Example
char x[10] ;
void main(){
strcpy(x, strtok(mikroEl, Ek));
strcpy(x, strtok(0, kE));
}
711
MikroElektronika
Miscellaneous Libraries
- Button Library
- Conversions Library
- PrintOut Library
- Setjmp Library
- Sprint Library
- Time 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
strrchr
Prototype
unsigned int Button(unsigned int *port, unsigned int pin, unsigned int time,
unsigned int active_state);
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
if (Button(&PORTD, 0, 1, 1))
PORTB = 0xFF;
...
Notes
None.
MikroElektronika
712
do {
if (Button(&PORTD, 0, 1, 1))
// detect logical one state
oldstate = 1;
if (oldstate && Button(&PORTD, 0, 1, 0)) { // detect logical one to logical zero
transition
LATB = ~LATB;
// toggle portb
oldstate = 0;
}
} while(1);
}
713
MikroElektronika
Conversions Library
The mikroC PRO for dsPIC30/33 and PIC24 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
- LongToStr
- LongWordToStr
- FloatToStr
- WordToStrWithZeros
- IntToStrWithZeros
- LongWordToStrWithZeros
- LongIntToStrWithZeros
- ByteToHex
- ShortToHex
- WordToHex
- IntToHex
- LongWordToHex
- LongIntToHex
- Rtrim
- Ltrim
The following functions convert decimal values to BCD and vice versa:
- Bcd2Dec
- Dec2Bcd
- Bcd2Dec16
- Dec2Bcd16
MikroElektronika
714
Description Converts input byte to a string. The output string has fixed width of 4 characters including null character
at the end (string termination). 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
Example
Notes
None.
ShortToStr
Prototype
Description Converts input signed short number to a string. The output string has fixed width of 5 characters
including null character at the end (string termination). 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
Example
short t = -24;
char txt[5];
...
ShortToStr(t, txt);
Notes
715
None.
MikroElektronika
Description Converts input word to a string. The output string has fixed width of 6 characters including null character
at the end (string termination). 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
Example
unsigned t = 437;
char txt[6];
...
WordToStr(t, txt);
Notes
// txt is
None.
IntToStr
Prototype
Description Converts input signed integer number to a string. The output string has fixed width of 7 characters
including null character at the end (string termination). The output string is right justified and the
remaining positions on the left (if any) are filled with blanks.
Parameters
- input: signed integer number to be converted
- output: destination string
Returns
Nothing.
Requires
Example
int j = -4220;
char txt[7];
...
IntToStr(j, txt);
Notes
None.
MikroElektronika
716
Description Converts input signed long integer number to a string. The output string has fixed width of 12 characters
including null character at the end (string termination). 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.
Requires
Example
long jj = -3700000;
char txt[12];
...
LongToStr(jj, txt);
// txt is
-3700000 (three blanks here)
Notes
None.
LongWordToStr
Prototype
Description Converts input unsigned long integer number to a string. The output string has fixed width of 11
characters including null character at the end (string termination). 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.
Requires
Example
Notes
None.
717
MikroElektronika
Example
float ff1 = -374.2;
float ff2 = 123.456789;
float ff3 = 0.000001234;
char txt[15];
...
FloatToStr(ff1, txt); // txt is -374.2
FloatToStr(ff2, txt); // txt is 123.4567
FloatToStr(ff3, txt); // txt is 1.234e-6
Notes
Given floating point number will be truncated to 7 most significant digits before conversion.
MikroElektronika
718
Description Converts input word to a string. The output string has fixed width of 6 characters including null character
at the end (string termination).
The output string is right justified and remaining positions on the left (if any) are filled with zeros.
Parameters
- input: unsigned integer to be converted
- output: destination string
Returns
Nothing.
Requires
Example
Notes
None.
IntToStrWithZeros
Prototype
Description Converts input integer to a string. The output string has fixed width of 7 characters including null
character at the end (string termination).
The output string is right justified and remaining positions on the left (if any) are filled with zeros.
Parameters
- input: integer number to be converted
- output: destination string
Returns
Nothing.
Requires
Example
short t = -3276;
char txt[7];
...
IntToStrWithZeros(t, txt);
Notes
719
None.
MikroElektronika
Description Converts input longword to a string. The output string has fixed width of 11 characters including null
character at the end (string termination).
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
Example
unsigned t = 12345678;
char txt[11];
...
LongWordToStrWithZeros(t, txt);
Notes
None.
LongIntToStrWithZeros
Prototype
Description Converts input signed long integer number to a string. The output string has fixed width of 12 characters
including null character at the end (string termination).
The output string is right justified and the remaining positions on the left (if any) are filled with zeros.
Parameters
- input: signed long number to be converted
- output: destination string
Returns
Nothing.
Requires
Example
int j = -12345678;
char txt[12];
...
LongIntToStrWithZeros(j, txt);
Notes
None.
MikroElektronika
720
Description Converts input number to a string containing the numbers hexadecimal representation. The output
string has fixed width of 3 characters including null character at the end (string termination).
Parameters
- input: byte to be converted
- output: destination string
Returns
Nothing.
Requires
Example
unsigned short t = 2;
char txt[3];
...
ByteToHex(t, txt); // txt is 02
Notes
None.
ShortToHex
Prototype
Description Converts input number to a string containing the numbers hexadecimal representation. The output
string has fixed width of 3 characters including null character at the end (string termination).
Parameters
- input: signed short number to be converted
- output: destination string
Returns
Nothing.
Requires
Example
short t = -100;
char txt[3];
...
ShortToHex(t, txt);
Notes
721
// txt is 9C
None.
MikroElektronika
Description Converts input number to a string containing the numbers hexadecimal representation. The output
string has fixed width of 5 characters including null character at the end (string termination).
Parameters
- input: unsigned integer to be converted
- output: destination string
Returns
Nothing.
Requires
Example
unsigned t = 1111;
char txt[5];
...
WordToHex(t, txt);
Notes
// txt is 0457
None.
IntToHex
Prototype
Description Converts input number to a string containing the numbers hexadecimal representation. The output
string has fixed width of 5 characters including null character at the end (string termination).
Parameters
- input: signed integer number to be converted
- output: destination string
Returns
Nothing.
Requires
Example
int j = -32768;
char txt[5];
...
IntToHex(j, txt);
Notes
// txt is 8000
None.
MikroElektronika
722
Description Converts input number to a string containing the numbers hexadecimal representation. The output
string has fixed width of 9 characters including null character at the end (string termination).
Parameters
- input: unsigned long integer number to be converted
- output: destination string
Returns
Nothing.
Requires
Example
Notes
None.
LongIntToHex
Prototype
Description Converts input number to a string containing the numbers hexadecimal representation. The output
string has fixed width of 9 characters including null character at the end (string termination).
Parameters
- input: signed long integer number to be converted
- output: destination string
Returns
Nothing.
Requires
Example
Notes
None.
723
MikroElektronika
Description Converts input unsigned short integer number to its appropriate BCD representation.
Parameters
- decnum: unsigned short integer number to be converted
Returns
Requires
Nothing.
Example
unsigned short a, b;
...
a = 22;
b = Dec2Bcd(a);
// b equals 34
Notes
None.
Bcd2Dec
Prototype
Requires
Nothing.
Example
unsigned short a, b;
...
a = 34;
b = Bcd2Dec(22);
// b equals 22
Notes
None.
MikroElektronika
724
Requires
Nothing.
Example
unsigned a, b;
...
a = 2345;
b = Dec2Bcd16(a);
Notes
// b equals 9029
None.
Bcd2Dec16
Prototype
Requires
Nothing.
Example
unsigned a, b;
...
a = 0x1234;
b = Bcd2Dec16(a);
Notes
725
// a equals 4660
// b equals 1234
None.
MikroElektronika
Description Trims the trailing spaces from array given with *string
Parameters
- string: array to be trimmed.
Returns
Requires
Nothing.
Example
char *res;
res = Rtrim(
mikroe);
// trims the trailing spaces and returns the
address of the first non-space character
Notes
None.
Ltrim
Prototype
Description 66
Trims the leading spaces from array given with *string
Parameters
- string: array to be trimmed.
Returns
Requires
Nothing.
Example
char *res;
res = Ltrim( mikroe); // trims the leading spaces and returns the address
of the first non-space character
Notes
None.
MikroElektronika
726
PrintOut Library
The mikroC PRO for dsPIC30/33 and PIC24 provides the PrintOut routine for easy data formatting and printing.
Library Routines
-PrintOut
PrintOut
Prototype
Description PrintOut is used to format data and print them in a way defined by the user through a print handler
function.
Parameters
- prntoutfunc: print handler function
- f: format string
The f argument is a format string and may be composed of characters, escape sequences, and
format specifications. Ordinary characters and escape sequences are copied to the print handler in
order in which they are interpreted. Format specifications always begin with a percent sign (%) and
require additional arguments to be included in the function call.
The format string is read from left to right. The first format specification encountered refers to the
first argument after the f parameter and then converts and outputs it using the format specification.
The second format specification accesses the second argument after f, and so on. If there are more
arguments than format specifications, the extra arguments are ignored. Results are unpredictable
if there are not enough arguments for the format specifications. The format specifications have the
following format:
% [flags] [width] [.precision]
[{ l | L }]
conversion_type
Each field in the format specification can be a single character or a number which specifies a particular
format option. The conversion_type field is where a single character specifies that an argument is
interpreted as a character, string, number, or pointer, as shown in the following table:
727
MikroElektronika
conversion_type
Argument Type
int
unsigned int
unsigned int
unsigned int
Unsigned
hexadecimal
0123456789abcdef
number
using
unsigned int
Unsigned
hexadecimal
0123456789ABCEDF
number
using
double
double
double
double
int
char *
void *
<none>
Output Format
The flags field is where a single character is used to justify the output and to print +/- signs and blanks,
decimal points, and octal and hexadecimal prefixes, as shown in the following table.
flags
Meaning
Prefix the output value with + or - sign if the output is a signed type.
s p a c e Prefix the output value with a blank if it is a signed positive value. Otherwise, no blank is
( ) prefixed.
#
Prefix a non-zero output value with 0, 0x, or 0X when used with o, x, and X field types,
respectively. When used with the e, E, f, g, and G field types, the # flag forces the
output value to include a decimal point. In any other case the # flag is ignored.
The width field is a non-negative number that specifies a minimum number of printed characters. If a
number of characters in the output value is less than width, blanks are added on the left or right (when
the - flag is specified) in order to pad to the minimum width. If the width is prefixed with 0, then zeros
are padded instead of blanks. The width field never truncates a field. If the length of the output value
exceeds the specified width, all characters are output.
MikroElektronika
728
d, u, o, x, X The precision field is where you specify the minimum number of digits that will
be included in the output value. Digits are not truncated if the number of digits
in an argument exceeds that defined in the precision field. If the number of
digits in the argument is less than the precision field, the output value is padded
on the left with zeros.
f
The precision field is where you specify the number of digits to the right of the
decimal point. The last digit is rounded.
e, E
The precision field is where you specify the number of digits to the right of the
decimal point. The last digit is rounded.
The precision field is where you specify the maximum number of significant
digits in the output value.
c, C
The precision field is where you specify the maximum number of characters in
the output value. Excess characters are not output.
Nothing.
Requires
Nothing.
Example
729
MikroElektronika
PrintOut(PrintHandler, /*\r\n
* Project name:\r\n
20060710:\r\n
- Initial release\r\n
* Description:\r\n
MCU:
PIC30F4013\r\n
Dev.Board:
EasydsPIC4A\r\n
Oscillator:
HS, %10.3fMHz\r\n
Ext. Modules:
None.\r\n
SW:
mikroC PRO for dsPIC30/33
and PIC24\r\n
* NOTES:\r\n
None.\r\n
*/\r\n, Get_Fosc_kHz()/1000.);
}
Notes
None.
MikroElektronika
730
Setjmp Library
The Setjmp library contains functions and types definitions for bypassing the normal function call and return
discipline.
jmp_buf is an array of unsigned int type suitable for holding information needed to restore a calling environment. Type
declaration is contained in the sejmp.h header file which can be found in the include folder of the compiler.
Library Routines
- Setjmp
- Longjmp
Setjmp
Prototype
Description This function saves calling position for a later use by Longjmp.
Parameters
- env: buffer suitable for holding information needed for restoring calling environment
Returns
- 0 if the return is from direct invocation
- nonzero value if the return is from a call to Longjmp (this value will be set by the Longjmp
routine)
Requires
Nothing.
Example
jmp_buf buf;
...
Setjmp(buf);
Notes
None.
731
MikroElektronika
Description Restores calling environment saved in 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
Returns
Nothing.
Requires
Invocation of Longjmp must occur before return from the function in which Setjmp was called
encounters.
Example
jmp_buf buf;
...
Longjmp(buf, 2);
Notes
None.
Library Example
This example demonstrates function cross calling using the Setjmp and Longjmp functions. When called, Setjmp
saves its calling environment in its jmp_buf argument for a later use by Longjmp. Longjmp, on the other hand,
restores the environment saved by the most recent invocation of Setjmp with the corresponding jmp_buf argument.
MikroElektronika
732
void func33(){
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
Delay_ms(1000);
asm nop;
Longjmp(buf, 2);
asm nop;
}
void func(){
portb = 3;
if (Setjmp(buf) == 2)
portb = 1;
else
func33();
}
void main() {
PORTB = 0;
TRISB = 0;
asm nop;
func();
asm nop;
Delay_ms(1000);
PORTB = 0xFFFF;
2<------------|
|
|
|
|
3---------------->|
|
|
|
|
|
|
|
|
1<--------|
|
|
|
|
|
|
|
|
3<----------------|
4-->|
|
|
|
|
|
2------------>|
|
|
4<--|
|
5----->| |
| |
| |
| |
| |
| |
| |
| |
| |
1-------->|
|
5<-----|
733
MikroElektronika
Sprint Library
The mikroC PRO for dsPIC30/33 and PIC24 provides the standard ANSI C Sprintf function for easy data formatting.
Note: In addition to ANSI C standard, the Sprint Library also includes two limited versions of the sprintf function
(sprinti and sprintl)
These functions take less ROM and RAM and may be more convenient for use in some cases.
Functions
- sprintf
- sprintl
- sprinti
sprintf
Prototype
Returns
The function returns the number of characters actually written to destination string.
Description
sprintf is used to format data and print them into destination string.
Parameters:
- wh: destination string
- f: format string
The f argument is a format string and may be composed of characters, escape sequences, and
format specifications. Ordinary characters and escape sequences are copied to the destination string
in the order in which they are interpreted. Format specifications always begin with a percent sign (%)
and require additional arguments to be included in the function call.
The format string is read from left to right. The first format specification encountered refers to the
first argument after f and then converts and outputs it using the format specification. The second
format specification accesses the second argument after f, and so on. If there are more arguments
than format specifications, then these extra arguments are ignored. Results are unpredictable if there
are not enough arguments for the format specifications. The format specifications have the following
format:
% [flags] [width] [.precision] [{ l | L }] conversion_type
Each field in the format specification can be a single character or a number which specifies a particular
format option. The conversion_type field is where a single character specifies that the argument is
interpreted as a character, string, number, or pointer, as shown in the following table:
MikroElektronika
734
conversion_type
Argument Type
int
unsigned int
unsigned int
unsigned int
Unsigned
hexadecimal
0123456789abcdef
number
using
unsigned int
Unsigned
hexadecimal
0123456789ABCEDF
number
using
double
double
double
double
int
char *
void *
<none>
Output Format
The flags field is where a single character is used to justify the output and to print +/- signs and blanks,
decimal points, and octal and hexadecimal prefixes, as shown in the following table.
flags
Meaning
Prefix the output value with + or - sign if the output is a signed type.
s p a c e Prefix the output value with a blank if it is a signed positive value. Otherwise, no blank is
( ) prefixed.
#
Prefix a non-zero output value with 0, 0x, or 0X when used with o, x, and X field types,
respectively. When used with the e, E, f, g, and G field types, the # flag forces the
output value to include a decimal point. In any other case the # flag is ignored.
The width field is a non-negative number that specifies the minimum number of printed characters.
If a number of characters in the output value is less than width, then blanks are added on the left or
right (when the - flag is specified) to pad to the minimum width. If width is prefixed with 0, then zeros
are padded instead of blanks. The width field never truncates a field. If a length of the output value
exceeds the specified width, all characters are output.
735
MikroElektronika
d, u, o, x, X The precision field is where you specify the minimum number of digits that will
be included in the output value. Digits are not truncated if the number of digits
in an argument exceeds that defined in the precision field. If the number of
digits in the argument is less than the precision field, the output value is padded
on the left with zeros.
f
The precision field is where you specify the number of digits to the right of the
decimal point. The last digit is rounded.
e, E
The precision field is where you specify the number of digits to the right of the
decimal point. The last digit is rounded.
The precision field is where you specify the maximum number of significant
digits in the output value.
c, C
The precision field is where you specify the maximum number of characters in
the output value. Excess characters are not output.
sprintl
Prototype
Returns
The function returns the number of characters actually written to destination string.
Description
sprinti
Prototype
Returns
The function returns the number of characters actually written to destination string.
Description
The same as sprintf, except it doesnt support long integers and float-type numbers.
MikroElektronika
736
737
MikroElektronika
Time Library
The Time Library contains functions and type definitions for time calculations in the UNIX time format which counts the
number of seconds since the epoch. This is very convenient for programs that work with time intervals: the difference
between two UNIX time values is a real-time difference measured in seconds.
What is the epoch?
Originally it was defined as the beginning of 1970 GMT. (January 1, 1970 Julian day) GMT, Greenwich Mean Time, is
a traditional term for the time zone in England.
The TimeStruct type is a structure type suitable for time and date storage. Type declaration is contained in __Time.h
which can be found in the mikroC PRO for dsPIC30/33 and PIC24 Time Library Demo example folder.
Library Routines
- Time_dateToEpoch
- Time_epochToDate
- Time_dateDiff
Time_dateToEpoch
Prototype
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
Requires
Nothing.
Example
#include
__Time.h
...
TimeStruct
ts1;
long
epoch ;
...
//what is the epoch of the date in ts ?
epoch = Time_dateToEpoch(&ts1) ;
Notes
None.
MikroElektronika
738
Nothing.
Requires
Nothing.
Example
#include
__Time.h
...
TimeStruct
ts2;
long
epoch ;
...
//what date is epoch 1234567890 ?
epoch = 1234567890 ;
Time_epochToDate(epoch, &ts2) ;
Notes
None.
739
MikroElektronika
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
Requires
Nothing.
Example
#include
__Time.h
...
TimeStruct
ts1, ts2;
long
diff ;
...
// how many seconds between these two dates contained in ts1 and ts2
buffers?
diff = Time_dateDiff(&ts1, &ts2) ;
Notes
None.
MikroElektronika
740
__Time.h
=
=
=
=
=
=
0;
7;
17;
23;
5;
2006;
/*
* What is the epoch of the date in ts ?
*/
epoch = Time_dateToEpoch(&ts1);
//
/*
* What date is epoch 1234567890 ?
*/
epoch = 1234567890;
Time_epochToDate(epoch, &ts2);
//
1148404020
/*
* How much seconds between this two dates?
*/
diff = Time_dateDiff(&ts1, &ts2);
// 86163870
}
741
MikroElektronika
Trigonometry Library
The mikroC PRO for dsPIC30/33 and PIC24 implements fundamental trigonometry functions. These functions are
implemented as look-up tables. Trigonometry functions are implemented in integer format in order to save memory.
Library Routines
- sinE3
- cosE3
sinE3
Prototype
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
Requires
Nothing.
Example
int res;
...
res = sinE3(45);
Notes
// result is 707
MikroElektronika
742
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
Requires
Nothing.
Example
int res;
...
res = cosE3(196);
Notes
743
// result is -193
MikroElektronika
CHAPTER 10
Tutorials
Managing Project
Projects
The mikroC PRO for dsPIC30/33 and PIC24 organizes applications into projects, consisting of a single project file
(extension .mcpds) and one or more source files (extension .c). mikroC PRO for dsPIC30/33 and PIC24 IDE allows
you to manage multiple projects (see Project Manager). Source files can be compiled only if they are part of a project.
The project file contains the following information:
- project name and optional description,
- target device,
- device flags (config word),
- device clock,
- list of the project source files with paths,
- header files (*.h),
- binary files (*.mcl),
- image files,
- other files.
Note that the project does not include files in the same way as preprocessor does, see Add/Remove Files from
Project.
MikroElektronika
744
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
Step One - Select the device from the device drop-down list:
745
MikroElektronika
Step Three - Specify the location where your project will be saved:
MikroElektronika
746
747
MikroElektronika
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
MikroElektronika
748
749
MikroElektronika
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
750
751
MikroElektronika
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
752
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
keyboard.
753
MikroElektronika
The list of relevant files is stored in the project file (extension .mcpds).
To add a file to the project, click the Add File to Project Icon
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
keyboard.
MikroElektronika
754
755
MikroElektronika
Source Files
Source files containing source code should have the extension .c. The list of source files relevant to the application
is stored in project file with extension .mcpds, along with other project information. You can compile source files only
if they are part of the project.
Use the preprocessor directive #include to include header files with the extension .h. Do not rely on the preprocessor
to include source files other than headers see Add/Remove Files from Project for more information.
If you use the New Project Wizard, an empty source file, named after the project with extension .c, will be created
automatically. The mikroC PRO for dsPIC30/33 and PIC24 does not require you to have a source file named the same
as the project, its just a matter of convenience.
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
Toolbar.
MikroElektronika
756
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:
757
MikroElektronika
Description
Add Search Path.
MikroElektronika
758
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.
759
MikroElektronika
Source Files
Source files containing source code should have the extension .c. The list of source files relevant to the application is
stored in project file with extension .mcpds, along with other project information. You can compile source files only if
they are part of the project.
Use the preprocessor directive #include to include header files with the extension .h. Do not rely on the preprocessor
to include source files other than headers see Add/Remove Files from Project for more information.
If you use the New Project Wizard, an empty source file, named after the project with extension .c, will be created
automatically. The mikroC PRO for dsPIC30/33 and PIC24 does not require you to have a source file named the same
as the project, its just a matter of convenience.
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
Toolbar.
MikroElektronika
760
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:
761
MikroElektronika
Description
Add Search Path.
MikroElektronika
762
763
MikroElektronika
Compilation
When you have created the project and written the source code, its 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
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 mikroC PRO for dsPIC30/33 and PIC24 will generate output
files.
Output Files
Upon successful compilation, the mikroC PRO for dsPIC30/33 and PIC24 will generate output files in the project folder
(folder which contains the project file .mcpds). Output files are summarized in the table below:
Format
Description
File Type
Intel HEX
Binary
List File
Assembler File
Assembly View
After compiling the program in the mikroC PRO for dsPIC30/33 and PIC24, 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
764
765
MikroElektronika
MikroElektronika
766
7. Connect second end of the modular interface cable to the ICD (RJ12) socket of EasydsPIC4A :
767
MikroElektronika
9. Next, open MPLAB, and select the appropriate device by choosing Configure Select Device... :
10. After device selection, click on the File Import. Open file dialog box should appear. Then, go to the project folder
and open the generated HEX file, UART.hex.
Note: This is very important, because hex file contains configuration bit settings which are essential for the proper
functioning of the user code.
MikroElektronika
768
769
MikroElektronika
13. Complete the MPLAB ICD 2 Setup Wizard from the Debugger menu (if needed).
MikroElektronika
770
771
MikroElektronika
MikroElektronika
772
773
MikroElektronika
MikroElektronika
774
775
MikroElektronika
MikroElektronika
776
777
MikroElektronika
What are differences between mikroC PRO, mikroPascal PRO and mikroBasic PRO
compilers ? Why do they have different prices ?
Basically, there is little differences between these compilers. mikroC PRO is standardized with ANSI C, and it is much
more complex and it is far more difficult to write the compiler for it. We used a lot more resources for making it than what
we used for mikroPascal and mikroBasic. We 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 dont support 12F508 and some similar chips ?
Unfortunately our PIC compilers dont 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
wont 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 doesnt work with new
compiler, you have to repeat registration procedure from the new compiler and you will get a new license.
MikroElektronika
778
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 companys 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 MCUs 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.
779
MikroElektronika
I have a question about your compilers which is not listed here. Where can I find an
answer ?
Firstly, look for it in your compilers Help. If you dont find an answer there, please create a support ticket on our
website.
MikroElektronika
780
781
MikroElektronika
If you have any questions, comments or business proposals, do not hesitate to contact us at office@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 want to learn more about our products, please visit our website at www.mikroe.com