manual microbasic
TRANSCRIPT
mikroBASIC
Develop your applications quickly and easily with the world'smost advanced BASIC compiler for dsPIC Microcontrollers (allfamilies).
Highly sophisticated IDE provides the power you need with thesimplicity of a Windows based point-and-click environment.
With useful implemented tools, many practical code examples,broad set of built-in routines, and a comprehensive Help,mikroBasic makes fast and reliable tool, which can satisfy theneeds of experienced engineers and beginners alike.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroElektronikaDevelopment tools - Books - Compilersw w w . m i k r o e l e k t r o n i k a . c o . y u
User
’s mm
anual
f o r d s P I C
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
ii mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
DISCLAIMER:mikroBasic and this manual are owned by mikroElektronika and are protected by copyrightlaw and international copyright treaty. Therefore, you should treat this manual like any othercopyrighted material (e.g., a book). The manual and the compiler may not be copied, par-tially or as a whole without the written consent from the mikroElektronika. The PDF-editionof the manual can be printed for private or local use, but not for distribution. Modifying themanual or the compiler is strictly prohibited.
HIGH RISK ACTIVITIESThe mikroBasic compiler is not fault-tolerant and is not designed, manufactured or intendedfor use or resale as on-line control equipment in hazardous environments requiring fail-safeperformance, such as in the operation of nuclear facilities, aircraft navigation or communica-tion systems, air traffic control, direct life support machines, or weapons systems, in whichthe failure of the Software could lead directly to death, personal injury, or severe physical orenvironmental damage ("High Risk Activities"). mikroElektronika and its suppliers specificallydisclaim any express or implied warranty of fitness for High Risk Activities.
LICENSE AGREEMENT:By using the mikroBasic compiler, you agree to the terms of this agreement. Only oneperson may use licensed version of mikroBasic compiler at a time. Copyright © mikroElektronika 2003 - 2005.
This manual covers mikroBasic for dsPIC version 1.0 and the related topics. New versionsmay contain changes without prior notice.
COMPILER BUG REPORTS:The compiler has been carefully tested and debugged. It is, however, not possible to guarantee a 100% error free product. If you would like to report a bug, please contact us atthe address [email protected]. Please include the following information in yourbug report:
- Your operating system- Version of mikroBasic- Code sample- Description of a bug
CONTACT US:mikroElektronikaVoice: + 381 (11) 30 66 377, + 381 (11) 30 66 378 Fax: + 381 (11) 30 66 379Web: www.mikroelektronika.co.yu E-mail: [email protected]
Reader’s note
dsPIC, dsPICmicro and MPLAB is a Registered trademark of Microchip company. Windowsis a Registered trademark of Microsoft Corp. All other trade and/or services marks are the property of the respective owners.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers
Table of Contents
CHAPTER 1 mikroBasic IDE
CHAPTER 2 Building Applications
CHAPTER 3 mikroBasic Language Reference
CHAPTER 4 mikroBasic Libraries
mikroBASIC UUser’s mmanual
CHAPTER 1: mikroBasic IDE 1
Quick Overview 1Code Editor 3Code Explorer 6Debugger 7Error Window 10Statistics 11Integrated Tools 14Keyboard Shortcuts 16
CHAPTER 2: Building Applications 19
Projects 20Source Files 21
Search Paths 21Managing Source Files 21
Compilation 23Output Files 23Assembly View 23
Error Messages 24
CHAPTER 3: mikroBasic Language Reference 27
mikroBasic Specifics 28Predefined Globals and Constants 28Accessing Individual Bits 28Interrupts 29Linker Directives 30
Lexical Elements 31Whitespace 31Comments 32
Tokens 33Literals 34
Integer Literals 34Floating Point Literals 34Character Literals 35String Literals 35
Keywords 36Identifiers 37
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
iv mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Punctuators 38Program Organization 40Scope and Visibility 43Modules 44
Include Clause 44Main Module 45Other Modules 46
Variables 47Constants 48Labels 49Symbols 50Functions and Procedures 51
Functions 51Procedures 52
Types 54Simple Types 55Arrays 56Strings 57Pointers 59Records 60
Types Conversions 62Implicit Conversion 62Explicit Conversion 63
Operators 64Precedence and Associativity 64Arithmetic Operators 65Relational Operators 66Bitwise Operators 67Boolean Operators 70
Expressions 71Statements 72
asm Statement 72Assignment Statements 73Conditional Statements 73Iteration Statements 75Jump Statements 77
Compiler Directives 80
mikroElektronika: DDevelopment ttools - BBooks - CCompilers vpage
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
CHAPTER 4: mikroBasic Libraries 83
Built-in Routines 84Library Routines 89
ADC Library 90Compact Flash Library 92I2C Library 101Keypad Library 106LCD Library (4-bit interface) 110LCD Library (8-bit interface) 115Graphic LCD Library 119Multi Media Card Library 130PS/2 Library 135PWM Library 138Secure Digital Library 143Software I2C Library 148Software SPI Library 152Software UART Library 155SPI Library 158UART Library 163Util Library 170Conversions Library 171Math Library 175Delays Library 181String Library 184DSP Library 191
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
vi mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
CHAPTER
MikroElektronika: DDevelopment ttools - BBooks - CCompilers
1
mikroBasic IDE
mikroBasic is a powerful, feature rich development tool for dsPIC micros. It hasbeen designed to provide the customer with the easiest possible solution fordeveloping applications for embedded systems, without compromising perform-ance or control.
Highly advanced IDE, broad set of hardware libraries, comprehensivedocumentation and plenty of ready to run examples should be more than enoughto get you started in programming dsPIC microcontrollers.
QUICK OVERVIEW
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
2 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
mikroBasic allows you to quickly develop and deploy complex applications:
- Write your BASIC source code using the highly advanced Code Editor
- Use the included mikroBasic libraries to dramatically speed up development:data acquisition, memory, displays, conversions, communications…
- Generate commented, human-readable assembly, and standard HEX compatible with all programmers.
- Inspect program flow and debug executable logic with the integrated Debugger. Get detailed reports and graphs on code statistics, assembly listing, calling tree…
- We have provided plenty of examples for you to expand, develop, and use as building bricks in your projects.
CodeExplorer
ErrorWindow
WatchWindow
CodeEditor
BreakpointsWindow
CodeAssistant
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 3page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
The Code Editor is advanced text editor fashioned to satisfy the needs of profes-sionals. General code editing is same as working with any standard text-editor,including familiar Copy, Paste, and Undo actions, common for Windows environ-ment.
Advanced Editor features include:
- Adjustable Syntax Highlighting - Code Assistant - Parameter Assistant - Code Templates- Code Folding- Auto Correct for common typos - Bookmarks and Goto Line
You can customize these options from te Editor Settings dialog. To access thesettings, click Tools > Options from the drop-down menu, or click the Tools icon.
CODE EDITOR
Tools Icon.
Code Assistant [CTRL+SPACE]
If you type first few letter of a word and then press CTRL+SPACE, all valid iden-tifiers matching the letters you typed will be prompted to you in a floating panel(see the image). Now you can keep typing to narrow the choice, or you can selectone from the list using keyboard arrows and Enter.
Parameter Assistant [CTRL+SHIFT+SPACE]
The Parameter Assistant will be automatically invoked when you open a parenthe-sis "(" or press CTRL+SHIFT+SPACE. If name of valid function or procedureprecedes the parenthesis, then the expected parameters will be prompted to you ina floating panel. As you type the actual parameter, next expected parameter willbecome bold.
Code Template [CTR+J]
You can insert the Code Template by typing the name of the template (forinstance, whileb), then press CTRL+J, and Editor will automatically generatecode. Or you can click button from Code toolbar and select template from the list.
You can add your own templates to the list. Just select Tools > Options from thedrop-down menu, or click the Tools Icon from the Settings Toolbar, and thenselect the Auto Complete Tab. Here you can enter the appropriate keyword,description, and code of your template.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
4 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Auto Correct
The Auto Correct feature corrects common typing mistakes. To access the list ofrecognized typos, select Tools > Options from the drop-down menu, or click theTools Icon from the Settings Toolbar, and then select the Auto Correct Tab. Youcan also add your own preferences to the list.
Comment/Uncomment
The Code Editor allows you to comment or uncomment selected block of code bya simple click of a mouse, using the Comment/Uncomment icons from the CodeToolbar.
Bookmarks
Bookmarks make navigation through large code easier.
CTRL+<number> : Goto bookmarkCTRL+SHIFT+<number> : Set bookmark
Goto Line
Goto Line option makes navigation through large code easier. Select Search >Goto Line from the drop-down menu, or use the shortcut CTRL+G.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 5page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Comment /Uncomment Icon.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
6 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Code Explorer is placed to the left of the main window by default, and gives clearview of every declared item in the source code. You can jump to declaration ofany item by right clicking it, or by clicking the Find Declaration icon. To expandor collapse treeview in the Code Explorer, use the Collapse/Expand All icon.
Also, two more tab windows are available in the Code Explorer. QHelp Tab listsall the available built-in and library functions, for a quick reference. Double-click-ing a routine in QHelp Tab opens the relevant Help topic. Keyboard Tab lists allavailable keyboard shortcuts in mikroBasic.
CODE EXPLORER
Collapse/ExpandAll Icon.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 7page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Source-level Debugger is an integral component of mikroBasic development envi-ronment. It is designed to simulate operations of Microchip Technology'sdsPICmicros and to assist users in debugging software written for these devices.
Debugger simulates program flow and execution of instruction lines, but does notfully emulate dsPIC device behavior: it does not update timers, interrupt flags, etc.
After you have successfully compiled your project, you can run Debugger byselecting Run > Debug from the drop-down menu, or by clicking Debug Icon .Starting the Debugger makes more options available: Step Into, Step Over, Run toCursor, etc. Line that is to be executed is color highlighted.
Debug [F9]Start the Debugger.
Run/Pause Debugger [F6]Run or pause the Debugger.
Step Into [F7]Execute the current BASIC (single– or multi–cycle) instruction, then halt. If theinstruction is a routine call, enter the routine and halt at the first instruction fol-lowing the call.
Step Over [F8]Execute the current BASIC (single– or multi–cycle) instruction, then halt. If theinstruction is a routine call, skip it and halt at the first instruction following thecall. Stops at the first breakpoint.
Step Out [Ctrl+F8] Execute the current BASIC (single– or multi–cycle) instruction, then halt. If theinstruction is within a routine, execute the instruction and halt at the first instruc-tion following the call. Stops at the first breakpoint.
Run to cursor [F4]Executes all instructions between the current instruction and the cursor position.Stops at the first breakpoint.
DEBUGGER
Start Debugger.
Step Into.
Step Over.
Step Out.
Pause Debugger.
Run to Cursor.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
8 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Toggle Breakpoint [F5]Toggle breakpoint at the current cursor position. To view all the breakpoints, selectRun > View Breakpoints from the drop-down menu. Double clicking an item inwindow list locates the breakpoint.
Watch Window
Debugger Watch Window is the main Debugger window which allows you tomonitor program items while running your program. To show the Watch Window,select View > Debug Windows > Watch Window from the drop-down menu.
The Watch Window displays variables and registers of dsPIC, with their addressesand values. Values are updated as you go through the simulation. Use the drop-down menu to add and remove the items that you want to monitor. Recentlychanged items are colored red.
Double clicking an item opens the Edit Value window in which you can assign anew value to the selected variable/register. Also, you can change view to binary,hex, char, or decimal for the selected item.
ToggleBreakpoint.
Stopwatch Window
Debugger Stopwatch Window is available from the drop-down menu,View > Debug Windows > Stopwatch.
The Stopwatch Window displays the current count of cycles/time since the lastDebugger action. Stopwatch measures the execution time (number of cycles) fromthe moment Debugger is started, and can be reset at any time. Delta represents thenumber of cycles between the previous instruction line (line where Debuggeraction was performed) and the active instruction line (where the Debugger actionlanded).
Note: You can change the clock in the Stopwatch Window; this will recalculatevalues for the newly specified frequency. Changing the clock in the StopwatchWindow does not affect the actual project settings – it only provides a simulation.
View RAM Window
Debugger View RAM Window is available from the drop-down menu,View > Debug Windows > View RAM.
The View RAM Window displays the map of dsPIC’s RAM, with recentlychanged items colored red. You can change value of any field by double-clickingit.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 9page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
10 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
In case that errors were encountered during compiling, compiler will report themand won't generate a hex file. The Error Window will be prompted at the bottomof the main window.
The Error Window is located under message tab, and displays location and type oferrors compiler has encountered. The compiler also reports warnings, but these donot affect generating hex code. Only errors can interefere with generation of hex.
Double click the message line in the Error Window to highlight the line where theerror was encountered.
Consult the Error Messages for more information about errors recognized by thecompiler.
ERROR WINDOW
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 11page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
After successful compilation, you can review statistics of your code. Select Project> View Statistics from the drop-down menu, or click the Statistics icon. There aresix tab windows:
Memory Usage WindowProvides overview of RAM and ROM memory usage in form of histogram.
Procedures (Graph) WindowDisplays functions in form of histogram, according to their memory allotment.
STATISTICS
Statistics Icon.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
12 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Procedures (Locations) WindowDisplays how functions are distributed in the microcontroller’s memory.
Procedures (Details) WindowDisplays the complete call tree, along with details for each routine: size, start andend address, calling frequency, return type, etc.
RAM WindowSummarizes all GPR and SFR registers and their addresses. It also displays sym-bolic names of variables and their addresses.
ROM WindowLists op-codes and their addresses in form of a human readable hex code.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 13page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
14 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
USART TerminalmikroBasic includes the USART (Universal Synchronous Asynchronous ReceiverTransmitter) communication terminal for RS232 communication. You can launchit from the drop-down menu Tools > Terminal or by clicking the Terminal icon.
ASCII ChartThe ASCII Chart is a handy tool, particularly useful when working with LCD dis-play. You can launch it from the drop-down menu Tools > ASCII chart.
INTEGRATED TOOLS
7 Segment Display DecoderThe 7seg Display Decoder is a convenient visual panel which returns decimal/hexvalue for any viable combination you would like to display on 7seg. Click on theparts of 7 segment image to the left to get the desired value in the edit boxes. Youcan launch it from the drop-down menu Tools > 7 Segment Display.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 15page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
16 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Below is the complete list of keyboard shortcuts available in mikroBasic IDE. Youcan also view keyboard shortcuts in the Code Explorer, tab Keyboard.
IDE Shortcuts
F1 HelpCTRL+N New ModuleCTRL+O OpenCTRL+F9 CompileCTRL+F11 Code Explorer on/offCTRL+SHIFT+F5 View breakpoints
Basic Editor shortcuts
F3 Find, Find NextCTRL+A Select AllCTRL+C CopyCTRL+F FindCTRL+P PrintCTRL+R ReplaceCTRL+S Save unitCTRL+SHIFT+S Save AsCTRL+V PasteCTRL+X CutCTRL+Y RedoCTRL+Z Undo
Advanced Editor shortcuts
CTRL+SPACE Code AssistantCTRL+SHIFT+SPACE Parameters AssistantCTRL+D Find declarationCTRL+G Goto lineCTRL+J Insert Code TemplateCTRL+<number> Goto bookmarkCTRL+SHIFT+<number> Set bookmark CTRL+SHIFT+I Indent selectionCTRL+SHIFT+U Unindent selectionCTRL+ALT+SELECT Select columns
KEYBOARD SHORTCUTS
Debugger Shortcuts
F4 Run to CursorF5 Toggle breakpointF6 Run/Pause DebuggerF7 Step intoF8 Step overF9 DebugCTRL+F2 Reset
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 17page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
18 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
CHAPTER
mikroElektronika: DDevelopment ttools - BBooks - CCompilers
2
BuildingApplications
Creating applications in mikroBasic is easy and intuitive. Project Wizard allowsyou to set up your project in just few clicks: name your application, select chip,set flags, and get going.
mikroBasic allows you to distribute your projects in as many units as you findappropriate. You can then share your mikroCompiled Libraries (.mcl files) withother developers without disclosing the source code.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
20 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
mikroBasic organizes applications into projects, consisting of a single project file(extension .dbp) and one or more source files (extension .dbas). You can com-pile source files only if they are a part of the project.
Project file carries the following information:
- project name and optional description- target device- device flags (config word) and device clock- list of project source files with paths
New Project
The easiest way to create project is by means of the New Project Wizard, drop-down menu Project > New Project. Just fill the dialog with desired values (projectname and description, location, device, clock, config word) and mikroBasic willcreate the appropriate project file.
Also, an empty source file named after the project will be created by default.mikroBasic does not require you to have a source file named same as the project,it’s just a matter of convenience.
Editing Project
Later, you can change project settings from the drop-down menu Project > Edit.You can add or remove source files from project, rename the project, modify itsdescription, change chip, clock, config word, etc.
To delete a project, simply delete the folder in which the project file is stored.
PROJECTS
New Project.
Edit Project.
Source files containing BASIC code should have the extension .dbas. List ofsource files relevant for the application is stored in the project file with extension.dbp, along with other project information. You can compile source files only ifthey are part of a project.
Search Paths
You can specify your own custom search paths. This can be configured by select-ing Tools > Options from the drop-down menu and Compiler > Search Paths.
When including source files with the include clause, mikroBasic will look for thefile in following locations, in this particular order:
1. mikroBasic installation folder > “defs” folder2. mikroBasic installation folder > “uses” folder3. your custom search paths4. the project folder (folder which contains the project file .dbp)
Managing Source Files
Creating new source file
To create a new source file, do the following:
Select File > New from the drop-down menu, or press CTRL+N, or click the NewFile icon. A new tab will open, named “Untitled1”. This is your new source file.Select File > Save As from the drop-down menu to name it the way you want.
If you have used the New Project Wizard, an empty source file, named after theproject with extension .dbas, is created automatically. mikroBasic does notrequire you to have a source file named same as the project, it’s just a matter ofconvenience.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 21page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
SOURCE FILES
New File.
Opening an Existing File
Select File > Open from the drop-down menu, or press CTRL+O, or click theOpen File icon. The Select Input File dialog opens. In the dialog, browse to thelocation of the file that you want to open and select it. Click the Open button. The selected file is displayed in its own tab. If the selected file is already open, itscurrent Editor tab will become active.
Printing an Open File
Make sure that the window containing the file that you want to print is the activewindow. Select File > Print from the drop-down menu, or press CTRL+P, or clickthe Print icon. In the Print Preview Window, set the desired layout of the docu-ment and click the OK button. The file will be printed on the selected printer.
Saving File
Make sure that the window containing the file you that want to save is the activewindow. Select File > Save from the drop-down menu, or press CTRL+S, or clickthe Save icon. The file will be saved under the name on its window.
Saving File Under a Different Name
Make sure that the window containing the file that you want to save is the activewindow. Select File > Save As from the drop-down menu, or pressSHIFT+CTRL+S. The New File Name dialog will be displayed. In the dialog,browse to the folder where you want to save the file. In the File Name field, modi-fy the name of the file you want to save. Click the Save button.
Closing a File
Make sure that the tab containing the file that you want to close is the active tab.Select File > Close from the drop-down menu, or right click the tab of the file thatyou want to close in Code Editor. If the file has been changed since it was lastsaved, you will be prompted to save your changes.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
22 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Open File.
Print File.
Save File.
Save File As.
Close File.
When you have created the project and written the source code, you will want tocompile it. Select Project > Build from the drop-down menu, or click the BuildIcon, or simply hit CTRL+F9.
Progress bar will appear to inform you about the status of compiling. If there areerrors, you will be notified in the Error Window. If no errors are encountered,mikroBasic will generate the output files.
Output Files
Upon successful compilation, mikroBasic will generate output files in the projectfolder (folder which contains the project file .dbp). Output files are summarizedbelow:
Intel HEX file (.hex)Intel style hex records. Use this file to program the chip.
Binary mikro Compiled Library (.mcl)Binary distribution of application that can be included in other projects.
List File (.lst)Overview of dsPIC memory allotment: addresses, registers, routines, etc.
Assembler File (.asm)Human readable assembly with symbolic names, extracted from the List File.
Assembly View
After compiling your program in mikroBasic, you can click the View AssemblyIcon or select Project > View Assembly from the drop-down menu to review gen-erated assembly code (.asm file) in a new tab window. The assembler is humanreadable with symbolic names. All physical addresses and other information canbe found in Statistics or in list file (.lst).
If the program is not compiled and there is no assembly file, starting this optionwill compile your code and then display assembly.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 23page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
View AssemblyIcon.
Build Icon.
COMPILATION
Error Messages
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
24 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
ERROR MESSAGES
Message Message Number
Error: "%s" is not a valid identifier 1
Error: Unknown type "%s" 2
Error: Identifier "%s" was not declared 3
Error: Expected "%s" but "%s" found 4
Error: Argument is out of range 5
Error: Syntax error in additive expression 6
Error: File "%s" not found 7
Error: Invalid command "%s" 8
Error: Not enough parameters 9
Error: Too many parameters 10
Error: Too many characters 11
Error: Actual and formal parameters must be identical 12
Error: Invalid ASM instruction: "%s" 13
Error: Identifier "%s" has been already declared 14
Error: Syntax error in multiplicative expression 15
Error: Definition file for "%s" is corrupted 16
Hint and Warning Messages
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 25page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Message Message Number
Hint: Variable "%s" has been declared, but was not used 1
Warning: Variable "%s" is not initialized 2
Warning: Return value of the function "%s" is not defined 3
Hint: Constant "%s" has been declared, but was not used 4
Warning: Identifier "%s" overrides declaration in unit "%s" 5
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
26 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
CHAPTER
mikroElektronika: DDevelopment ttools - BBooks - CCompilers
3
mikroBasicLanguage Reference
Why BASIC in the first place? The answer is simple: it is legible, easy-to-learn,structured programming language, with sufficient power and flexibility needed forprogramming microcontrollers. Whether you had any previous programming expe-rience, you will find that writing programs in mikroBasic is very easy. This chap-ter will help you learn or recollect BASIC syntax, along with the specifics of pro-gramming dsPIC microcontrollers.
Predefined Globals and Constants
To facilitate programming, mikroBasic implements a number of predefined globalsand constants.
All dsPIC SFR registers are implicitly declared as global variables of word type.These identifiers have external linkage, and are visible in the entire project. Whencreating a project, mikroBasic will include an appropriate .def file, containingdeclarations of available SFR and constants (such as W0, TMR1, etc). Identifiers areall in uppercase, identical to the nomenclature in Microchip datasheets.
For the complete set of predefined globals and constants, look for “Defs” in yourmikroBasic installation folder, or probe the Code Assistant for specific letters(Ctrl+Space in the Code Editor).
Accessing Individual Bits
mikroBasic for dsPIC allows you to access individual bits of 16-bit variables.Simply use the dot (.) with a variable, followed by a number 0..15, with 15 beingthe most significant bit.
For example:
' If RB0 is set, set RC0:if PORTB.0 = 1 then
PORTC.0 = 1end if
There is no need for any special declarations; this kind of selective access is anintrinsic feature of mikroBasic and can be used anywhere in the code.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
28 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
mikroBasic SPECIFICS
Interrupts
You can create a specific interrupt handler by placing your procedure at theaddress from interrupt vector table. Use the linker directive org to push routine tospecific memory address (see Linker Directives). Consult the datasheet for inter-rupt vector details.
For example, to create a handler for Timer1 interrupt, we’ll use the value $A1 (asstated in datasheet, interupt vector table):
sub procedure Timer1Int org 0x1AIFS0 = IFS0 and 0xFFF7 ' clear TMR1IF' code for interrupt handling goes here
end sub
You don’t need to save the context manually. mikroBasic will automatically saveregisters W0 – W13 upon entering the interrupt routine, and restore them upon exit.
Example
Here is a simple procedure which inverts state of PORTB upon each interruptfrom Timer1:
sub procedure Timer1Int org 0x1AIFS0 = IFS0 and 0xFFF7 ' clear TMR1IFLATB = not PORTB ' invert PORTB
sub end
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 29page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Linker Directives
mikroBasic uses internal algorithm to distribute objects within memory. If youneed to have a variable or a routine at the specific predefined address, use the link-er directives absolute and org.
Note: You must specify an even address when using the linker directives.
Directive absolute
Directive absolute specifies the starting address in RAM for a variable. If thevariable spans more than 1 word (16-bit), higher words will be stored at the con-secutive locations. Directive absolute is appended to the declaration of a vari-able:
dim x as word absolute $32' Variable x will occupy 1 word (16 bits) at address $32
y as longint absolute $34' Variable y will occupy 2 words at addresses $34 and $36
Be careful when using the absolute directive, as you may overlap variables byaccident. For example:
dim i as word absolute $42' Variable i will occupy 1 word at address $42;
jj as longint absolute $40' Variable will occupy 2 words at $40 and $42; thus,' changing i changes jj at the same time and vice versa
Directive org
Directive org specifies the starting address of a routine in ROM. It is appended tothe declaration of a routine. For example:
sub procedure proc(dim par as word) org $200' Procedure will start at the address $200;...end sub
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
30 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
These topics provide a formal definition of the mikroBasic lexical elements. Theydescribe the different categories of word-like units (tokens) recognized by a lan-guage.
In the tokenizing phase of compilation, the source code file is parsed (that is, bro-ken down) into tokens and whitespace. The tokens in mikroBasic are derived froma series of operations performed on your programs by the compiler.
A mikroBasic program starts as a sequence of ASCII characters representing thesource code, created by keystrokes using a suitable text editor (such as themikroBasic Code Editor). The basic program unit in mikroBasic is the file. Thisusually corresponds to a named file located in RAM or on disk and having theextension .dbas.
Whitespace
Whitespace is the collective name given to spaces (blanks), horizontal and verticaltabs, newline characters, and comments. Whitespace serves to indicate wheretokens start and end, but beyond this function, any surplus whitespace is discard-ed.
Newline Character
Newline character (CR/LF) is not a whitespace in BASIC, and serves as a state-ment terminator/separator. In mikroBasic, however, you may use newline to breaklong statements into several lines. Parser will first try to get the longest possibleexpression (across lines if necessary), and then check for statement terminators.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 31page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
LEXICAL ELEMENTS
Whitespace in Strings
The ASCII characters representing whitespace can occur within string literals, inwhich case they are protected from the normal parsing process (they remain aspart of the string). For example, statement
some_string = "mikro foo"
parses to four tokens, including the single string literal token:
some_string="mikro foo"newline character
Comments
Comments are pieces of text used to annotate a program, and are technicallyanother form of whitespace. Comments are for the programmer’s use only; theyare stripped from the source text before parsing.
Use the apostrophe to create a comment:
' Any text between an apostrophe and the end of the' line constitutes a comment. May span one line only.
There are no multi-line comments in BASIC.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
32 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Token is the smallest element of a BASIC program that is meaningful to the com-piler. The parser separates tokens from the input stream by creating the longesttoken possible using the input characters in a left–to–right scan.
mikroBasic recognizes these kinds of tokens:
- keywords - identifiers - constants - operators - punctuators (also known as separators)
Token Extraction Example
Here is an example of token extraction. Let’s have the following code sequence:
end_flag = 0
The compiler would parse it as the following four tokens:
end_flag ' variable identifier= ' assignment operator0 ' literalnewline ' statement terminator
Note that end_flag would be parsed as a single identifier, rather than as the key-word end followed by the identifier _flag.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 33page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
TOKENS
Literals are tokens representing fixed numeric or character values.
The data type of a constant is deduced by the compiler using such clues as numer-ic value and the format used in the source code.
Integer Literals
Integral values can be represented in decimal, hexadecimal, or binary notation.
In decimal notation, numerals are represented as a sequence of digits (withoutcommas, spaces, or dots), with optional prefix + or - operator to indicate the sign.Values default to positive (6258 is equivalent to +6258).
The dollar-sign prefix ($) or the prefix 0x indicates a hexadecimal numeral (forexample, $8F or 0x8F).
The percent-sign prefix (%) indicates a binary numeral (for example, %0101).
The allowed range of values is imposed by the largest data type in mikroBasic –longint. Compiler will report an error if the literal exceeds 2147483647($7FFFFFFF).
Floating Point Literals
A floating-point value consists of:
- Decimal integer- Decimal point - Decimal fraction - e or E and a signed integer exponent (optional)
You can omit either the decimal integer or the decimal fraction (but not both).Negative floating constants are taken as positive constants with the unary operatorminus (-) prefixed.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
34 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
LITERALS
mikroBasic limits floating-point constants to range±1.17549435082E38 .. ±6.80564774407E38.
Here are some examples:
0. ' = 0.023.45e6 ' = 23.45 * 10^62e-5 ' = 2.0 * 10^-5-.09E34 ' = -0.09 * 10^34
Character Literals
Character literal is one character from the extended ASCII character set, enclosedby quotes (for example, "A"). Character literal can be assigned to variables of byteand char type (variable of byte will be assigned the ASCII value of the character).Also, you can assign character literal to a string variable.
String Literals
String literal is a sequence of up to 255 characters from the extended ASCII char-acter set, enclosed by quotes. Whitespace is preserved in string literals, i.e. parserdoes not “go into” strings but treats them as single tokens.
Length of string literal is the number of characters it consists of. String is storedinternally as the given sequence of characters plus a final null character (ASCIIzero). This appended “stamp” does not count against string’s total length. Stringliteral with nothing in between the quotes (null string) is stored as a single nullcharacter. You can assign string literal to a string variable or to an array of char.
Here are several string literals:
"Hello world!" ' message, 12 chars long" " ' two spaces, 2 chars long"C" ' letter, 1 char long"" ' null string, 0 chars long
Quote itself cannot be a part of the string literal, i.e. there is no escape sequence.See String Splicing under Strings (Types) for more inforation.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 35page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Keywords are words reserved for special purposes and must not be used as normalidentifier names.
Beside standard BASIC keywords, all relevant SFR are defined as global variablesand represent reserved words that cannot be redefined (for example: W0, TMR1,T1CON, etc). Probe the Code Assistant for specific letters (CTRL+SPACE inEditor) or refer to Predefined Globals and Constants.
Here is the alphabetical listing of keywords in mikroBasic:
absolute float orabs for organd function printarray goto procedureasm gosub programbegin if readboolean include selectcase in subchar int stepchr integer stringclear interrupt switchconst is thendim loop todiv label untildo mod wenddouble module whileelse new withend next xorexit not
Also, mikroBasic includes a number of predefined identifiers used in libraries. Youcould replace these by your own definitions, if you plan to develop your ownlibraries. For more information, see mikroBasic Libraries.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
36 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
KEYWORDS
Identifiers are arbitrary names of any length given to functions, variables, symbol-ic constants, user-defined data types, and labels. All these program elements willbe referred to as objects throughout the help (not to be confused with the meaningof object in object-oriented programming).
Identifiers can contain letters a to z and A to Z, the underscore character _, anddigits 0 to 9. First character must be a letter or an underscore, i.e. identifier cannotbegin with a numeral.
Case Sensitivity
BASIC is not case sensitive, so Sum, sum, and suM represent an equivalentidentifier.
Uniqueness and Scope
Although identifier names are arbitrary (within the rules stated), errors result if thesame name is used for more than one identifier within the same scope and sharingthe same name space. Duplicate names are legal for different name spaces regard-less of scope rules. For more information on scope, refer to Scope and Visibility.
Identifier Examples
Here are some valid identifiers:
temperature_V1Pressureno_hitdat2stringSUM3_vtext
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 37page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
IDENTIFIERS
The mikroBasic punctuators (also known as separators) include brackets, parenthe-ses, comma, semicolon, colon, and dot.
Brackets
Brackets [ ] indicate single and multidimensional array subscripts:
dim alphabet as byte[30]' ...alphabet[2] = "c"
For more information, refer to Arrays.
Parentheses
Parentheses ( ) are used to group expressions, isolate conditional expressions,and indicate function calls and function declarations:
d = c * (a + b) ' Override normal precedenceif (d = z) then ... ' Useful with conditional statementsfunc() ' Function call, no args
For more information, refer to Operators Precedence and Associativity,Expressions, or Functions and Procedures.
Comma
The comma (,) separates the arguments in routine calls:
Lcd_Out(1, 1, txt)
Further, the comma separates identifiers in declarations:
dim i, j, k as word
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
38 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
PUNCTUATORS
The comma also separates elements of array in initialization lists:
const MONTHS as byte[12] = (31,28,31,30,31,30,31,31,30,31,30,31)
Colon
Colon (:) is used to indicate a labeled statement:
start: nop'...
goto start
For more information, refer to Labels.
Dot
Dot (.) indicates access to a field of a record. For example:
person.surname = "Smith"
For more information, refer to Structures.
Dot is also a necessary part of floating point literals. Also, dot can be used foraccessing individual bits of registers in mikroBasic.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 39page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
mikroBasic imposes strict program organization. Below you can find models forwriting legible and organized source files. For more information on file inclusionand scope, refer to Units and to Scope and Visibility.
Organization of Main Module
Basically, main source file has two sections: declaration and program body.Declarations should be in their proper place in the code, organized in an orderlymanner. Otherwise, compiler may not be able to comprehend the programcorrectly.
When writing code, follow the model presented in the following page.
Organization of Other Modules
Modules other than main start with the keyword module; implementation sectionstarts with the keyword implements. Follow the models presented in the followingpages.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
40 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
PROGRAM ORGANIZATION
Main module should look like this:
program <program name>include <include other modules>
'********************************************************'* Declarations (globals):'********************************************************
' symbols declarationssymbol ...
' constants declarationsconst ...
' variables declarationsdim ...
' procedures declarationssub procedure procedure_name(...)
<local declarations>...
end sub
' functions declarationssub function function_name(...)
<local declarations>...
end sub
'********************************************************'* Program body:'********************************************************
main:' write your code here
end.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 41page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Other modules should look like this:
module <module name>include <include other modules>
'********************************************************'* Interface (globals):'********************************************************
' symbols declarationssymbol ...
' constants declarationsconst ...
' variables declarationsdim ...
' procedures prototypessub procedure procedure_name(...)
' functions prototypessub function function_name(...)
'********************************************************'* Implementation:'********************************************************
implements
' constants declarationsconst ...
' variables declarationsdim ...
' procedures declarationssub procedure procedure_name(...)
<local declarations>...
end sub
' functions declarationssub function function_name(...)
<local declarations>...
end sub
end.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
42 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Scope
The scope of identifier is the part of the program in which the identifier can beused to access its object. There are different categories of scope which depend onhow and where identifiers are declared:
If identifier is declared in the declaration section of a main module, out of anyfunction or procedure, scope extends from the point where it is declared to the endof the current file, including all routines enclosed within that scope. These identi-fiers have a file scope, and are referred to as globals.
If identifier is declared in the function or procedure, scope extends from the pointwhere it is declared to the end of the current routine. These identifiers are referredto as locals.
If identifier is declared in the interface section of a module, scope extends theinterface section of a module from the point where it is declared to the end of themodule, and to any other module or program that uses that module.
If identifier is declared in the implementation section of a module, but not withinany function or procedure, scope extends from the point where it is declared to theend of the module. The identifier is available to any function or procedure in themodule.
Visibility
The visibility of an identifier is that region of the program source code from whichlegal access can be made to the identifier’s associated object.
Scope and visibility usually coincide, though there are circumstances under whichan 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 thescope of the duplicate identifier is ended.
Technically, visibility cannot exceed scope, but scope can exceed visibility.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 43page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
SCOPE AND VISIBILITY
In mikroBasic, each project consists of a single project file, and one or more unitfiles. Project file, with extension .dbp contains information about the project,while modules, with extension .dbas, contain the actual source code.
Modules allow you to:
- break large programs into encapsulated modules that can be edited separately,- create libraries that can be used in different projects,- distribute libraries to other developers without disclosing the source code.
Each module is stored in its own file and compiled separately; compiled modulesare linked to create an application. To build a project, the compiler needs either asource file or a compiled module file for each module.
Include Clause
mikroBasic includes modules by means of include clause. It consists of thereserved word include, followed by a quoted module name. Extension of the fileshould not be included.
You can include one file per include clause. There can be any number ofinclude clauses in each source file, but they all must be stated immediately afterthe program (or module) name.
Here’s an example:
program MyProgram
include "utils"include "strings"include "MyUnit"
...
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
44 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
MODULES
Given a unit name, compiler will check for the presence of .mcl and .dbas files,in order specified by the search paths.
- If both .dbas and .mcl files are found, compiler will check their dates andinclude the newer one in the project. If the .dbas file is newer than the .mcl,new library will be written over the old one;
- If only .dbas file is found, compiler will create the .mcl file and include it inthe project;
- If only .mcl file is present, i.e. no source code is available, compiler willinclude it as found;
- If none found, compiler will issue a “File not found” warning.
Main Module
Every project in mikroBasic requires a single main module file. Main unit is iden-tified by the keyword program at the beginning; it instructs the compiler where to“start”.
After you have successfully created an empty project with Project Wizard, CodeEditor will display a new main unit. It contains the bare-bones of a program:
program MyProject
' main proceduremain:
' Place program code hereend.
Other than comments, nothing should precede the keyword program. After theprogram name, you can optionally place the include clauses.
Place all global declarations (constants, variables, labels, routines) before the labelmain.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 45page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Other Modules
Modules other than main start with the keyword module. Newly created blankunit contains the bare-bones:
module MyModule
implements
end.
Other than comments, nothing should precede the keyword module. After themodule name, you can optionally place the include clauses.
Interface Section
Part of the unit above the keyword implements is referred to as interface section.Here, you can place global declarations (constants, variables, and labels) for theproject.
You do not define routines in the interface section. Instead, state the prototypes ofroutines (from implementation section) that you want to be visible outside the unit.Prototypes must match the declarations exactly.
Implementation Section
Implementation section hides all the irrelevant innards from other units, thusencapsulating the code.
Everything declared below the keyword implements is private, i.e. has its scopelimited to the file. When you declare an identifier in the implementation section ofa unit, you cannot use it outside the unit, but you can use it in any block or routinedefined within the unit.
By placing the prototype in the interface section of the unit (above the wordimplements) you can make the routine public, i.e. visible outside of unit.Prototypes must match the declarations exactly.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
46 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Variable is object whose value can be changed during the runtime. Every variableis declared under unique name which must be a valid identifier. This name is usedfor accessing the memory location occupied by the variable.
Variables are declared in the declaration part of the file or routine — each variableneeds to be declared before it can be used. Global variables (those that do notbelong to any enclosing block) are declared below the include statements, abovethe label main.
Specifying a data type for each variable is mandatory. Basic syntax for variabledeclaration is:
dim identifier_list as type
The identifier_list is a comma-delimited list of valid identifiers and typecan be any data type.
For more details refer to Types and Types Conversions. For more information onvariables’ scope refer to the chapter Scope and Visibility.
Here are a few examples:
dim i, j, k as bytedim counter, temp as worddim samples as longint[100]
Variables and dsPIC
Every declared variable consumes part of RAM memory. Data type of variabledetermines not only the allowed range of values, but also the space variable occu-pies in RAM memory. Bear in mind that operations using different types of vari-ables take different time to be completed. mikroBasic recycles local variable mem-ory space – local variables declared in different functions and procedures sharesame memory space, if possible. There is no need to declare SFR explicitly, asmikroBasic automatically declares relevant registers as global variables of word.For example: W0, TMR1, etc.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 47page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
VARIABLES
Constant is data whose value cannot be changed during the runtime. Using a con-stant in a program consumes no RAM memory. Constants can be used in anyexpression, but cannot be assigned a new value.
Constants are declared in the declaration part of program or routine, with the fol-lowing syntax:
const constant_name [as type] = value
Every constant is declared under unique constant_name which must be a valididentifier. It is a tradition to write constant names in uppercase. Constant requiresyou to specify value, which is a literal appropriate for the given type. The type isoptional; in the absence of type, compiler assumes the “smallest” type that canaccommodate value.
Note: You cannot omit type if declaring a constant array.
BASIC allows shorthand syntax with only one keyword const followed by multi-ple constant declarations. Here’s an example:
const MAX as longint = 10000const MIN = 1000 ' compiler will assume word typeconst SWITCH = "n" ' compiler will assume char typeconst MSG = "Hello" ' compiler will assume string typeconst MONTHS as byte[12] = (31,28,31,30,31,30,31,31,30,31,30,31)
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
48 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
CONSTANTS
Labels serve as targets for goto statements. Mark the desired statement with labeland a colon like this:
label_identifier : statement
No special declaration of label is necessary in mikroBasic.
Name of the label needs to be a valid identifier. The labeled statement, andgoto/gosub statement must belong to the same block. Hence it is not possible tojump into or out of routine. Do not mark more than one statement in a block withthe same label.
Note: Label main marks the entry point of a program and must be present in themain module of every project. See Program Organization for more information.
Here is an example of an infinite loop that calls the procedure Beep repeatedly:
loop: Beepgoto loop
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 49page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
LABELS
BASIC symbols allow you to create simple macros without parameters. You canreplace any one line of code with a single identifier alias. Symbols, when properlyused, can increase code legibility and reusability.
Symbols need to be declared at the very beginning of the module, right after themodule name and the (optional) include clauses. Check Program Organizationfor more details. Scope of a symbol is always limited to the file in which it hasbeen declared.
Symbol is declared as:
symbol alias = code
Here, alias must be a valid identifier which you will be using throughout thecode. This identifier has file scope. The code can be any one line of code (literals,assignments, function calls, etc).
Using a symbol in program consumes no RAM memory – compiler simplyreplaces each instance of a symbol with the appropriate line of code from the dec-laration.
Here is an example:
symbol MAXALLOWED = 216 ' Alias for numeric valuesymbol PORT = PORTC ' Alias for SFRsymbol MYDELAY = Delay_ms(1000) ' Alias for procedure call
dim cnt as byte ' Some variable
'...main:
if cnt > MAXALLOWED thencnt = 0PORT.1 = 0MYDELAY
end if
Note: Symbols do not support macro expansion in the way C preprocessor does.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
50 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
SYMBOLS
Functions and procedures, collectively referred to as routines, are subprograms(self-contained statement blocks) which perform a certain task based on a numberof input parameters. Function returns a value when executed, and procedure doesnot. Note: mikroBasic does not support inline routines.
Functions
Function is declared like this:
sub function function_name(parameter_list) as return_type[ local declarations ]function body
end sub
The function_name represents a function’s name and can be any valid identifier.The return_type is the type of return value and can be any simple type. Withinparentheses, parameter_list is a formal parameter list similar to variable dec-laration. In mikroBasic, parameters are always passed to function by value; to passargument by the address, add the keyword var ahead of identifier.
Local declarations are optional declarations of variables and/or constants,local for the given function. Function body is a sequence of statements to beexecuted upon calling the function.
A function is called by its name, with actual arguments placed in the samesequence as their matching formal parameters. The compiler is able to coerce mis-matching arguments to the proper type according to implicit conversion rules.Upon function call, all formal parameters are created as local objects initialized byvalues of actual arguments. Upon return from a function, temporary object is cre-ated in the place of the call, and it is initialized by the expression of return state-ment. This means that function call as an operand in complex expression is treatedas the function result.
Use the variable result (automatically created local) to assign the return value ofa function.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 51page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
FUNCTIONS AND PROCEDURES
Function calls are considered to be primary expressions, and can be used in situa-tions where expression is expected. Function call can also be a self-containedstatement, in which case the return value is discarded.
Here’s a simple function which calculates xn based on input parameters x and n(n > 0):
sub function power(dim x, n as byte) as longintdim i as byte
i = 0result = 1if n > 0 then
for i = 1 to nresult = result*x
next iend if
end sub
Now we could call it to calculate, say, 312:
tmp = power(3, 12)
Procedures
Procedure is declared like this:
sub procedure procedure_name(parameter_list)[ local declarations ]procedure body
end sub
The procedure_name represents a procedure’s name and can be any valid identi-fier. Within parentheses, parameter_list is a formal parameter list similar tovariable declaration. In mikroBasic, parameters are always passed to procedure byvalue; to pass argument by the address, add the keyword var ahead ofidentifier.
Local declarations are optional declaration of variables and/or constants,local for the given procedure. Procedure body is a sequence of statements to beexecuted upon calling the procedure.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
52 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
A procedure is called by its name, with actual arguments placed in the samesequence as their matching formal parameters. The compiler is able to coerce mis-matching arguments to the proper type according to implicit conversion rules.Upon procedure call, all formal parameters are created as local objects initializedby values of actual arguments.
Procedure call is a self-contained statement.
Here’s an example procedure which transforms its input time parameters, prepar-ing them for output on LCD:
sub procedure time_prep(dim byref sec, min, hr as byte)sec = ((sec and $F0) >> 4)*10 + (sec and $0F)min = ((min and $F0) >> 4)*10 + (min and $0F)hr = ((hr and $F0) >> 4)*10 + (hr and $0F)
end sub
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 53page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
BASIC is a strictly typed language, which means that every variable and constantneeds to have a strictly defined type, known at the time of compilation.
The type serves:
- to determine the correct memory allocation required,- to interpret the bit patterns found in the object during subsequent accesses,- in many type-checking situations, to ensure that illegal assignments are trapped.
mikroBasic supports many standard (predefined) and user-defined data types,including signed and unsigned integers of various sizes, arrays, strings, pointers,and records.
Type Categories
Types can be divided into:
- simple types- arrays- strings- pointers- structures (user defined types)
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
54 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
TYPES
Simple types represent types that cannot be divided into more basic elements, andare the model for representing elementary data on machine level.
Here is an overview of simple types in mikroBasic:
Note: Italicized types (char, byte, and short) are kept in mikroBasic for dsPICfor the sake of backward compatibility. Types char and byte behave exactly asthe 16-bit word, while short is a synonym for integer.
You cannot mix signed and unsigned objects in expressions with arithmetic or log-ical operators. You can assign signed to unsigned or vice versa only using theexplicit conversion. Refer to Types Conversions for more information.
Bit Type
mikroBasic for dsPIC includes a special bit type. Variables of this type behave as16-bit words, so they are not 0/1 flags. The bit type has its use for passingparameters to routines, and is commonly served in format REGISTER.PIN (seeAccessing Individual Bits for more information).
If bit type parameter is passed by the address, two words are pushed on stack:the address of the origin register, and bit position in register (15 being the mostsignificant bit). If bit type parameter is passed by the value, then 0 or 1 is pushedon stack and can be accessed as any other variable of word type.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 55page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
SIMPLE TYPES
Type Size Range
word, byte, char 16-bit 0 .. 65535
integer, short 16-bit -32768 .. 32767
longint 32-bit -2147483648 .. 2147483647
float 32-bit ±1.17549435082 * 10-38 ..±6.80564774407 * 1038
An array represents an indexed collection of elements of the same type (called thebase type). Because each element has a unique index, arrays, unlike sets, canmeaningfully contain the same value more than once.
Array types are denoted by constructions of the form:
type[array_length]
Each of the elements of an array is numbered from 0 through the array_length- 1. Every element of an array is of type and can be accessed by specifying arrayname followed by element’s index within brackets.
Here are a few examples of array declaration:
dim weekdays as byte[7]dim samples as word[50]
main:' Now we can access elements of array variables, for example:samples[0] = 1if samples[37] = 0 then
' ...
Constant Arrays
Constant array is initialized by assigning it a comma-delimited sequence of valueswithin parentheses. For example:
' Declare a constant array which holds no. of days in each month:const MONTHS as byte[12] = (31,28,31,30,31,30,31,31,30,31,30,31)
Note that indexing is zero based; in the previous example, number of days inJanuary is MONTHS[0], and number of days in December is MONTHS[11].
The number of assigned values must not exceed the specified length. Vice versa ispossible, when the trailing “excess” elements will be assigned zeroes.
For more information on arrays of char, refer to Strings.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
56 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
ARRAYS
A string represents a sequence of characters, and is an equivalent to an array ofchar. It is declared like:
string[string_length]
Specifier string_length is the number of characters string consists of. String isstored internally as the given sequence of characters plus a final null character(zero). This appended “stamp” does not count against string’s total length.
A null string ("") is stored as a single null character.
You can assign string literals or other strings to string variables. String on the rightside of an assignment operator has to be the shorter of the two, or of equal length.For example:
dim msg1 as string[20]dim msg2 as string[19]
main:msg1 = "This is some message"msg2 = "Yet another message"msg1 = msg2 ' this is ok, but vice versa would be illegal
Alternately, you can handle strings element–by–element. For example:
dim s as string[5]' ...s = "mik"' s[0] is char literal "m"' s[1] is char literal "i"' s[2] is char literal "k"' s[3] is zero' s[4] is undefined' s[5] is undefined
Be careful when handling strings in this way, since overwriting the end of a stringcan cause access violations.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 57page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
STRINGS
String Splicing
mikroBasic allows you to splice strings by means of plus character (+). This kindof concatenation is applicable to string variables/literals and character variables/lit-erals. For control characters, use the mikroBasic’s built-in function Chr (e.g.Chr(13) for CR).
The result of splicing is of string type. See also Concat function.
Here is an example:
dim msg as string[100]dim res_txt as string[5]dim res, channel as word
main:
res = Adc_Read(channel) ' Get result of ADCWordToStr(res, res_txt) ' Create string out of numeric result
' Prepare message for outputmsg = "Result is" + ' Text "Result is"
Chr(13) + ' Append CR (carriage return)Chr(10) + ' Append LF (linefeed)res_txt + ' Result of ADC"." ' Append a dot
'...
Note: mikroBasic includes a String Library which automatizes string related tasks.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
58 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
A pointer is a data type which holds a memory address. While a variable accessesthat memory address directly, a pointer can be thought of as a reference to thatmemory address.
To declare a pointer data type, add a carat prefix (^) before the type. For example,if you are creating a pointer to an integer, you would write:
^integer;
To access data at the pointer’s memory location, add a carat after the variablename. For example, let’s declare variable p which points to a word, and thenassign the pointed memory location value 5:
dim p as ^word'...p^ = 5
A pointer can be assigned to another pointer. However, note that only the address,not the value, is copied. Once you modify the data located at one pointer, the otherpointer, when dereferenced, also yields modified data.
@ Operator
The @ operator returns the address of a variable or routine; that is, @ constructs apointer to its operand. The following rules apply to @:
- If X is a variable, @X returns the address of X. - If F is a routine (a function or procedure), @F returns F’s entry point (result is oflongint).
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 59page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
POINTERS
A structure represents a heterogeneous set of elements. Each element is called amember; the declaration of a structure type specifies a name and type for eachmember. The syntax of a structure type declaration is
structure structnamedim member1 as type1'...dim membern as typen
end structure
where structname is a valid identifier, each type denotes a type, and eachmember is a valid identifier. The scope of a member identifier is limited to thestructure in which it occurs, so you don’t have to worry about naming conflictsbetween member identifiers and other variables.
For example, the following declaration creates a structure type called Dot:
structure Dotdim x as floatdim y as float
end structure
Each Dot contains two members: x and y coordinates; memory is allocated whenyou instantiate the structure, like this:
dim m, n as Dot
This variable declaration creates two instances of Dot, called m and n.
A member can be of a previously defined structure type. For example:
' Structure defining a circle:structure Circle
dim radius as floatdim center as Dot
end structure
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
60 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
STRUCTURES (Under construction)
Structure Member Access
You can access the members of a structure by means of dot (.) as a direct memberselector. If we had declared variables circle1 and circle2 of the previouslydefined type Circle:
dim circle1, circle2 as Circle
we could access their individual members like this:
circle1.radius = 3.7circle1.center.x = 0circle1.center.y = 0
You can also commit assignments between complex variables, if they are of thesame type:
circle2 = circle1 ' This will copy values of all members
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 61page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Conversion of object of one type is changing it to the same object of another type(i.e. applying another type to a given object). mikroBasic supports both implicitand explicit conversions for built-in types.
Implicit Conversion
You cannot mix signed and unsigned objects in expressions with arithmetic orlogical operators. You can assign signed to unsigned or vice versa only using theexplicit conversion.
Compiler will provide an automatic implicit conversion in the followingsituations:
- statement requires an expression of particular type (according to language definition), and we use an expression of different type,
- operator requires an operand of particular type, and we use an operand of different type,
- function requires a formal parameter of particular type, and we pass it an object of different type,
- result does not match the declared function return type.
Promotion
When operands are of different types, implicit conversion promotes the less complex to more complex type taking the following steps:
byte/char -> wordshort -> integershort -> longintinteger -> longintintegral -> float
Higher bytes of extended unsigned operand are filled with zeroes. Higher bytes ofextended signed operand are filled with bit sign (if number is negative, fill higherbytes with one, otherwise with zeroes).
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
62 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
TYPES CONVERSIONS
Clipping
In assignments, and statements that require an expression of particular type,destination will store the correct value only if it can properly represent the resultof expression (that is, if the result fits in destination range).
If expression evaluates to a more complex type than expected, excess data will besimply clipped (higher bytes are lost).
dim i as bytedim j as word'...j = $FF0Fi = j ' i becomes $0F, higher byte $FF is lost
Explicit Conversion
Explicit conversion can be executed at any point by inserting type keyword (byte,word, short, integer or longint) ahead of the expression to be converted.The expression must be enclosed in parentheses. Explicit conversion can beperformed only on the operand left of the assignment operator.
Special case is the conversion between signed and unsigned types. Explicit con-version between signed and unsigned data does not change binary representationof data; it merely allows copying of source to destination.
For example:
dim a as bytedim b as short'...b = -1a = byte(b) ' a is 255, not 1
' This is because binary representation remains' 11111111; it's just interpreted differently now
You cannot execute explicit conversion on the operand left of the assignmentoperator.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 63page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
64 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Operators are tokens that trigger some computation when applied to variables andother objects in an expression.
There are four types of operators in mikroBasic:
- Arithmetic Operators- Bitwise Operators- Boolean Operators- Relational Operators
Operators Precedence and Associativity
There are 4 precedence categories in mikroBasic. Operators in the same categoryhave equal precedence with each other.
Each category has an associativity rule: left-to-right, or right-to-left. In the absenceof parentheses, these rules resolve the grouping of expressions with operators ofequal precedence.
OPERATORS
Precedence Operands Operators Associativity
4 1 @ not + - right-to-left
3 2 * /div mod and << >>
left-to-right
2 2 + - or xor left-to-right
1 2 = <> < > <= >= left-to-right
Arithmetic Operators
Arithmetic operators are used to perform mathematical computations. They havenumerical operands and return numerical results. As char operators aretechnically bytes, they can be also used as unsigned operands in arithmeticoperations. Operands need to be either both signed or both unsigned.
All arithmetic operators associate from left to right.
Operator - can be used as a prefix unary operator to change sign of a signedvalue. Unary prefix operator + can be used, but it doesn’t affect the data.
For example: b = -a
Division by Zero
If 0 (zero) is used explicitly as the second operand (i.e. x div 0), compiler willreport an error and will not generate code. But in case of implicit division by zero:x div y , where y is 0 (zero), result will be the maximum value for the appropri-ate type (for example, if x and y are words, the result will be $FFFF).
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 65page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Operator Operation Precedence
+ addition 2
- subtraction 2
* multiplication 3
/ division 3
div division, rounds down to nearest integer 3
modreturns the remainder of integer division (can-not be used with floating points) 3
Relational Operators
Use relational operators to test equality or inequality of expressions. All relationaloperators return TRUE or FALSE.
All relational operators associate from left to right.
Relational Operators in Expressions
Precedence of arithmetic and relational operators was designated in such a way toallow complex expressions without parentheses to have expected meaning:
a + 5 >= c - 1.0 / e ' i.e. (a + 5) >= (c - (1.0 / e))
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
66 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Operator Operation Precedence
= equal 1
<> not equal 1
> greater than 1
< less than 1
>= greater than or equal 1
<= less than or equal 1
Bitwise Operators
Use the bitwise operators to modify the individual bits of numerical operands.Operands need to be either both signed or both unsigned.
Bitwise operators associate from left to right. The only exception is the bitwisecomplement operator not which associates from right to left.
Bitwise operators and, or, and xor perform logical operations on appropriatepairs of bits of their operands. Operator not complements each bit of its operand.For example:
$1234 and $5678 ' equals $1230
' because ..
' $1234 : 0001 0010 0011 0100' $5678 : 0101 0110 0111 1000' ----------------------------' and : 0001 0010 0011 0000
' .. that is, $1230
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 67page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Operator Operation Precedence
andbitwise AND; returns 1 if both bits are 1, oth-erwise returns 0 3
orbitwise (inclusive) OR; returns 1 if either orboth bits are 1, otherwise returns 0 2
xorbitwise exclusive OR (XOR); returns 1 if thebits are complementary, otherwise 0 2
not bitwise complement (unary); inverts each bit 4
<<bitwise shift left; moves the bits to the left,see below 3
>>bitwise shift right; moves the bits to the right,see below 3
' Similarly:$1234 or $5678 ' equals $567C$1234 xor $5678 ' equals $444Cnot $1234 ' equals $EDCB
Unsigned and Conversions
If number is converted from less complex to more complex data type, upper bytesare filled with zeroes. If number is converted from more complex to less complexdata type, data is simply truncated (upper bytes are lost).
For example:
dim a as bytedim b as word' ...
a = $AAb = $F0F0b = b and a' a is extended with zeroes; b becomes $00A0
Signed and Conversions
If number is converted from less complex data type to more complex, upper bytesare filled with ones if sign bit is 1 (number is negative); upper bytes are filled withzeroes if sign bit is 0 (number is positive). If number is converted from more com-plex data type to less complex, data is simply truncated (upper bytes are lost).
For example:
dim a as bytedim b as word' ...
a = -12b = $70FFb = b and a
' a is sign extended, upper byte is $FF;' b becomes $70F4
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
68 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Bitwise Shift Operators
Binary operators << and >> move the bits of the left operand for a number of posi-tions specified by the right operand, to the left or right, respectively. Right operandhas to be positive and less than 255.
With shift left (<<), left most bits are discarded, and “new” bits on the right areassigned zeroes. Thus, shifting unsigned operand to the left by n positions isequivalent to multiplying it by 2n if all the discarded bits are zero. This is also truefor signed operands if all the discarded bits are equal to the sign bit.
With shift right ( >>), right most bits are discarded, and the “freed” bits on theleft are assigned zeroes (in case of unsigned operand) or the value of the sign bit(in case of signed operand). Shifting operand to the right by n positions is equiva-lent to dividing it by 2n.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 69page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Boolean Operators
Although mikroBasic does not support boolean type, you have Boolean operatorsat your disposal for building complex conditional expressions. These operatorsconform to standard Boolean logic, and return either TRUE (all ones) or FALSE(zero):
Boolean operators associate from left to right. Negation operator not associatesfrom right to left.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
70 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Operator Operation
and logical AND
or logical OR
xor logical exclusive OR
not logical negation
An expression is a sequence of operators, operands, and punctuators that returns avalue.
The primary expressions include: literals, variables, and function calls. Fromthese, using operators, more complex expressions can be created. Formally,expressions are defined recursively: subexpressions can be nested up to the limitsof memory.
Expressions are evaluated according to certain conversion, grouping, associativityand precedence rules that depend on the operators used, the presence of parenthe-ses and the data types of the operands. Precedence and associativity of the opera-tors are summarized in Operator Precedence and Associativity. The way operandsand subexpressions are grouped does not necessarily specify the actual order inwhich they are evaluated by mikroBasic.
You cannot mix signed and unsigned data types in assignment expressions or inexpressions with arithmetic or logical operators. You can use explicit conversionthough.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 71page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
EXPRESSIONS
Statements define algorithmic actions within a program. Each statement needs tobe terminated by a newline character (CR/LF).
The simplest statements include assignments, routine calls and jump statements.These can be combined to form loops, branches, and other structured statements.In the absence of specific jump and selection statements, statements are executedsequentially in order of appearance in the source code.
Statements can be roughly divided into:
- asm Statement- Assignment Statements- Conditional Statements- Iteration Statements (Loops)- Jump Statements
asm Statement
mikroBasic allows embedding assembly in the source code by means of asm state-ment. Note that you cannot use numerals as absolute addresses for register vari-ables in assembly instructions. You may use symbolic names instead (listing willdisplay these names as well as addresses).
Denote a group of assembly instructions with the keyword asm:
asmblock of assembly instructions
end asm
BASIC comments are not allowed in embedded assembly code. Instead, you mayuse one-line assembly comments starting with semicolon. If you plan to use a cer-tain BASIC variable only in the embedded assembler, be sure to at least initializeit (assign it initial value) in BASIC code; otherwise, linker will issue an error. Thisdoes not apply to predefined globals such as PORTB.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
72 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
STATEMENTS
Assignment Statements
Assignment statements have the form:
variable = expression
The statement evaluates the expression and assigns its value to the variable.All rules of the implicit conversion apply. Variable can be any declared variableor array element, and expression can be any expression.
Do not confuse the assignment with the relational operator = which tests for equal-ity. mikroBasic will interpret the meaning of the character = from the context.
Conditional Statements
Conditional or selection statements select from alternative courses of action bytesting certain values. There are two types of selection statements in mikroBasic:if and select case.
If Statement
Use the keyword if to implement a conditional statement. Syntax of the if state-ment has the form:
if expression thenstatements
[elseother statements]
end if
When expression evaluates to true, statements execute. If the expressionis false, other statements execute. The expression must convert to aboolean type; otherwise, the condition is ill-formed. The else keyword with analternate block of statements (other statements) is optional.
Nested if statements require additional attention. General rule is that the nestedconditionals are parsed starting from the innermost conditional, with each elsebound to the nearest available if on its left.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 73page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Select Case Statement
Use the select case statement to pass control to a specific program branch,based on a certain condition. The select case statement consists of a selectorexpression (a condition) and a list of possible values. Syntax of select case
statement is:
select case selectorcase value_1
statements_1...case value_n
statements_n[case else
default_statements]end select
The selector is an expression which should evaluate as integral value. Thevalues can be literals, constants, or expressions, and statements can be anystatements. The case else clause is optional.
First, the selector expression (condition) is evaluated. The select case state-ment then compares it against all the available values. If the match is found, thestatements following the match evaluate, and select case statement termi-nates. In case that there are multiple matches, the first matching statement willbe executed. If none of the values matches the selector, then thedefault_statements in the case else clause (if there is one) are executed.
Here is a simple example of select case statement:
select case operatorcase "+"
res = n1 + n2case "-"
res = n1 - n2case else
res = 0cnt = cnt + 1
end select
Also, you can group values together for a match. Simply separate the values bycommas. Note that select case statements can be nested – values are thenassigned to the innermost enclosing select case statement.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
74 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Iteration Statements (Loops)
Iteration statements let you loop a set of statements. There are three forms of itera-tion statements in mikroBasic: for, while and do.
You can use the statements break and continue to control the flow of a loopstatement. The break terminates the statement in which it occurs, whilecontinue begins executing the next iteration of the sequence.
For Statement
The for statement implements an iterative loop and requires you to specify thenumber of iterations. Syntax of for statement is:
for counter = initial_value to final_value [step step_value]statements
next counter
The counter is a variable which increases by step_value with each iteration ofthe loop. Parameter step_value is an optional integral value, and defaults to 1 ifomitted. Before the first iteration, counter is set to the initial_value and willincrement until it reaches (or exceeds) the final_value. With each iteration,statements will be executed.
The initial_value and final_value should be expressions compatible withthe counter; statements can be any statements that do not change the value ofcounter. Note that parameter step_value may be negative, allowing you to create acountdown.
Here is an example of calculating scalar product of two vectors, a and b, of lengthn, using for statement:
s = 0for i = 0 to n
s = s + a[i] * b[i]next i
The for statement results in an endless loop if the final_value equals orexceeds the range of counter’s type.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 75page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
While Statement
Use the while keyword to conditionally iterate a statement. Syntax of whilestatement is:
while expressionstatements
wend
The statements are executed repeatedly as long as the expression evaluatestrue. The test takes place before the statements are executed. Thus, if expres-sion evaluates false on the first pass, the loop does not execute. Here is an exam-ple of calculating scalar product of two vectors, using the while statement:
s = 0i = 0while i < n
s = s + a[i] * b[i]i = i + 1
wend
Do Statement
The do statement executes until the condition becomes true. Syntax of do state-ment is:
dostatements
loop until expression
The statements are executed repeatedly until the expression evaluates true.The expression is evaluated after each iteration, so the loop will executestatements at least once. Here is an example of calculating scalar product oftwo vectors, using the do statement:
s = 0i = 0do
s = s + a[i] * b[i]i = i + 1
loop until i = n
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
76 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Jump Statements
A jump statement, when executed, transfers control unconditionally. There are fivesuch statements in mikroBasic: break, continue, exit, goto and gosub.
Break Statement
Sometimes, you might need to stop the loop from within its body. Use breakwithin loops to pass control to the first statement following the innermost loop(for, while or do).
For example:
' Wait for CF card to be plugged; refresh every secondwhile true
Lcd_Out(1, 1, "No card inserted")if Cf_Detect() = 1 then
breakend ifDelay_ms(1000)
wend
' Now we can work with CF card ...Lcd_Out(1, 1, "Card detected ")
Continue Statement
You can use the continue statement within loops to “skip the cycle”:
- continue statement in for loop moves program counter to the line withkeyword for; it does not change the loop counter,
- continue statement in while loop moves program counter to the line withloop condition (top of the loop),
- continue statement in do loop moves program counter to the line withloop condition (bottom of the loop).
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 77page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Exit Statement
The exit statement allows you to break out of a routine (function or procedure).It passes the control to the first statement following the routine call.
Here is a simple example:
sub procedure Proc1()dim error as byte
... ' we're doing something hereif error = TRUE then
exitend if... ' some code, which won't be executed if error is true
end sub
Note: If breaking out of a function, return value will be the value of the localvariable result at the moment of exit.
Goto Statement
Use the goto statement to unconditionally jump to a local label — for more infor-mation, refer to Labels. Syntax of goto statement is:
goto label_name
This will transfer control to the location of a local label specified by label_name.The goto line can come before or after the label. It is not possible to jump into orout of routine.
You can use goto to break out from any level of nested control structures. Neverjump into a loop or other structured statement, since this can have unpredictableeffects.
Use of goto statement is generally discouraged as practically every algorithm canbe realized without it, resulting in legible structured programs. One possible appli-cation of goto statement is breaking out from deeply nested control structures.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
78 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Gosub Statement
Use the gosub statement to unconditionally jump to a local label — for moreinformation, refer to Labels. Syntax of gosub statement is:
gosub label_name...label_name:...return
This will transfer control to the location of a local label specified by label_name.Also, the calling point is remembered. Upon encountering a return statement,program execution will continue with the next statement (line) after the gosub.The gosub line can come before or after the label.
It is not possible to jump into or out of routine by means of gosub. Never jumpinto a loop or other structured statement, since this can have unpredictable effects.
Note: Like with goto, use of gosub statement is generally discouraged.mikroBasic supports gosub only for the sake of backward compatibility. It is bet-ter to rely on functions and procedures, creating legible structured programs.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
79 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Any line in source code with a leading # is taken as a compiler directive. The ini-tial # can be preceded or followed by whitespace (excluding new lines). Compilerdirectives are not case sensitive.
You can use conditional compilation to select particular sections of code to com-pile while excluding other sections. All compiler directives must be completed inthe source file in which they begun.
Directives #DEFINE and #UNDEFINE
Use directive #DEFINE to define a conditional compiler constant (“flag”). You canuse any identifier for a flag, with no limitations. No conflicts with program identi-fiers are possible, as flags have a separate name space. Only one flag can be setper directive.
For example: #DEFINE extended_format
Use #UNDEFINE to undefine (“clear”) previously defined flag.
Directive #IFDEF
Conditional compilation is carried out by the #IFDEF directive. The #IFDEF testswhether a flag is currently defined or not; that is, whether a previous #DEFINEdirective has been processed for that flag and is still in force.
Directive #IFDEF is terminated by the #ENDIF directive, and can have any num-ber of #ELSEIF clauses and an optional #ELSE clause:
#IFDEF flag THENblock of code
[ #ELSEIF flag_1 THENblock of code 1
...#ELSEIF flag_n THEN
block of code n ][ #ELSE
alternate block of code ]#ENDIF
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
80 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
COMPILER DIRECTIVES
First, #IFDEF checks if the flag is set by means of #DEFINE. If so, only block ofcode will be compiled. Otherwise, compiler will check flags flag_1 .. flag_nand execute the appropriate block of code i. Eventually, if none of the flags isset, alternate block of code in the #ELSE (if any) will be compiled.
The #ENDIF ends the conditional sequence. The result of the preceding scenario isthat only one section of code (possibly empty) is passed on for further processing.The processed section can contain further conditional clauses, nested to any depth;each #IFDEF must be matched with a closing #ENDIF.
Here is an example:
' Uncomment the appropriate flag for your application:'#DEFINE resolution8'#DEFINE resolution10'#DEFINE resolution12
#IFDEF resolution8 THEN... ' code specific to 8-bit resolution
#ELSEIF resolution10 THEN... ' code specific to 10-bit resolution
#ELSEIF resolution12 THEN... ' code specific to 12-bit resolution
#ELSE... ' default code
#ENDIF
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 81page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Predefined Flags
mikroBasic has several predefined flags for configuring hardware. These can befound in definition files (“defs” folder), specifying hardware settings for individualchips. SFR are sorted under categories: ___SFR (umbrella for all registers),___CONFIG_OSC (oscillator), ___CONFIG_WDT (Watchdog timer), and ___CON-FIG_BORPOR (brown–out reset and power–on–timer).
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
82 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
CHAPTER
mikroElektronika: DDevelopment ttools - BBooks - CCompilers
4
mikroBasicLibraries
mikroBasic provides a number of built-in and library routines which can help youdevelop your applications faster and easier. Libraries for ADC, UART, SPI, I2C,LCD, GLCD, PWM, MMC/SD, numeric formatting, and many other are includedalong with practical, ready-to-use code examples.
mikroBasic compiler provides a set of useful built-in utility functions. Built-inroutines can be used in any part of the project.
Currently, mikroBasic includes following built-in functions:
LoHiChrOrdSetBitClearBitTestBitIncDecClock_KhzClock_Mhz
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
84 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
BUILT-IN ROUTINES
Prototype sub function Lo(dim number as longint) as word
Returns Lower 16 bits (word) of number.
Description Function returns lower word of number. Function does not interpret bit patterns ofnumber – it merely returns lower 16 bits as found in register.
Example a = Lo(0xAC10F4) ' Equals 0x10F4
Lo
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 85page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub function Hi(dim number as longint) as word
Returns Higher 16 bits (word) of number.
Description Function returns higher word of number. Function does not interpret bit patterns ofnumber – it merely returns higher 16 bits as found in register.
Example a = Hi(0xAC10F4) ' Equals $00AC
Hi
Prototype sub function Chr(dim code as byte) as char
Returns Returns a character associated with the specified character code.
Description Function returns a character associated with the specified character code. Numbersfrom 0 to 31 are the standard non-printable ASCII codes.
Example c = Chr(10) ' returns a linefeed character
Chr
Prototype sub function Ord(dim character as char) as byte
Returns ASCII code of the character.
Description Function returns ASCII code of the character.
Example c = Ord("A") ' returns 65
Ord
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
86 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure SetBit(dim byref register as word, dim rbit asword)
Description Function sets the bit rbit of register. Parameter rbit needs to be a variable or liter-al with value 0..15. See Predefined Globals and Constants for more information.
Example tBit(PORTB, 2) ' Set RB2
SetBit
Prototype sub procedure ClearBit(dim byref register as word, dim rbit asword)
Description Function clears the bit rbit of register. Parameter rbit needs to be a variable or lit-eral with value 0..15. See Predefined Globals and Constants for more information.
Example ClearBit(PORTC, 7) ' Clear RC7
ClearBit
Prototype sub function TestBit(dim register, rbit as word) as word
Returns If the bit is set, returns 1, otherwise returns 0.
Description Function tests if the bit rbit of register is set. If set, function returns 1, otherwisereturns 0. Parameter rbit needs to be a variable or literal with value 0..15. SeePredefined Globals and Constants for more information on register identifiers.
Example flag = TestBit(PORTE, 2) ' 1 if RE2 is set, otherwise 0
TestBit
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 87page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Inc(dim byref par as longint)
Description Increases parameter par by 1.
Example p = 4Inc(p) ' p is now 5
Inc
Prototype sub procedure Dec(dim byref par as longint)
Description Decreases parameter par by 1.
Example p = 4Dec(p) ' p is now 3
Dec
Prototype sub function Clock_Khz as longint
Returns Device clock in KHz.
Description Returns device clock in KHz, rounded to the nearest integer.
Example clk = Clock_Khz()
Clock_Khz
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
88 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub function Clock_Mhz as word
Returns Device clock in MHz.
Description Returns device clock in MHz, rounded to the nearest integer.
Example clk = Clock_Mhz()
Clock_Mhz
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 89page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
mikroBasic provides a set of libraries which simplify the initialization and use ofdsPIC and its modules: Library functions do not require any header files to beincluded; you can use them anywhere in your projects.
Currently available libraries are:
- ADC Library- Compact Flash Library- I2C Library- Keypad Library- LCD Library (4-bit interface)- LCD Library (8-bit interface)- Graphic LCD Library- Multi Media Card Library- PS/2 Library- PWM Library- Secure Digital Library- Software I2C Library- Software SPI Library- Software UART Library- SPI Library- UART Library- Util Library
- Conversions Library- Math Library- Delays Library- String Library- DSP Library
LIBRARY ROUTINES
ADC (Analog to Digital Converter) module is available with all dsPIC chips.Library function Adc_Read is included to provide you comfortable work with themodule.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
90 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
ADC Library
Prototype sub function Adc_Read(dim channel as byte) as word
Returns Depending on chip, function reads 10-bit or 12-bit unsigned value from the specifiedchannel.
Description Initializes dsPIC’s internal ADC module and reads value from channel. Conversiontakes 32 Tcy. Refer to the appropriate datasheet for channel-to-pin mapping.
You don’t need to configure ports manually for using the module; library will take careof the initialization.
Example tmp = Adc_Read(1) ' Read analog value from channel 1
Adc_Read
Library Example
The following code code snippet reads analog value from channel 2 and displays iton PORTD.
program adc_test
main:TRISD = 0 ' PORTD is outputwhile TRUE
PORTD = Adc_Read(2) ' Send results to PORTDwend
end.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 91page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
+5V
+5V 10MHz10
K
Reset
RG15RC1RC2RC3RC4
RG6RG7RG8MCLR
RG9VssVddRA12RA13
RB5
RB4RB3RB2RB1RB0
RC14RC13RD0
RD11RD10
RD9RD8
RA15RA14
VssRC15
OSC1/CLKIVddRG2
RG3
RF6RF7RF8RF2RF3
RB
6R
B7
RA
9R
A10
AV
dd
AV
ss
RB
8R
B9
RB
10
RB
11
Vss
Vdd
RB
12
RB
13
RB
14
RB
15
RD
14
RD
15
RF
4R
F5
RG
13
RG
12
RG
14
RA
7R
A6
RG
0R
G1
RF
1R
F0
Vdd
Vss
RD
7R
D6
RD
5
RD
4
RD
13
RD
12
RD
3R
D2
RD
1
dsPIC30F6014
330
330
330
330
330
330
330
330
330
330
330
330
LD11
LD10
LD9
LD8
LD7
LD6
LD5
LD4
LD3
LD2
LD1
LD0
Hardware Connection
Compact Flash Library provides routines for accessing data on Compact Flashcard (abbrev. CF further in text). CF cards are widely used memory elements,commonly found in digital cameras. Great capacity (8MB ~ 2GB, and more) andexcellent access time of typically few microseconds make them very attractive formicrocontroller applications.
In CF card, data is divided into sectors, one sector usually comprising 512 bytes(few older models have sectors of 256B). Read and write operations are not per-formed directly, but successively through 512B buffer. Following routines can beused for CF with FAT16, and FAT32 file system. Note that routines for file han-dling can be used only with FAT16 file system.
Important! Before write operation, make sure you don’t overwrite boot or FATsector as it could make your card on PC or digital cam unreadable. Drive mappingtools, such as Winhex, can be of a great assistance.
Cf_InitCf_DetectCf_Total_SizeCf_EnableCf_DisableCf_Read_InitCf_Read_ByteCf_Read_WordCf_Write_InitCf_Write_ByteCf_Write_Word
Cf_Find_FileCf_File_Write_InitCf_File_Write_ByteCf_Read_SectorCf_Write_SectorCf_Set_File_Date
Cf_File_Write_Complete
Function Cf_Set_Reg_Adr is for compiler internal purpose only.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
92 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Compact Flash Library
Library Routines
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 93page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Cf_Init(dim byref WR,RD,A2,A1,A0,RY,CE,CD as bit,dim byref dataport as word)
Description Initializes microcontroller ports appropriately for communication with CF card. Specifythe dataport; parameters WR, RD, A2, A1, A0, RY, CE, CD can be any available pins.Use LAT exclusively for these parameters.
Example Cf_Init(LATD.4, LATD.3, LATD.2, LATD.1, LATD.0, LATG.14, LATG.13,LATG.15, LATB)
Cf_Init
Prototype sub function Cf_Detect as byte
Returns Returns 1 if CF is present, otherwise returns 0.
Description Checks for presence of CF card on ctrlport.
Requires Ports must be initialized. See Cf_Init.
Example ' Wait until CF card is inserted:do
noploop until Cf_Detect() = 1
Cf_Detect
Prototype sub function Cf_Total_Size as logint
Returns Card size in kilobytes.
Description Returns the size of the Compact Flash card in kilobytes.
Example size = Cf_Total_Size()
Cf_Total_Size
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
94 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure Cf_Read_Init(dim address as longint, dim sectcnt asbyte)
Description Initializes CF card for reading. Parameter address specifies sector address from wheredata will be read, and sectcnt is total number of sectors prepared for read operation.
Requires Ports must be initialized. See Cf_Init.
Example Cf_Read_Init(590, 1)
Cf_Read_Init
Prototype sub procedure Cf_Disable
Description Routine disables the device and frees the data line for other devices. To enable thedevice again, call Cf_Enable. These two routines in conjuction allow you to free/occu-py data line when working with multiple devices. Check the example at the end of thechapter.
Requires Ports must be initialized. See Cf_Init.
Example Cf_Disable()
Cf_Disable
Prototype sub procedure Cf_Enable
Description Enables the device. Routine needs to be called only if you have disabled the device bymeans of Cf_Disable. These two routines in conjuction allow you to free/occupy dataline when working with multiple devices. Check the example at the end of the chapter.
Requires Ports must be initialized. See Cf_Init.
Example Cf_Enable()
Cf_Enable
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 95page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub function Cf_Read_Byte as byte
Returns Returns byte from CF.
Description Reads one byte from CF.
Requires CF must be initialized for read operation. See Cf_Read_Init.
Example PORTC = Cf_Read_Byte()
Cf_Read_Byte
Prototype sub procedure Cf_Write_Init(dim address as longint, dim sectcntas byte)
Description Initializes CF card for writing. Parameter address specifies sector address where datawill be stored, and sectcnt is total number of sectors prepared for write operation.
Requires Ports must be initialized. See Cf_Init.
Example Cf_Write_Init(590, 1)
Cf_Write_Init
Prototype sub function Cf_Read_Word as word
Returns Returns word (16-bit) from CF.
Description Reads one word from CF.
Requires CF must be initialized for read operation. See Cf_Read_Init.
Example PORTC = Cf_Read_Word()
Cf_Read_Word
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
96 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure Cf_Write_Byte(dim data as byte)
Description Writes one byte (data) to CF. All 512 bytes are transferred to a buffer.
Requires CF must be initialized for write operation. See Cf_Write_Init.
Example Cf_Write_Byte(100)
Cf_Write_Byte
Prototype sub procedure Cf_Write_Word(dim data as word)
Description Writes one word (data) to CF. All 512 bytes are transferred to a buffer.
Requires CF must be initialized for write operation. See Cf_Write_Init.
Example Cf_Write_Word(100)
Cf_Write_Word
Prototype sub procedure Cf_Find_File(dim find_first as byte, dim byreffile_name as string[11])
Description Routine looks for files on CF card. Parameter find_first can be TRUE or FALSE; ifTRUE, routine looks for the first file on card, in order of physical writing. Otherwise,routine “moves forward” to the next file from the current position, again in physicalorder. If file is found, routine writes its name and extension in the string file_name. If nofile is found, the string will be filled with zeroes.
Requires Ports must be initialized. See Cf_Init.
Example Cf_Find_File(TRUE, file)if file[0] <> 0 then...' if first file found, handle it
Cf_Find_File
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 97page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Cf_File_Write_Byte(dim data as byte)
Description Adds one byte (data) to file. You can supply ASCII value as parameter, for example 48for zero.
Requires CF must be initialized for file write operation. See Cf_File_Write_Init.
Example ' Write 50000 zeroes (bytes) to file:for i = 0 to 50000
Cf_File_Write_Byte(48)Inc(i)
next i
Cf_File_Write_Byte
Prototype sub procedure Cf_File_Write_Init
Description Initializes CF card for file writing operation (FAT16 only).
Requires Ports must be initialized. See Cf_Init.
Example Cf_File_Write_Init()
Cf_File_Write_Init
Prototype sub procedure Cf_Read_Sector(dim sector_number as word, dim byrefbuffer as byte[512])
Description Reads one sector (sector_number) into buffer.
Requires Ports must be initialized. See Cf_Init.
Example Cf_Read_Sector(22, data)
Cf_Read_Sector
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
98 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure Cf_File_Write_Complete(dim byref filename aschar[8], dim byref extension as char[3])
Description Finalizes writing to file. Upon all data has be written to file, use this function to closethe file and make it readable. Parameter filename must be 8 character long in uppercase.Don’t forget to append a timestamp with Cf_Set_File_Date before finalizing a file.
Requires CF must be initialized for file write operation. See Cf_File_Write_Init.
Example Cf_File_Write_Complete("MY_FILE1", "TXT")
Cf_File_Write_Complete
Prototype sub procedure Cf_Write_Sector(dim sector_number as word, dimbyref buffer as byte[512])
Description Writes value from buffer to CF sector at sector_number.
Requires Ports must be initialized. See Cf_Init.
Example Cf_Write_Sector(22, data)
Cf_Write_Sector
Prototype sub procedure Cf_Set_File_Date(dim year as word, dim month, day,hours, min, sec as byte)
Description Writes system timestamp to a file. Use this routine before finalizing a file; otherwise,file will be appended a random timestamp.
Requires CF must be initialized for file write operation. See Cf_File_Write_Init.
Example Cf_Set_File_Date(2005,4,1,18,7,0) ' April 1st 2005, 18:07:00
Cf_Set_File_Date
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 99page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Library Examples
The following example demonstrates working with the Compact Flash Library:
program cf_testdim i, m as word
sub procedure My_InitCf_Init(LATD.4,LATD.3,LATD.2,LATD.1,LATD.0,LATG.14,LATG.13,LATG.15,LATB)ADPCFG = $FFFF ' PORTB is digital!' Wait to plug the Compact Flash carddo
noploop until Cf_Detect() = 1Delay_ms(200)
end sub
sub procedure My_Write_ByteCf_Write_Init(590, 1) ' Initialize writing to sector 590Delay_ms(50)i = 0while i < 512
Cf_Write_Byte(i)Inc(i)
wendend sub
sub procedure My_Read_ByteCf_Read_Init(590, 1)Delay_ms(50)i = 0while i < 512
m = Cf_Read_Byte()Delay_ms(100)LATF = mInc(i)
wendend sub
' continues ..
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
100 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
' .. continued
main:TRISF = 0PORTF = 0My_Init()My_Write_Byte()My_Read_Byte()while TRUE
nopwend
end.
+5V
Compact Flash Connector
(TOP VIEW)
Compact Flash Card
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
25
21
22
23
24
17
18
19
20
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
50
46
47
48
49
42
43
44
45
+5V
10K
RG15 RB3
RB4
RB5
RB6
RB7
RG13
RD3
RD4
RG14
RD2
RD1
RD0
RB0
RB1
RB2
dsPIC
HW Connection
mikroBasic provides library which supports the master I²C mode.
I2C_InitI2C_StartI2C_Repeated_StartI2C_Is_IdleI2C_RdI2C_WrI2C_Stop
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 101page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
I2C Library
Library Routines
Prototype sub procedure I2C_Init(const clock as longint)
Description Initializes I2C with the desired clock (refer to device data sheet for correct values inrespect with Fosc). Needs to be called before using other functions of I2C Library. Youdon’t need to configure ports manually for using the module; library will take care ofthe initialization.
Example I2C_Init(100000)
I2C_Init
Prototype function I2C_Start : byte;
Returns If there is no error, function returns 0.
Description Determines if I²C bus is free and issues START signal.
Requires I²C must be configured before using this function. See I2C_Init.
Example if I2C_Start() = 0 then...
I2C_Start
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
102 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure I2C_Repeated_Start
Description Issues repeated START signal.
Requires I²C must be configured before using this function. See I2C_Init.
Example I2C_Repeated_Start()
I2C_Repeated_Start
Prototype sub function I2C_Is_Idle as byte
Returns Returns 1 if I²C bus is free, otherwise returns 0.
Description Tests if I²C bus is free.
Requires I²C must be configured before using this function. See I2C_Init.
Example if I2C_Is_Idle() then...
I2C_Is_Idle
Prototype sub function I2C_Rd(dim ack as byte) as byte
Returns Returns one byte from the slave.
Description Reads one byte from the slave, and sends not acknowledge signal if parameter ack is 0,otherwise it sends acknowledge.
Requires START signal needs to be issued in order to use this function. See I2C_Start.
Example tmp = I2C_Rd(0) ' Read data and send not acknowledge signal
I2C_Rd
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 103page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub function I2C_Wr(dim data as byte) as byte
Returns Returns 0 if there were no errors.
Description Sends data byte (parameter data) via I²C bus.
Requires START signal needs to be issued in order to use this function. See I2C_Start.
Example I2C_Write(0xA3)
I2C_Wr
Prototype sub procedure I2C_Stop
Description Issues STOP signal.
Requires I²C must be configured before using this function. See I2C_Init.
I2C_Stop
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
104 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
This code demonstrates working with the I2C Library. Program sends data to 24c02 EEPROM,which is connected to dsPIC. Then, we read the data via I²C from EEPROM and send its value toPORTF, to check if the cycle was successful. See the figure below for interfacing 24c02 to dsPIC.
program i2c_test
dim data as word
sub procedure I2C_Ee_Write(dim chip_adr, ee_adr, ee_data as word)dim address as word
address = chip_adr ' Calculating theaddress = address << 1 ' right sequence foraddress = address or 0xA1 ' writing addressI2C_Start() ' Issue I2C start signalI2C_Write(address) ' Send byte via I2C(command to 24cOx)I2C_Write(ee_adr) ' Send byte(address for EEPROM)I2C_Write(ee_data) ' Send data(data that will be written)I2C_Stop() ' Issue I2C stop signal
end sub
sub function I2C_Ee_Read(dim chip_adr, ee_adr as word) as worddim address as word
address = chip_adr ' Calculating theaddress = address << 1 ' right sequence foraddress = address or 0xA0 ' writing addressI2C_Init(100000) ' Initialize I2C system clockI2C_Start() ' Issue I2C start signalI2C_Write(address) ' Send byte via I2C(command to 24cOx)I2C_Write(ee_adr) ' Send byte(address for EEPROM)result = I2C_Read()I2C_Stop() ' Issue I2C stop signal
end sub
main:TRISD = 0LATD = 0I2C_Init(100000) ' Initialize I2C system clockI2C_Ee_Write(1, 1, 65)data = I2C_Ee_Read(1, 1)LATD = data ' Output data on PORTF
while TRUEnop
wendend.
Library Example
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 105page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
6MHz
+5V
+5V
1
2
3
4
8
7
6
5
A0
A1
NC
GND
Vcc
WP
SCL
SDA
24C04
+5V
+5V
10K
10K
10K
Reset
dsP
IC30F2010
RB0
RB2
RB3
RB4
RB5
Vss
OSC1/CLKI
RC15
RC13
RC14
Vdd
RD1
MCLR
RB1
Avss
RE1
RE2
RE3
RE4
RE5
Vdd
Vss
RF2
RF3
RE8
RD0
AVdd
RE0
HW Connection
mikroBasic provides library for working with 4x4 keypad; routines can also beused with 4x1, 4x2, or 4x3 keypad. Check the connection scheme at the end of thetopic.
Keypad_InitKeypad_ReadKeypad_Released
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
106 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Keypad Library
Library Routines
Prototype sub procedure Keypad_Init(dim byref port as word)
Description Initializes port to work with keypad. The procedure needs to be called before using otherroutines from Keypad library.
Example Keypad_Init(PORTB)
Keypad_Init
Prototype sub function Keypad_Read as byte
Returns 1..16, depending on the key pressed, or 0 if no key is pressed.
Description Checks if any key is pressed. Function returns 1 to 16, depending on the key pressed, or0 if no key is pressed.
Requires Port needs to be appropriately initialized; see Keypad_Init.
Example kp = Keypad_Read()
Keypad_Read
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 107page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub function Keypad_Released as byte
Returns 1..16, depending on the key.
Description Call to Keypad_Released is a blocking call: function waits until any key is pressedand released. When released, function returns 1 to 16, depending on the key.
Requires Port needs to be appropriately initialized; see Keypad_Init.
Example kp = Keypad_Released()
Keypad_Released
The following code can be used for testing the keypad. It supports keypads with 1 to 4 rows and 1to 4 columns. The code returned by the keypad functions (1..16) is transformed into ASCII codes[0..9,A..F]. In addition, a small single-byte counter displays the total number of keys pressed inthe second LCD row.
program keypad_test
dim kp, cnt as bytedim txt as string[5]
main:cnt = 0Keypad_Init(LATF)Lcd_Init(LATD.11, LATD.10, LATB) ' Initialize LCD on PORTCLcd_Cmd(LCD_CLEAR) ' Clear displayLcd_Cmd(LCD_CURSOR_OFF) ' Cursor off
Lcd_Out(1, 1, "Key :")Lcd_Out(2, 1, "Times:")
' continues ..
Library Example
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
108 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
' .. continued
dokp = 0while kp = 0 ' Wait for key to be pressed
kp = Keypad_Released() ' or: kp = Keypad_Released()wend
select case kp ' Prepare value for outputcase 1
kp = 49 ' 1case 2
kp = 50 ' 2case 3
kp = 51 ' 3case 4
kp = 65 ' Acase 5
kp = 52 ' 4case 6
kp = 53 ' 5case 7
kp = 54 ' 6case 8
kp = 66 ' Bcase 9
kp = 55 ' 7case 10
kp = 56 ' 8case 11
kp = 57 ' 9case 12
kp = 67 ' Ccase 13
kp = 42 ' *case 14
kp = 48 ' 0case 15
kp = 35 ' #case 16
kp = 68 ' Dend select
Inc(cnt)Lcd_Chr(1, 12, kp) ' print it on LCDWordToStr(cnt, txt)Lcd_Out(2, 8, txt)
loop until TRUEend.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 109page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
RG
15
RC
1R
C2
RC
3R
C4
RG
6R
G7
RG
8M
CLR
RG
9V
ss
Vdd
RA
12
RA
13
RB
5
RB
4R
B3
RB
2R
B1
RB
0
RC
14
RC
13
RD
0R
D11
RD
10
RD
9R
D8
RA
15
RA
14
Vss
RC
15
OS
C1/C
LK
IV
dd
RG
2
RG
3
RF
6R
F7
RF
8R
F2
RF
3
RB6RB7RA9RA10AVdd
AVssRB8RB9RB10
RB11VssVddRB12RB13
RB14
RB15RD14RD15RF4RF5
RG13RG12RG14
RA7RA6
RG0RG1RF1RF0
VddVss
RD7RD6RD5
RD4
RD13RD12RD3RD2RD1
dsP
IC30F6014
T3
T2
T1
T7
T6
T5
T11
T10
T9
T15
T14
T13
T4
T8
T12
T16
HW Connection
mikroBasic provides a library for communicating with commonly used LCD (4-bitinterface). Figures showing HW connection of dsPIC and LCD are given at theend of the chapter.
Note: Be sure to designate ports with LCD as output, before using any of the fol-lowing library functions.
Lcd_InitLcd_Init_LoLcd_OutLcd_Out_CpLcd_ChrLcd_Chr_CpLcd_Cmd
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
110 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
LCD Library (4-bit interface)
Library Routines
Prototype sub procedure Lcd_Init(dim byref en, rs as bit, dim byrefdataport as word)
Description Initializes LCD at dataport with the following pin settings:D3 -> dataport.7, D2 -> dataport.6, D1 -> dataport.5, D0 -> dataport.4
Parameters en and rs can be any available pin on any port. Use LAT exclusively forparameters. Check the connection scheme at the end of the chapter.
Example Lcd_Init(LATC.14, LATC.13, LATB)
Lcd_Init
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 111page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Lcd_Out(dim row, col as word, dim text asstring[20])
Description Prints text on LCD at the specified row and column (parameters row and col). Bothstring variables and literals can be passed as text.
Requires Port with LCD must be initialized. See Lcd_Init.
Example Lcd_Out(1, 3, "Hello!") ' Print "Hello!" at line 1, char 3
Lcd_Out
Prototype sub procedure Lcd_Out_Cp(dim text as string[20])
Description Prints text on LCD at the current cursor position. Both string variables and literals canbe passed as text.
Requires Port with LCD must be initialized. See Lcd_Init.
Example Lcd_Out_Cp("Here!") ' Print "Here!" at current cursor position
Lcd_Out_Cp
Prototype sub procedure Lcd_Init_Lo(dim byref en, rs as bit, dim byrefdataport as word)
Description Initializes LCD at dataport with the following pin settings:D3 -> dataport.3, D2 -> dataport.2, D1 -> dataport.1, D0 -> dataport.0
Parameters en and rs can be any available pin on any port. Use LAT exclusively forparameters. Check the connection scheme at the end of the chapter.
Example Lcd_Init_Lo(LATC.14, LATC.13, LATB)
Lcd_Init_Lo
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
112 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure Lcd_Chr_Cp(dim character as byte)
Description Prints character on LCD at current cursor position. Both variables and literals can bepassed as character.
Requires Port with LCD must be initialized. See Lcd_Init.
Example Lcd_Chr_Cp("e") ' Print "e" at the current cursor position
Lcd_Chr_Cp
Prototype sub procedure Lcd_Cmd(dim command as word)
Description Sends command to LCD. You can pass one of the predefined constants to the function.The complete list of available commands is shown on the following page.
Requires Port with LCD must be initialized. See Lcd_Config or Lcd_Init.
Example Lcd_Cmd(LCD_Clear) ' Clear LCD display
Lcd_Cmd
Prototype sub procedure Lcd_Chr(dim row, col, character as word)
Description Prints character on LCD at the specified row and column (parameters row and col).Both variables and literals can be passed as character.
Requires Port with LCD must be initialized. See Lcd_Init.
Example Lcd_Out(2, 3, "i") ' Print "i" at line 2, char 3
Lcd_Chr
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 113page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
LCD Commands
LCD Command Purpose
LCD_FIRST_ROW Move cursor to 1st row
LCD_SECOND_ROW Move cursor to 2nd row
LCD_THIRD_ROW Move cursor to 3rd row
LCD_FOURTH_ROW Move cursor to 4th row
LCD_CLEAR Clear display
LCD_RETURN_HOMEReturn cursor to home position, returns a shifted display to original posi-tion. Display data RAM is unaffected.
LCD_CURSOR_OFF Turn off cursor
LCD_UNDERLINE_ON Underline cursor on
LCD_BLINK_CURSOR_ON Blink cursor on
LCD_MOVE_CURSOR_LEFT Move cursor left without changing display data RAM
Lcd_Move_Cursor_Right Move cursor right without changing display data RAM
LCD_TURN_ON Turn LCD display on
LCD_TURN_OFF Turn LCD display off
LCD_SHIFT_LEFT Shift display left without changing display data RAM
LCD_SHIFT_RIGHT Shift display right without changing display data RAM
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
114 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Library Example (default pin settings)
Hardware Connection
program lcd_test ' continually prints results of AD conversion on LCDdim i as worddim h as string[5]main:
Lcd_Init(LATD.11, LATD.10, LATB) ' LCD init and prepsLcd_Cmd(LCD_FIRST_ROW)Lcd_Cmd(LCD_CURSOR_OFF)Lcd_Out(1, 1, "Result ADC:")while TRUE
Lcd_Cmd(LCD_SECOND_ROW) ' Position to LCD line 2i = Adc_Read(10) ' Get results of ADCWordToHex(i, h) ' Format result for outputLcd_Out_Cp(h) ' Print resut on LCDDelay_ms(10)
wendend.
1R/W D4ERS D3D2D1D0 D7D6D5VeeVddVss
+5V
LC
Dco
ntr
ast
PIN1PIN0 PIN3PIN2
dsPIC MCU
any port (with 8 pins)
m i k r o e l E k t r o n i k a
Data PortControl Port
PIN0 PIN3PIN2
RS
E
R/W
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 115page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
mikroBasic provides a library for communicating with commonly used 8-bit inter-face LCD (with Hitachi HD44780 controller). Figures showing HW connection ofdsPIC and LCD are given at the end of the chapter.
Note: Be sure to designate ports with LCD as output, before using any of the fol-lowing library functions.
Lcd8_InitLcd8_OutLcd8_Out_CpLcd8_ChrLcd8_Chr_CpLcd8_Cmd
LCD Library (8-bit interface)
Library Routines
Prototype sub procedure Lcd8_Init(dim byref en, rs as bit, dim byrefdataport as word)
Description Initializes LCD at dataport with following pin settings:
D7 -> dataport.7D6 -> dataport.6D5 -> dataport.5D4 -> dataport.4D3 -> dataport.3D2 -> dataport.2D1 -> dataport.1D0 -> dataport.0
Parameters en and rs can be any available pin on any port. Use LAT exclusively forparameters. Check the connection scheme at the end of the chapter.
Example Lcd8_Init(LATC.14, LATC.13, LATB)
Lcd8_Init
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
116 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure Lcd8_Out(dim row, col as word, dim textas string[20])
Description Prints text on LCD at the specified row and column (parameters row and col). Bothstring variables and literals can be passed as text.
Requires Ports with LCD must be initialized. See Lcd8_Init.
Example Lcd8_Out(1, 3, 'Hello!'); ' Print "Hello!" at line 1, char 3
Lcd8_Out
Prototype sub procedure Lcd8_Out_Cp(dim text as string[20])
Description Prints text on LCD at the current cursor position. Both string variables and literals canbe passed as text.
Requires Ports with LCD must be initialized. See Lcd8_Init.
Example Lcd8_Out_Cp("Here!") ' Print "Here!" at current cursor position
Lcd8_Out_Cp
Prototype sub procedure Lcd8_Chr(dim row, col, character as word)
Description Prints character on LCD at the specified row and column (parameters row and col).Both variables and literals can be passed as character.
Requires Ports with LCD must be initialized. See Lcd8_Init.
Example Lcd8_Out(2, 3, "i") ' Print "i" at line 2, char 3
Lcd8_Chr
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 117page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Lcd8_Chr_Cp(dim character as byte)
Description Prints character on LCD at the current cursor position. Both variables and literals canbe passed as character.
Requires Ports with LCD must be initialized. See Lcd8_Init.
Example Lcd8_Chr_Cp("e") ' Print "e" at current cursor position
Lcd8_Chr_Cp
Prototype sub procedure Lcd8_Cmd(dim command as word)
Description Sends command to LCD. You can pass one of the predefined constants to the function.The complete list of available commands is on the page 113.
Requires Ports with LCD must be initialized. See Lcd8_Init.
Example Lcd8_Cmd(LCD_Clear) ' Clear LCD display
Lcd8_Cmd
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
118 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Library Example (default pin settings)
Hardware Connection
program lcd8_test; ' continually prints results of AD conversion on LCDdim i as worddim h as string[5]main:
Lcd8_Init(LATD.11, LATD.10, LATB) ' LCD init and prepsLcd8_Cmd(LCD_FIRST_ROW)Lcd8_Cmd(LCD_CURSOR_OFF)Lcd8_Out(1, 1, "Result ADC:")while TRUE
Lcd8_Cmd(LCD_SECOND_ROW) ' Position to LCD line 2i = Adc_Read(10) ' Get results of ADCWordToHex(i, h) ' Format result for outputLcd8_Out_Cp(h) ' Print resut on LCDDelay_ms(10)
wendend.
1R/W D4ERS D3D2D1D0 D7D6D5VeeVddVss
+5V
LC
Dco
ntr
ast
PIN1 PIN7PIN0 PIN6PIN5PIN4PIN3PIN2
dsPIC MCU
any port (with 8 pins)
m i k r o e l E k t r o n i k a
Data PortControl Port
PIN0 PIN3PIN2
RS
E
R/W
mikroBasic provides a library for drawing and writing on Graphic LCD. Theseroutines work with the common GLCD 128x64.
Note: Be sure to designate port with GLCD as output, before using any of the fol-lowing library procedures or functions.
Basic routines:
Glcd_InitGlcd_DisableGlcd_Set_SideGlcd_Set_PageGlcd_Set_XGlcd_Read_DataGlcd_Write_Data
Advanced routines:
Glcd_FillGlcd_DotGlcd_LineGlcd_V_LineGlcd_H_LineGlcd_RectangleGlcd_BoxGlcd_CircleGlcd_Set_FontGlcd_Write_CharGlcd_Write_TextGlcd_ImageGlcd_Partial_Image
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 119page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
GLCD Library
Library Routines
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 120page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Glcd_Init(dim byref cs1, cs2, rs, rw, rst, en asbit, dim byref dataport as word)
Description Initializes GLCD at Data port (parameter dataport) with the pin settings you specify.Parameters cs1, cs2, rs, rw, rst, and en should all point to different pins. This proce-dure needs to be called before using other routines of GLCD library.
Example Glcd_Init(LATD.8, LATD.9, LATD.10, LATD.3, LATG.12, LATD.11,LATB)
Glcd_Init
Prototype sub procedure Glcd_Set_Side(dim x as byte)
Description Selects side of GLCD, left or right. Parameter x specifies the side: values from 0 to 63specify the left side, and values higher than 64 specify the right side. Use the functionsGlcd_Set_Side, Glcd_Set_X, and Glcd_Set_Page to specify an exact position onGLCD. Then, you can use Glcd_Write_Data or Glcd_Read_Data on that location.
Requires GLCD needs to be initialized. See Glcd_Init.
Example Glcd_Set_Side(0); ' Select the left side of GLCD
Glcd_Set_Side
Prototype sub procedure Glcd_Disable
Description Routine disables the device and frees the data line for other devices. To enable thedevice again, call any of the library routines; no special command is required.
Requires GLCD needs to be initialized. See Glcd_Init.
Example Glcd_Disable()
Glcd_Disable
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 121page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Glcd_Set_Page(dim page as byte)
Description Selects page of GLCD, technically a line on display; parameter page can be 0..7.
Requires GLCD needs to be initialized. See Glcd_Init.
Example Glcd_Set_Page(5)
Glcd_Set_Page
Prototype sub procedure Glcd_Set_X(dim x as byte)
Description Positions to x dots from the left border of GLCD within the given page.
Requires GLCD needs to be initialized. See Glcd_Init.
Example Glcd_Set_X(25)
Glcd_Set_X
Prototype sub function Glcd_Read_Data as byte
Returns One word from the GLCD memory.
Description Reads data from from the current location of GLCD memory. Use the functionsGlcd_Set_Side, Glcd_Set_X, and Glcd_Set_Page to specify an exact position onGLCD. Then, you can use Glcd_Write_Data or Glcd_Read_Data on that location.
Requires Reads data from from the current location of GLCD memory.
Example tmp = Glcd_Read_Data()
Glcd_Read_Data
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 122page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Glcd_Write_Data(dim data as byte)
Description Writes data to the current location in GLCD memory and moves to the next location.
Requires GLCD needs to be initialized. See Glcd_Init.
Example Glcd_Write_Data(data)
Glcd_Write_Data
Prototype sub procedure Glcd_Fill(dim pattern as byte)
Description Fills the GLCD memory with byte pattern. To clear the GLCD screen, useGlcd_Fill(0); to fill the screen completely, use Glcd_Fill($FF).
Requires GLCD needs to be initialized. See Glcd_Init.
Example Glcd_Fill(0) ' Clear screen
Glcd_Fill
Prototype sub procedure Glcd_Dot(dim x, y, color as byte)
Description Draws a dot on the GLCD at coordinates (x, y). Parameter color determines the dotstate: 0 clears dot, 1 puts a dot, and 2 inverts dot state.
Requires GLCD needs to be initialized. See Glcd_Init.
Example Glcd_Dot(0, 0, 2) ' Invert the dot in the upper left corner
Glcd_Dot
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 123page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Glcd_Line(dim x1, y1, x2, y2, color as byte)
Description Draws a line on the GLCD from (x1, y1) to (x2, y2). Parameter color determinesthe dot state: 0 draws an empty line (clear dots), 1 draws a full line (put dots), and 2draws a “smart” line (invert each dot).
Requires GLCD needs to be initialized. See Glcd_Init.
Example Glcd_Line(0, 63, 50, 0, 2)
Glcd_Line
Prototype sub procedure Glcd_V_Line(dim y1, y2, x, color as byte)
Description Similar to GLcd_Line, draws a vertical line on the GLCD from (x, y1) to(x, y2).
Requires GLCD needs to be initialized. See Glcd_Init.
Example Glcd_V_Line(0, 63, 0, 1)
Glcd_V_Line
Prototype sub procedure Glcd_H_Line(dim x1, x2, y, color as byte)
Description Similar to GLcd_Line, draws a horizontal line on the GLCD from (x1, y) to (x2, y).
Requires GLCD needs to be initialized. See Glcd_Init.
Example Glcd_H_Line(0, 127, 0, 1)
Glcd_H_Line
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 124page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Glcd_Rectangle(dim x1, y1, x2, y2, color as byte)
Description Draws a rectangle on the GLCD. Parameters (x1, y1) set the upper left corner,(x2, y2) set the bottom right corner. Parameter color defines the border: 0 draws anempty border (clear dots), 1 draws a solid border (put dots), and 2 draws a “smart” bor-der (invert each dot).
Requires GLCD needs to be initialized. See Glcd_Init.
Example Glcd_Rectangle(10, 0, 30, 35, 1)
Glcd_Rectangle
Prototype sub procedure Glcd_Box(dim x1, y1, x2, y2, color as byte)
Description Draws a box on the GLCD. Parameters (x1, y1) set the upper left corner, (x2, y2)set the bottom right corner. Parameter color defines the fill: 0 draws a white box (cleardots), 1 draws a full box (put dots), and 2 draws an inverted box (invert each dot).
Requires GLCD needs to be initialized. See Glcd_Init.
Example Glcd_Box(10, 0, 30, 35, 1)
Glcd_Box
Prototype sub procedure Glcd_Circle(dim x, y, radius, color as integer)
Description Draws a circle on the GLCD, centered at (x, y) with radius. Parameter color defines thecircle line: 0 draws an empty line (clear dots), 1 draws a solid line (put dots), and 2draws a “smart” line (invert each dot).
Requires GLCD needs to be initialized. See Glcd_Init.
Example Glcd_Circle(63, 31, 25, 1)
Glcd_Circle
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 125page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Glcd_Write_Char(dim character, x, page,color as byte)
Description Prints character at page (one of 8 GLCD lines, 0..7), x dots away from the left border ofdisplay. Parameter color defines the “fill”: 0 writes a “white” letter (clear dots), 1 writesa solid letter (put dots), and 2 writes a “smart” letter (invert each dot).
Use routine Glcd_Set_Font to specify font, or the default 5x7 font (included with thelibrary) will be used.
Requires GLCD needs to be initialized, see Glcd_Init. Use the Glcd_Set_Font to specify thefont for display; if no font is specified, the default 5x8 font supplied with the library willbe used.
Example Glcd_Write_Char("C", 0, 0, 1)
Glcd_Write_Char
Prototype sub procedure Glcd_Set_Font(dim font_address as longint, dimfont_width, font_height as byte, dim font_offset as word)
Description Sets the font for text display routines, Glcd_Write_Char and Glcd_Write_Text.Font needs to be formatted as an array of byte. Parameter font_address specifies theaddress of the font; you can pass a font name with the @ operator. Parametersfont_width and font_height specify the width and height of characters in dots. Fontwidth should not exceed 128 dots, and font height should not exceed 8 dots. Parameterfont_offset determines the ASCII character from which the supplied font starts.Demo fonts supplied with the library have an offset of 32, which means that they startwith space.
If no font is specified, Glcd_Write_Char and Glcd_Write_Text will use the default5x8 font supplied with the library. You can create your own fonts by following theguidelines given in the file “GLCD_Fonts.dbas”. This file contains the default fonts forGLCD, and is located in your installation folder, “Extra Examples” > “GLCD”.
Requires GLCD needs to be initialized. See Glcd_Init.
Example ' Use the custom 5x7 font "myfont" which starts with space (32):Glcd_Set_Font(@myfont, 5, 7, 32)
Glcd_Set_Font
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
126 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure Glcd_Write_Text(dim text as char[20], dim x, page,color as byte)
Description Prints text at page (one of 8 GLCD lines, 0..7), x dots away from the left border ofdisplay. Parameter color defines the “fill”: 0 prints a “white” letters (clear dots), 1prints solid letters (put dots), and 2 prints “smart” letters (invert each dot).
Use routine Glcd_Set_Font to specify font, or the default 5x7 font (included with thelibrary) will be used.
Requires GLCD needs to be initialized, see Glcd_Init. Use the Glcd_Set_Font to specify thefont for display; if no font is specified, the default 5x8 font supplied with the library willbe used.
Example Glcd_Write_Text("Hello world!", 0, 0, 1)
Glcd_Write_Text
Prototype sub procedure Glcd_Image(dim image as byte[1024])
Description Displays bitmap image on the GLCD. Parameter image should be formatted as an arrayof 1024 bytes. Use the mikroBasic’s integrated Bitmap-to-LCD editor (menu optionTools > Graphic LCD Editor) to convert image to a constant array suitable for displayon GLCD.
Requires GLCD needs to be initialized. See Glcd_Init.
Example Glcd_Image(my_image)
Glcd_Image
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 127page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Glcd_Partial_Image(dim x1, y1, x2, y2, color asbyte, dim image as byte[1024])
Description Displays partial bitmap image on the GLCD. Parameter image should be formatted asan array of 1024 bytes. Parameters (x1, y1) set the upper left corner, and (x2, y2) setthe lower right corner of the clip. Parameter color defines the fill: 0 draws a “white”image (clear dots), 1 draws a “black” image (put dots), and 2 draws an inverted image(invert each dot). Use the mikroBasic’s integrated Bitmap-to-LCD editor (menu optionTools > Graphic LCD Editor) to convert image to a constant array suitable for displayon GLCD.
Requires GLCD needs to be initialized. See Glcd_Init.
Example Glcd_Partial_Image(0, 0, 32, 64, 1, my_image)
Glcd_Partial_Image
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
128 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Library Example
The following example is a simple demonstration of GLCD Library:
program glcd_testdim j, k as word
main:ADPCFG = 0xFFFFTBLPAG = 0Glcd_Init(LATD.8, LATD.9, LATD.10, LATD.3, LATG.12, LATD.11, LATB)Glcd_Fill(0xAA)Delay_ms(2000)
' Set font for displaying textGlcd_Set_Font(@FontSystem5x8, 5, 8, 32)
while TRUE
' Draw circlesGlcd_Fill(0) ' Clear screenGlcd_Write_Text("Circles", 0, 0, 1)j = 4while j < 31
Glcd_Circle(63, 31, j, 2)j = j + 4
wendDelay_ms(4000)
' Draw LinesGlcd_Fill(0) ' Clear screenGlcd_Write_Text("Lines", 0, 0, 1)for j = 0 to 15
k = j*4 + 3Glcd_Line(0, 0, 127, k, 2)
next jfor j = 0 to 31
k = j*4 + 3Glcd_Line(0, 63, k, 0, 2)
next jDelay_ms(4000)
wendend.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 129page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
118K
GN
D
Vcc
Ve
e
RS
R/W
ED0
D1
D2
D3
D4
D5
D6
D7
+ 5V
10k
10
KS0108 GLCD Test
"Hello world"
mikroElektronika
CS
2
RE
SE
T
VO
UT
CS
1
GND
Hardware Connection
The Multi Media Card (MMC) is a flash memory memory card standard. MMCcards are currently available in sizes up to and including 1 GB, and are used incell phones, mp3 players, digital cameras, and PDAs.
mikroBasic provides a library for accessing data on Multi Media Card via SPIcommunication.
Mmc_InitMmc_Read_SectorMmc_Write_SectorMmc_Read_CidMmc_Read_Csd
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
130 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Multi Media Card Library
Library Routines
Prototype sub function Mmc_Init(dim byref cs as bit) as word
Returns Returns 0 if MMC card is present and successfully initialized, otherwise returns 1.
Description Initializes hardware SPI communication; parameter cs designates the CS line for com-munication. The function returns 0 if MMC card is present and successfully initialized,otherwise returns 1. Mmc_Init needs to be called before using other functions of thislibrary.
Example error = Mmc_Init(LATC.2) ' Init with CS line at RC2
Mmc_Init
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 131page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub function Mmc_Read_Sector(dim sector as longint, dim byrefdata as byte[512]) as byte
Returns Returns 0 if read was successful, or 1 if an error occurred.
Description Function reads one sector (512 bytes) from MMC card at sector address sector. Readdata is stored in the array data. Function returns 0 if read was successful, or 1 if anerror occurred.
Requires Library needs to be initialized, see Mmc_Init.
Example error = Mmc_Read_Sector(sector, data)
Mmc_Read_Sector
Prototype sub function Mmc_Write_Sector(dim sector as longint, dim byrefdata as byte[512]) as byte
Returns Returns 0 if write was successful; returns 1 if there was an error in sending write com-mand; returns 2 if there was an error in writing.
Description Function writes 512 bytes of data to MMC card at sector address sector. Functionreturns 0 if write was successful, or 1 if there was an error in sending write command,or 2 if there was an error in writing.
Requires Library needs to be initialized, see Mmc_Init.
Example error = Mmc_Write_Sector(sector, data)
Mmc_Write_Sector
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
132 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub function Mmc_Read_Cid(dim byref data_for_registers asbyte[512]) as byte
Returns Returns 0 if read was successful, or 1 if an error occurred.
Description Function reads CID register and returns 16 bytes of content intodata_for_registers.
Requires Library needs to be initialized, see Mmc_Init.
Example error = Mmc_Read_Cid(data)
Mmc_Read_Cid
Prototype sub function Mmc_Read_Csd(dim byref data_for_registers asbyte[512]) as byte
Returns Returns 0 if read was successful, or 1 if an error occurred.
Description Function reads CSD register and returns 16 bytes of content intodata_for_registers.
Requires Library needs to be initialized, see Mmc_Init.
Example error = Mmc_Read_Csd(data)
Mmc_Read_Csd
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 133page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Library Example
The following code tests MMC library routines. First, we fill the buffer with 512 “M” charactersand write it to sector 56; then we repeat the sequence with character “E” at sector 56. Finally, weread the sectors 55 and 56 to check if the write was successful.
program mmc_testdim tmp as bytedim i as worddim data as byte[512]
main:Uart1_Init(9600)
tmp = Mmc_Init(LATF.5) ' Initialize ports
for i = 0 to 512 ' Fill the buffer with the "M" characterdata[i] = "M"
next i
tmp = Mmc_Write_Sector(55, data) ' Write it to MMC card, sector 55
for i = 0 to 512 ' Fill the buffer with the "E" characterdata[i] = "E"
next i
tmp = Mmc_Write_Sector(56, data) ' Write it to MMC card, sector 56
'** Verify: **
tmp = Mmc_Read_Sector(55, data) ' Read from sector 55
if tmp = 0 then ' Send 512 bytes from buffer to UARTfor i = 0 to 512
Uart1_Write_Char(data[i])next i
end if
tmp = Mmc_Read_Sector(56, data) ' Read from sector 56
if tmp = 0 then ' Send 512 bytes from buffer to UARTfor i = 0 to 512
Uart1_Write_Char(data[i])next i
end ifend.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
134 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Hardware Connection
3K
32K
2
3K
32K
2
3K
32K
2
IC1
MC33269-3.3
IN OUT
GND
+5V
+3V3
+
100nF +
22uF
Data_OUT
GND
CLK
+3V3
GND
Data_IN
/CS
MMC
SV18MHz
+5V
+5V
10K
Reset
dsP
IC30F2010
RB0
RB2
RB3
RB4
RB5
Vss
OSC1/CLKI
RC15
RC13
RC14
Vdd
RD1
MCLR
RB1
Avss
RE1
RE2
RE3
RE4
RE5
Vdd
Vss
RF2
RF3
RE8
RD0
AVdd
RE0
Back view
1 2 3 4 5 6 7
MMC
mikroBasic provides a library for communicating with common PS/2 keyboard.The library does not utilize interrupts for data retrieval, and requires oscillatorclock to be 6MHz and above.
Please note that:
- The pins to which a PS/2 keyboard is attached should be connected to pull-up resistors.
- Although PS/2 is a two-way communication bus, this library does not provide PIC-to-keyboard communication; e.g. the Caps Lock LED will not turn on if you press the Caps Lock key.
Ps2_InitPs2_Key_Read
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 135page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
PS/2 Library
Library Routines
Prototype sub procedure Ps2_Init(dim byref data, clock as bit)
Description Initializes the chip for work with PS/2 keyboard, with custom pin settings. Parametersclock and data specify the pins for Clock line and Data line, respectively; the twocannot point to the same pin. You need to call Ps2_Init before using other routines ofPS/2 library.
Requires Both Data and Clock lines need to be in pull-up mode.
Example Ps2_Init(LATD.8, LATD.9)
Ps2_Init
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
136 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub function Ps2_Key_Read(dim byref value, special, pressed asbyte) as byte
Returns Returns 1 if reading of a key from the keyboard was successful, otherwise 0.
Description The procedure retrieves information about key pressed.
Parameter value holds the value of the key pressed. For characters, numerals, punctua-tion marks, and space, value will store the appropriate ASCII value. Procedure “recog-nizes” the function of Shift and Caps Lock, and behaves appropriately.
Parameter special is a flag for special function keys (F1, Enter, Esc, etc). If keypressed is one of these, special will be set to 1, otherwise 0.
Parameter pressed is set to 1 if the key is pressed, and 0 if released.
Requires PS/2 keyboard needs to be initialized; see Ps2_Init.
Example ' Press Enter to continue:while TRUE
if Ps2_Key_Read(val, spec, press) = 1 thenif (val = 13) and (spec = 1) then breakend if
end ifwend
Ps2_Key_Read
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 137page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Library Example
This simple example reads values of keys pressed on PS/2 keyboard and sends them via USART.
program ps2_test
dim keydata, special, down as word
main:ADPCFG = 0xFFFF ' PORTB to be digital on 30F6014keydata = 0special = 0down = 0
Ps2_Init(LATB.0, LATB.1)Uart1_Init(9600)Delay_ms(100) ' Wait for keyboard to finishUart1_Write_Text("You can type now!") ' Ready
while TRUEif Ps2_Key_Read(keydata, special, down) = 1 then
if (down <> 0) and (keydata = 16) thenUart1_Write_Char(keydata)
elseif (down <> 0) and (keydata = 13) then
' Send CR/LF sequence on "Enter" pressedUart1_Write_Char(13)Uart1_Write_Char(10)
end ifelse
if (down <> 0) and (special = 0) and (keydata <> 0) thenUart1_Write_Char(keydata)
end ifend if
end ifDelay_ms(10) ' debounce
wendend.
mikroBasic provides library for PWM. These routines are supported by all chipswith Motor Control PWM module. Library works with all PWM modules.
Note: Some dsPIC’s don’t have channel 4.
Pwm_InitPwm_StartPwm_Set_DutyPwm_StopPwm_Calc_Period
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
138 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
PWM Library
Library Routines
Prototype sub procedure Pwm_Init(dim freq_hz, pair_output_mode,enable_output_x, clock_prescale_output_postscale as word)
Description Procedure configures the PWM module with the following parameters:
- Parameter freq_hz is a desired PMW frequency in Hz.
- Parameter pair_output_mode sets the pair output mode (independent or comple-mentary) for each of the 4 PWM modules. It should contain 4 bits, in this order<pwm4.pwm3.pwm2.pwm1>, where each bit sets the mode for the appropriate module:0 - independent, 1 - complementary.
- Parameter enable_output_x configures individual bits of PWM modules. It contains8 bits, in this order <pin4H.pin3H.pin2H.pin1H.pin4L.pin3L.pin2L.pin1L>,where each bit configures the appropriate bit: 0 - disabled, pin is standard I/O; 1 -enabled, pin is PWM output.
continued on the following page ..
Pwm_Init
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 139page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Description(continued)
- Parameter clock_prescale_output_postscale sets both clock prescale and out-put postscale values in one byte. Lower nibble sets the output postscaler: 0 correspondsto 1:1, 1 -> 1:2, 2 -> 1:3, …, 15 -> 1:16. Higher nibble sets the clock prescaler: 0 corre-sponds to 1:1, 1 -> 1:4, 2 -> 1:16, 3 -> 1:64.
For example, to set the postscaler to 1:11, we need lower nibble to be 10 ($A); for theprescaler to be 1:4, we need higher nibble to be 1. Together, they form value $1A(%00011010) for parameter clock_prescale_output_postscale.
Requires Library supports all dsPIC’s with Motor Control PWM module. This routine configuresthe PWM module; to actually start the module, use the Pwm_Start.
Example constFREQUENCY = 4321 ' PWM frequency in HzALL_COMPLEMENTARY = %1111 ' channel outputs are complementaryENABLE_ALL_CHANNELS = 0xFF ' turn on all PWM channelsPRESCALE_POSTSCALE = 0x2D ' prescaler = 1:16, postscaler = 1:14
main:' Initalize PWM modulesPwm_Init(FREQUENCY, ALL_COMPLEMENTARY,
ENABLE_ALL_CHANNELS, PRESCALE_POSTSCALE)
Prototype sub procedure Pwm_Set_Duty(dim duty, channel as word)
Description Procedure updates the dutycycle register. Parameter duty sets the duty cycle; 0 fornone, and for other values consult the appropriate dsPIC datasheet. Parameter channelselects the desired channel: 1..4. (Note that some dsPICs don’t have channel 4.)
Example Pwm_Set_Duty(0xFF, 2)
Pwm_Set_Duty
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
140 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure Pwm_Start
Description Starts PWM.
Requires You need a CCP unit on PORTC to use this library. To use this function, unit needs to beinitalized – see Pwm_Init.
Example Pwm_Start()
Pwm_Start
Prototype sub procedure Pwm_Stop
Description Stops PWM.
Requires To use this function, module needs to be started – see Pwm_Start.
Example Pwm_Stop()
Pwm_Stop
Prototype sub function Pwm_Calc_Period(dim freq_hz, prescaler as word) asword
Description This is an auxiliary function used to calculate the value for PTPER register, given adesired frequency in Hz (parameter freq_hz) and a prescaler. See the description of thePwm_Init for setting up the prescaler parameter.
Function returns the value calculated by the formula:PTPER = -1 + FCY/(Fpwm * prescaler)
Requires The routine is used internally by the library, and is not intended for the end users.
Example Pwm_Calc_Period(1200, 0)
Pwm_Calc_Period
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 141page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Library Example
The example changes PWM duty ratio continually. The program has been tested with P30F3011,@10MHz, External oscillator, ECPLL 8x, EasyDsPIC2 board. You should also be able to monitorchanges on LED connected to the PWM module pin.
program Pwm_Test
constFREQUENCY = 4321 ' PWM frequency in HzALL_COMPLEMENTARY = %1111 ' channel outputs are complementaryENABLE_ALL_CHANNELS = 0xFF ' turn on all PWM channelsPRESCALE_POSTSCALE = 0x00 ' prescaler = 1:1, postscaler = 1:1
dim newduty as word
main:newduty = 0x1FF
Delay_ms(5000)
' Initalize PWM modulesPwm_Init(FREQUENCY,ALL_COMPLEMENTARY,ENABLE_ALL_CHANNELS,PRESCALE_POSTSCALE)
' Set different duty cycles for all channelsPwm_Set_Duty(0x000F, 1)Pwm_Set_Duty(0x001F, 2)Pwm_Set_Duty(0x002F, 3)' some dsPIC's do not have channel 4'Pwm_Set_Duty(0x003F, 4)
' Start PWMPwm_Start()
' Change duty in a loopwhile TRUE
Pwm_Set_Duty(newduty, 1)Delay_ms(10)Inc(newduty)if newduty >= 0x4FF then
newduty = 0xFend if
wendend.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
142 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Hardware Connection
6MHz
+5V
+5V
10K
Reset
dsP
IC30F2010
RB0
RB2
RB3
RB4
RB5
Vss
OSC1/CLKI
RC15
RC13
RC14
Vdd
RD1
MCLR
RB1
Avss
RE1
RE2
RE3
RE4
RE5
Vdd
Vss
RF2
RF3
RE8
RD0
AVdd
RE0330R
Secure Digital (SD) is a flash memory memory card standard, based on the olderMulti Media Card (MMC) format. SD cards are currently available in sizes up toand including 2 GB, and are used in cell phones, mp3 players, digital cameras, andPDAs.
mikroBasic provides a library for accessing data on Secure Digital Card via SPIcommunication.
Sd_InitSd_Read_SectorSd_Write_SectorSd_Read_CidSd_Read_Csd
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 143page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Secure Digital Library
Library Routines
Prototype sub function Sd_Init(dim byref cs as bit) as word
Returns Returns 0 if SD card is present and successfully initialized, otherwise returns 1.
Description Initializes hardware SPI communication; parameters port and pin designate the CS lineused in the communication (parameter pin should be 0..7). The function returns 0 if SDcard is present and successfully initialized, otherwise returns 1. Sd_Init needs to becalled before using other functions of this library.
Example error = Sd_Init(LATC.2) ' Init with CS line at RC2
Sd_Init
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
144 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub function Sd_Read_Sector(dim sector as longint, dim byref dataas byte[512]) as byte
Returns Returns 0 if read was successful, or 1 if an error occurred.
Description Function reads one sector (512 bytes) from SD card at sector address sector. Readdata is stored in the array data. Function returns 0 if read was successful, or 1 if anerror occurred.
Requires Library needs to be initialized, see Sd_Init.
Example error = Sd_Read_Sector(sector, data)
Sd_Read_Sector
Prototype sub function Sd_Write_Sector(dim sector as longint, dim byrefdata as byte[512]) as byte
Returns Returns 0 if write was successful; returns 1 if there was an error in sending write com-mand; returns 2 if there was an error in writing.
Description Function writes 512 bytes of data to SD card at sector address sector. Function returns 0if write was successful, or 1 if there was an error in sending write command, or 2 ifthere was an error in writing.
Requires Library needs to be initialized, see Sd_Init.
Example error = Sd_Write_Sector(sector, data)
Sd_Write_Sector
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 145page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub function Sd_Read_Cid(dim byref data_for_registers asbyte[512]) as byte
Returns Returns 0 if read was successful, or 1 if an error occurred.
Description Function reads CID register and returns 16 bytes of content intodata_for_registers.
Requires Library needs to be initialized, see Sd_Init.
Example error = Sd_Read_Cid(data)
Sd_Read_Cid
Prototype sub function Sd_Read_Csd(dim byref data_for_registers asbyte[512]) as byte
Returns Returns 0 if read was successful, or 1 if an error occurred.
Description Function reads CSD register and returns 16 bytes of content intodata_for_registers.
Requires Library needs to be initialized, see Sd_Init.
Example error = Sd_Read_Csd(data)
Sd_Read_Csd
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
146 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Library Example
The following code tests SD library routines. First, we fill the buffer with 512 “M” characters andwrite it to sector 56; then we repeat the sequence with character “E” at sector 56. Finally, we readthe sectors 55 and 56 to check if the write was successful.
program sd_test
dim tmp as bytedim i as worddim data as byte[512]
main:
Uart1_Init(9600)tmp = Sd_Init(LATF.5) ' Initialize ports
for i = 0 to 512 ' Fill the buffer with the "M" characterdata[i] = "M"
next i
tmp = Sd_Write_Sector(55, data) ' Write it to SD card, sector 55
for i = 0 to 512 ' Fill the buffer with the "E" characterdata[i] = "E"
next i
tmp = Sd_Write_Sector(56, data) ' Write it to SD card, sector 56
'** Verify: **tmp = Sd_Read_Sector(55, data) ' Read from sector 55
if tmp = 0 then ' Send 512 bytes from buffer to UARTfor i = 0 to 512
Uart1_Write_Char(data[i])next i
end if
tmp = Sd_Read_Sector(56, data) ' Read from sector 56
if tmp = 0 then ' Send 512 bytes from buffer to UARTfor i = 0 to 512
Uart1_Write_Char(data[i])next i
end ifend.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 147page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Hardware Connection
3K
32K
2
3K
32K
2
3K
32K
2
IC1
MC33269-3.3
IN OUT
GND
+5V
+3V3
+
100nF +
22uF
8MHz
+5V
+5V
10K
Reset
dsP
IC30F2010
RB0
RB2
RB3
RB4
RB5
Vss
OSC1/CLKI
RC15
RC13
RC14
Vdd
RD1
MCLR
RB1
Avss
RE1
RE2
RE3
RE4
RE5
Vdd
Vss
RF2
RF3
RE8
RD0
AVdd
RE0
Data_OUT
GND
CLK
+3V3
GND
Data_IN
/CS
SD
mikroBasic provides routines which implement software I²C. These routines arehardware independent and can be used with any MCU. Software I2C Libraryenables you to use MCU as Master in I²C communication. Multi-master mode isnot supported.
Note: This library implements time-based activities, so interrupts need to be dis-abled when using Soft I2C.
Soft_I2C_InitSoft_I2C_StartSoft_I2C_ReadSoft_I2C_WriteSoft_I2C_Stop
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
148 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Software I2C Library
Library Routines
Prototype sub procedure Soft_I2C_Init(dim byref sda, sck as bit)
Description Configures software I²C. Parameters sda and sck specify the SDA and SCK pins,repectively; parameters cannot point at the same pin.
Soft_I2C_Init needs to be called before using other functions from Soft I²C Library.
Example Soft_I2C_Init(LATD.8, LATD.9)
Soft_I2C_Init
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 149page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Soft_I2C_Start
Description Issues START signal. Needs to be called prior to sending and receiving data.
Requires Soft I²C must be configured before using this function. See Soft_I2C_Init.
Example Soft_I2C_Start()
Soft_I2C_Start
Prototype sub function Soft_I2C_Read(dim ack as byte) as byte
Returns Returns one byte from the slave.
Description Reads one byte from the slave, and sends not acknowledge signal if parameter ack is 0,otherwise it sends acknowledge.
Requires START signal needs to be issued in order to use this function. See Soft_I2C_Start.
Example tmp = Soft_I2C_Read(0)
Soft_I2C_Read
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
150 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub function Soft_I2C_Write(dim data as byte) as byte
Returns Returns 0 if there were no errors.
Description Sends data byte (parameter data) via I²C bus.
Requires START signal needs to be issued in order to use this function. See Soft_I2C_Start.
Example Soft_I2C_Write(0xA3)
Soft_I2C_Write
Prototype sub procedure Soft_I2C_Stop
Description Issues STOP signal.
Requires START signal needs to be issued in order to use this function. See Soft_I2C_Start.
Example Soft_I2C_Stop()
Soft_I2C_Stop
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 151page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Library Example
The example demonstrates use of Software I²C Library. dsPIC is connected (SCL, SDA pins) to24C02 EEPROM. Program sends data to EEPROM (data is written at address 2). Then, we readdata via I²C from EEPROM and send its value to PORTC, to check if the cycle was successful.
Check the hardware connection scheme at hardware I2C Library.
program i2c_test
dim ee_adr, ee_data as bytedim jj as word
main:
Soft_I2C_Init(LATG.2, LATG.3) ' Initialize full master modeTRISC = 0 ' PORTC is outputPORTC = 0xFF ' Initialize PORTCSoft_I2C_Start() ' Issue I2C start signalSoft_I2C_Write(0xA2) ' Send byte via I2C(command to 24cO2)ee_adr = 2Soft_I2C_Write(ee_adr) ' Send byte(address for EEPROM)ee_data = 0xAASoft_I2C_Write(ee_data) ' Send data(data that will be written)Soft_I2C_Stop() ' Issue I2C stop signal
for jj = 0 to 65500 ' Pause while EEPROM writes datanop
next jj
Soft_I2C_Start() ' Issue I2C start signalSoft_I2C_Write(0xA2) ' Send byte via I2Cee_adr = 2Soft_I2C_Write(ee_adr) ' Send byte(address for EEPROM)Soft_I2C_Start() ' Issue I2Csignal repeated startSoft_I2C_Write(0xA3) ' Send byte(request data from EEPROM)ee_data = Soft_I2C_Read(0) ' Read the dataSoft_I2C_Stop() ' Issue I2C_stop signalPORTC = ee_data ' Display data on PORTC
while TRUEnop
wend
end.
mikroBasic provides library which implement software SPI. These routines arehardware independent and can be used with any MCU. You can easily communi-cate with other devices via SPI: A/D converters, D/A converters, MAX7219,LTC1290, etc.
The library configures SPI to master mode, clock = 50kHz; other settings are cus-tomizable.
Note: These functions implement time-based activities, so interrupts need to bedisabled when using the library.
Soft_Spi_InitSoft_Spi_ReadSoft_Spi_Write
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
152 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Software SPI Library
Library Routines
Prototype sub procedure Soft_Spi_Init(dim byref sdi, sdo, sck as bit, dimprescaler, clock_idle, edge_select, spi_mode as word)
Description(continues)
Configures and initializes software SPI. Parameters sdi, sdo, and sck specify the pinsSDI, SDO, and SCK, respectively. These parameters cannot point at the same pin.
Parameter prescaler determines the frequency divider (base prescaler), and can havethe following values:
const _SOFT_SPI_PRESCALER_2 = 1 ' Prescaler set to 1:2const _SOFT_SPI_PRESCALER_4 = 2 ' Prescaler set to 1:4const _SOFT_SPI_PRESCALER_8 = 3 ' Prescaler set to 1:8const _SOFT_SPI_PRESCALER_16 = 4 ' Prescaler set to 1:16const _SOFT_SPI_PRESCALER_32 = 5 ' Prescaler set to 1:32const _SOFT_SPI_PRESCALER_64 = 6 ' Prescaler set to 1:64const _SOFT_SPI_PRESCALER_128 = 7 ' Prescaler set to 1:128const _SOFT_SPI_PRESCALER_256 = 8 ' Prescaler set to 1:256
continues ..
Soft_Spi_Init
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 153page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Description(continued)
.. continued
Parameter clock_idle determines idle state for clock; can have the following values:
const _SOFT_SPI_IDLE_LO = 0 ' Clock idle LOWconst _SOFT_SPI_IDLE_HI = 1 ' Clock idle HIGH
Parameter edge_select can have the following values:
const _SOFT_SPI_HI_2_LO = 1 ' transmit on high to low edgeconst _SOFT_SPI_LO_2_HI = 0 ' transmit on low to high edge
Parameter spi_mode sets the message format and can have the following values:
const _SOFT_SPI_MODE_8 = 8 ' Sets SPI mode to 8-bitconst _SOFT_SPI_MODE_16 = 16 ' Sets SPI mode to 16-bit
Soft_Spi_Init needs to be called before using other functions from Soft SPI Library.
Example Soft_Spi_Init(LATB.2, LATB.3, LATB.6, 7, _SOFT_SPI_IDLE_HI,_SOFT_SPI_LO_2_HI, _SOFT_SPI_MODE_16)
Prototype sub function Soft_Spi_Read(dim buffer as byte) as byte
Returns Returns the received data.
Description Provides clock by sending buffer and receives data.
Requires Soft SPI must be initialized and communication established before using this function.See Soft_Spi_Init.
Example tmp = Soft_Spi_Read(buffer)
Soft_Spi_Read
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
154 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure Soft_Spi_Write(dim data as byte)
Description Immediately transmits data.
Requires Soft SPI must be initialized and communication established before using this function.See Soft_Spi_Init.
Example Soft_Spi_Write(1)
Soft_Spi_Write
Library Example
program soft_spi_testdim value as word
sub procedure Dac_Output(dim out_value as word)dim tmp as word
LATB = PORTB and 0xFEtmp = 0x3000 + out_valueDelay_ms(1)Spi1_Write(tmp)Delay_ms(50)LATB = PORTB or 1
end sub
main:ADPCFG = 0xFFFFTRISB = TRISB and 0xFE ' CS pin is on the LATB.1Soft_Spi_Init(LATB.2, LATB.3, LATB.6, 7, _SOFT_SPI_IDLE_HI,
_SOFT_SPI_LO_2_HI, _SOFT_SPI_MODE_16)while TRUE
value = 1while value < 0x3FF
Dac_Output(value)Delay_ms(500)Inc(value)
wendwend
end.
mikroBasic provides library which implements software UART. These routines arehardware independent and can be used with any MCU. You can easily communi-cate with other devices via RS-232 protocol – simply use the functions listedbelow.
Note: This library implements time-based activities, so interrupts need to be dis-abled when using Soft UART.
Soft_Uart_InitSoft_Uart_ReadSoft_Uart_Write
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 155page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Software UART Library
Library Routines
Prototype sub procedure Soft_Uart_Init(dim byref rx, tx as bit, dim baud,inverted, stop_bits as word)
Description Initalizes software UART. Parameters rx and tx specify the RX and TX pins (the twocannot point at the same pin). Parameter baud is the desired baud rate. Maximum baudrate depends on dsPIC’s clock and working conditions. Parameter inverted, if set tonon-zero value, indicates inverted logic on output. Parameter stop_bits specifies thenumber of stop bits, and can take the following values:
const _UART_ONE_STOPBIT = 0 ' for 1 stop bitconst _UART_TWO_STOPBITS = 1 ' for 2 stop bits
Soft_Uart_Init needs to be called before using other routines of this library.
Example This will initialize software UART and establish the communication at 57,600 bps:
Soft_Uart_Init(LATF.2, LATF.3, 57600, 0, 0)
Soft_Uart_Init
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
156 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub function Soft_Uart_Read(dim byref error as byte) as byte
Returns Returns a received byte.
Description Function receives a byte via software UART. Parameter error will be zero if the transfer was successful. This is a non-blocking function call, so you should test theerror manually (check the example below).
Requires Soft UART must be initialized and communication established before using this func-tion. See Soft_Uart_Init.
Example ' Here's a loop which holds until some data’s been received:error = 1do
data = Soft_Uart_Read(error)loop until error <> 0
Soft_Uart_Read
Prototype sub procedure Soft_Uart_Write(dim data as byte)
Description Function transmits a byte (data) via UART.
Requires Soft UART must be initialized and communication established before using this func-tion. See Soft_Uart_Init.
Be aware that during transmission, software UART is incapable of receiving data – datatransfer protocol must be set in such a way to prevent loss of information.
Example Soft_Uart_Write(0x0A)
Soft_Uart_Write
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 157page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Library Example
The example demonstrates a simple data exchange via software UART. When the MCU receivesdata, it immediately sends it back. If dsPIC is connected to the PC, you can test the example fromthe mikroBasic terminal for RS-232 communication, menu item Tools > Terminal.
program soft_uart_test
dim rx, err as word
main:ADPCFG = 0xFFFFSoft_Uart_Init(LATF.2, LATF.3, 57600, 0, 0)
while TRUErx = Soft_Uart_Read(err)Soft_Uart_Write(rx)
wend
end.
SPI module is available with all dsPICmicros. mikroBasic provides a library forinitializing Slave mode and comfortable work with Master mode. dsPIC can easilycommunicate with other devices via SPI: A/D converters, D/A converters,MAX7219, LTC1290, etc.
Important: When using SPI Library routines, you are required to specify the actualSPI module, either SPI1 or SPI2. Simply append the number 1 or 2 to the wordSpi in a routine name, e.g. Spi2_Init().
If the actual chip has only one module, you would still need to use Spi1_ as pre-fix to the routines. Throughout the documentation, we’ll be referring to moduleSPI1; routines for SPI2 are identical, except for the names. If using the prefixSpi2 with a single module chip, the compiler will report an error.
Spi1_Init Spi1_Init_Advanced Spi1_Data_Ready Spi1_Read Spi1_Write Spi1_Stop
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
158 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
SPI Library
Library Routines
Prototype sub procedure Spi1_Init
Description Configures and initializes SPI with default settings. Spi_Init_Advanced orSpi_Init needs to be called before using other functions from SPI Library. Default set-tings are: Master mode, clock Fosc/4, clock idle state low, data transmitted on low tohigh edge, and input data sampled at the middle of interval.
For a custom configuration, use Spi1_Init_Advanced.
Example Spi1_Init()
Spi1_Init
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 159page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Spi1_Init_Advanced(dim master_mode, mode16,fcy_div, prescaler, slave_ss, data_sample, clock_idle, edge asword)
Description Configures and initializes SPI. Spi1_Init_Advanced or Spi1_Init needs to becalled before using other functions of SPI Library.
Parameter mode determines the work mode for SPI; can have the following values:
const MASTER = 0x20 ' Master modeconst SLAVE = 0x00 ' Slave mode
Parameter fcy_div determines frequency divider (additional prescaler); can have thefollowing values:
const FCY_DIV1 = 0x03 ' frequency divided by 1const FCY_DIV4 = 0x02 ' frequency divided by 4const FCY_DIV16 = 0x01 ' frequency divided by 16const FCY_DIV64 = 0x00 ' frequency divided by 64
Parameter prescale determines frequency divider (base prescaler); can have the fol-lowing values:
const PRESCALE_8 = 0x00 ' prescaler set to 1:8const PRESCALE_7 = 0x04 ' prescaler set to 1:7const PRESCALE_6 = 0x08 ' prescaler set to 1:6const PRESCALE_5 = 0x0C ' prescaler set to 1:5const PRESCALE_4 = 0x10 ' prescaler set to 1:4const PRESCALE_3 = 0x14 ' prescaler set to 1:3const PRESCALE_2 = 0x18 ' prescaler set to 1:2const PRESCALE_1 = 0x1C ' prescaler set to 1:1
Parameter slave_ss enables or disables Slave Select; can have the following values:
const SLAVE_SS_ENABLE = 0x80 ' Slave Select enabledconst SLAVE_SS_DIS = 0x00 ' Slave Select disabled
Parameter data_sample determines when data is sampled; can have the following val-ues:
const DATA_SAMPLE_MIDDLE = 0x200 ' in middle of intervalconst DATA_SAMPLE_END = 0x00 ' at the end of interval
continues ..
Spi1_Init_Advanced
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
160 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Description(continued)
.. continued
Parameter clock_idle determines idle state for clock; can have the following values:
const CLK_IDLE_HIGH = 0x00 ' Clock idle HIGHconst CLK_IDLE_LOW = 0x100 ' Clock idle LOW
Parameter edge can have the following values:
const LOW_2_HIGH = 0x00 ' Data transmit on low to high edgeconst HIGH_2_LOW = 0x40 ' Data transmit on high to low edge
You don’t need to configure ports manually for using the module; library will take careof the initialization.
Example ' 10MHz Fosc -> 2.5MHz Fcy -> Fspi = 4.88KHz:
SPI1_Init_Advanced(_SPI_MASTER, _SPI_8_BIT, _SPI_FCY_DIV64,_SPI_PRESCALE_8, _SPI_SS_DIS, _SPI_DATA_SAMPLE_MIDDLE,_SPI_CLK_IDLE_HIGH, _SPI_IDLE_2_ACTIVE)
Prototype sub function Spi1_Data_Ready as word
Returns Function returns 1 if data is ready or 0 if there is no data on line.
Description Use the function to test if data is ready for transmission.
Requires SPI must be initialized and communication established before using this function. SeeSpi1_Init_Advanced or Spi1_Init.
Example if Spi1_Data_Ready() = 1 thenreceive = Spi1_Read()
end if
Spi1_Data_Ready
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 161page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub function Spi1_Read as word
Returns Returns the received data.
Description Receives data via SPI.
Requires SPI must be initialized and communication established before using this function. SeeSpi_Init_Advanced or Spi_Init.
Example buffer = Spi1_Read()
Spi1_Read
Prototype sub procedure Spi1_Write(dim data as word)
Description Writes 16-bit data to SPIxBUF, and immediately starts the transmission via SPI.
Requires SPI must be initialized and communication established before using this function. SeeSpi_Init_Advanced or Spi_Init.
Example Spi1_Write(0x1A)
Spi1_Write
Prototype sub procedure Spi1_Stop as word
Description Stops the transimission and shuts down the SPI module.
Requires SPI must be initialized and communication established before using this function. SeeSpi_Init_Advanced or Spi_Init.
Example Spi1_Stop()
Spi1_Stop
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
162 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Library Example
The code demonstrates communication with DAC on RB1 via Serial Peripheral Interface, moduleSPI1.
program spi_dac_test
dim value as word
sub procedure Dac_Output(dim value as word)dim loc as word
PORTB = PORTB and 0xFDloc = 0x3000 + valueDelay_ms(10)Spi1_Write(loc)Delay_ms(50)PORTB = PORTB or 2
end sub
main:TRISB = TRISB and 0xFDSpi1_Init()value = 1while value < 0x3FF
Dac_Output(value)Delay_ms(1000)Inc(value)
wend
while TRUEnop
wend
end.
UART hardware module is available with all dsPICmicros. mikroBasic UARTLibrary provides comfortable work with the Asynchronous (full duplex) mode.
Important: When using UART Library routines, you are required to specify theactual module, either UART1 or UART2. Simply append the number 1 or 2 to theword Uart in a routine name, e.g. Uart2_Init(). If the actual chip has only onemodule, you would still need to use Uart1_ as prefix to the routines. Throughoutthe documentation, we’ll be referring to module UART1; routines for UART2 areidentical, except for the names. If using the prefix Uart2_ with a single modulechip, the compiler will return an error.
Uart1_InitUart1_Init_AdvancedUart1_EnableUart1_DisableUart1_Data_ReadyUart1_ReadUart1_Read_TextUart1_Write_CharUart1_Write_Text
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 163page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
UART Library
Library Routines
Prototype sub procedure Uart1_Init(dim baud_rate as longint)
Description Initializes UART module with the desired baud rate, 8 bits, no parity, and one stop bit.Refer to the device data sheet for baud rates allowed for specific Fosc. If you specify theunsupported baud rate, compiler will report an error. For custom configuration, use theUart1_Init_Advanced. The module is automatically enabled by this routine; you arenot required to enable it “manually” with Uart1_Enable.
Requires Uart1_Init or Uart1_Init_Advanced need to be called before using other functionsof the UART Library.
Example ' Initialize HW UART and establish communication at 2400 bps:Uart1_Init(2400)
Uart1_Init
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
164 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure Uart1_Init_Advanced(dim baud_rate as longint, dimparity, stop_bits as word)
Description Initializes UART module with custom settings:
Parameter baud_rate specifies the desired baud rate. Refer to the device data sheet forrates allowed for specific Fosc. If you specify the unsupported baud rate, compiler willreport an error.
Parameter parity specifies the parity, and can take the following values:
_UART_8BIT_NOPARITY = 0x000 ' for 8 bits, no parity_UART_8BIT_EVENPARITY = 0x002 ' for 8 bits, even parity_UART_8BIT_ODDPARITY = 0x004 ' for 8 bits, odd parity_UART_9BIT_NOPARITY = 0x006 ' for 9 bits, no parity
Parameter stop_bits specifies the number of stop bits, and can take the values:
_UART_ONE_STOPBIT = 0x000 ' for 1 stop bit_UART_TWO_STOPBITS = 0x001 ' for 2 stop bits
You don’t need to configure ports manually for using the module; library will take careof the initialization. The module is automatically enabled by this routine; you are notrequired to enable it “manually” with Uart1_Enable.
Requires Uart1_Init or Uart1_Init_Advanced need to be called before using other functionsof the UART Library.
Example ' Initialize hardware UART and establish communication' at 2400 bps, no parity, one stop bit:Uart1_Init_Advanced(2400, _UART_8BIT_NOPARITY, _UART_ONE_STOPBIT)
Uart1_Init_Advanced
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 165page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Uart1_Enable
Description Enables the UART1 module. This is the default state after calling Uart1_Init orUart1_Init_Advanced. Use this routine if you have disabled the module with theUart1_Disable.
Example Uart1_Enable()
Uart1_Enable
Prototype sub procedure Uart1_Disable
Description Disables the UART1 module. All UART1 pins can be used as general I/O pins under thecontrol of their corresponding PORT and TRIS bits.
Example Uart1_Disable()
Uart1_Disable
Prototype sub function Uart1_Data_Ready as word
Returns Function returns 1 if data is ready or 0 if there is no data on line.
Description Use the function to test if data in receive buffer is ready for reading.
Requires Communication must be established before using the function. See Uart1_Init.
Example ' If data is ready, read it:if Uart1_Data_Ready() = 1 then
receive = Uart1_Read()end if
Uart1_Data_Ready
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
166 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub function Uart1_Read as word
Returns Returns the received byte. If byte is not received, returns 0.
Description Function receives a byte via UART. Use the function Uart1_Data_Ready to test if datais ready first.
Requires Communication must be established before using the function. See Uart1_Init.
Example ' If data is ready, read it:if Uart1_Data_Ready() = 1 then
receive = Uart1_Read()end if
Uart1_Read
Prototype sub procedure Uart1_Read_Text(dim byref output, delimiter asstring[20])
Description Reads characters received via USART until the delimiter sequence is detected. The readsequence is stored in the parameter output; delimiter sequence is stored in the parame-ter delimiter. This is a blocking call: the delimiter sequence is expected, otherwisethe procedure exits after 20 recieved characters.
Requires Communication must be established before using the function. See Uart1_Init.
Example ' Read text until the sequence "OK" is received, and send it back
Uart1_Init(9600)delim = "OK"while TRUE
if Uart1_Data_Ready() = 1 thenUart1_Read_Text(txt, delim)Uart1_Write_Text(txt)
end ifwend
Uart1_Read_Text
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 167page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Uart1_Write_Char(dim character as word)
Description Function transmits a character via UART.
Requires Communication must be established before using the function. See Uart1_Init.
Example Uart1_Write_Char("e") ' send character "e" via UART
Uart1_Write_Char
Prototype sub procedure Uart1_Write_Text(dim text as string[20])
Description Function transmits text via UART.
Requires Communication must be established before using the function. See Uart1_Init.
Example Uart1_Write_Char("Hello world!") ' send message via UART
Uart1_Write_Text
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
168 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Library Example
The following example demonstrates simple data exchange via UART. When microcontrollerreceives data, it immediately sends it back. If dsPIC is connected to the PC (see the figure on thefollowing page), you can test the example from the mikroBasic’s terminal for the RS-232 commu-nication, menu item Tools > Terminal.
program Uart_Test
dim text, delimiter as string[15]dim test as word
main:Uart1_Init(9600)delimiter = "stop"
while TRUEif Uart1_Data_Ready() = 1 then
Uart1_Read_Text(text, delimiter) ' only if you send "stop"Uart1_Write_Text(text)
end ifwend
end.
Here’s a simple test for chips with 2 UART modules:
program Uart2_example
dim rx2 as word
main:Uart2_Init(9600)
while TRUEUart2_Write_Text("Proud to be a dsPIC user :-)")Delay_ms(100)
wend
end.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 169page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
SUB-D 9-pin connector
+
+
+
1
2
3
4
5
6
7
8
9
1
2
3
4
5
6
7
8
9
serial cable
(1 to 1)
Receive data (Rx)
Send data (Tx)
+
MAX232
C1+
V+
C1-
C2+
C2-
V-
T2out
R2in R2out
T2in
T1in
R1out
R1in
T1out
GN
D
Vcc
+5V
4.7
uF
4.7uF
4.7
uF
4.7
uF
6MHz
+5V
+5V
10K
Re
se
t
dsP
IC30F2010
RB0
RB2
RB3
RB4
RB5
Vss
OSC1/CLKI
RC15
RC13
RC14
Vdd
RD1
MCLR
RB1
Avss
RE1
RE2
RE3
RE4
RE5
Vdd
Vss
RF2
RF3
RE8
RD0
AVdd
RE0
Hardware Connection
Util library contains miscellaneous routines useful for project development.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
170 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Util Library
Prototype sub function Button(dim byref button_pin as bit, dim time,active_state as word) as word
Description Function eliminates the influence of contact flickering upon pressing a button (debounc-ing). Parameter button_pin specifies the location of the button (e.g. LATB.5); parame-ter time is a debounce period in milliseconds; parameter active_state can be either0 or 1, and it determines if the button is active upon logical zero or logical one.
Example The following example reads RB0, to which the button is connected; on transition from1 to 0 (release of button), PORTD is inverted:
while TRUEif Button(LATB.0, 1, 1) then
oldstate = TRUEend ifif oldstate and Button(LATB.0, 1, 0) then
PORTD = not(PORTD)oldstate = FALSE
end ifwend
Button
mikroBasic Conversions Library provides routines for converting numerals to dec-imal and hexadecimal strings.
You can get text representation of numerical value by passing it to one of the fol-lowing routines:
ByteToStrWordToStrIntToStrLongintToStrWordToHexFloatToStr
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 171page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Conversions Library
Library Routines
Prototype sub procedure ByteToStr(dim input as byte, dim byref output asstring[3])
Description Procedure creates string out of input (lower 8 bits of a 16-bit numerical value).Parameter output accepts the created string. Output string has fixed width of 3 charac-ters, right aligned; remaining positions on the left (if any) are filled with blanks.
Note: the term byte is only an alias for the word type; the routine actually works withthe lower byte of a 16-bit input. See Simple Types for more information.
Example Here’s an example which prints value of a byte variable on LCD:
dim input as bytedim output as string[3]'...main:input = 6ByteToStr(input, output)Lcd_Out_Cp(output) ' Print " 6" (two blanks here) on LCD
ByteToStr
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
172 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure WordToStr(dim input as word, dim byref output asstring[5])
Description Procedure creates string out of input (numerical value of word type). Parameteroutput accepts the created string. Output string has fixed width of 5 characters, rightaligned; remaining positions on the left (if any) are filled with blanks.
Example Here’s an example which prints value of a word variable on LCD:
dim input as worddim output as string[5]'...main:input = 437WordToStr(input, output)Lcd_Out_Cp(output) ' Print " 437" (two blanks here) on LCD
WordToStr
Prototype sub procedure IntToStr(dim input as integer, dim byref output asstring[6])
Description Procedure creates string out of input (numerical value of integer type). Parameteroutput accepts the created string. Output string has fixed width of 6 characters, rightaligned; remaining positions on the left (if any) are filled with blanks.
Example Here’s an example which prints value of an integer variable on LCD:
dim input as integerdim output as string[6]'...main:input = -4220IntToStr(input, output)Lcd_Out_Cp(output) ' Print " -4220" (one blank here) on LCD
IntToStr
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 173page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure LongintToStr(dim input as longint, dim byref outputas string[11])
Description Procedure creates string out of input (numerical value of longint type). Parameteroutput accepts the created string. Output string has fixed width of 11 characters, rightaligned; remaining positions on the left (if any) are filled with blanks.
Example Here’s an example which prints value of a longint variable on LCD:
dim input as longintdim output as string[11]'...main:input = -12345678LongintToStr(input, output)Lcd_Out_Cp(output) ' Print " -12345678" on LCD (2 blanks here)
LongintToStr
Prototype sub procedure WordToHex(dim input as word, dim byref output asstring[4])
Description Procedure creates string of hexadecimal digits out of input (numerical value of wordtype). Parameter output accepts the created string. Output string has fixed width of 4characters, right aligned; remaining positions on the left (if any) are filled with zeroes.
Example Here’s an example which prints value of a word variable on LCD:
dim input as worddim output as string[4]'...main:input = 26WordToHex(input, output)Lcd_Out_Cp(output) ' Print "001A" on LCD
WordToHex
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
174 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure FloatToStr(dim input as float, dim byref output asstring[17])
Description Procedure creates string out of the input parameter, which should be a floating pointnumber in the longint range (±2147483648). Parameter output accepts the createdstring. The result is given in format "integer.fraction", left aligned.
Note: Procedure won’t return the correct result if input exceeds the longint range!You’ll need to create a custom routine if you want to handle such large numbers.
The integer part has flexible width of up to 11 characters (10 digits + sign). If theactual integer part is shorter than that, string will wrap to the integer’s length. Thefraction part is always 5 characters long. If the actual fraction is shorter than 5 digits,remaining chars on the right will be filled with zeroes; if the fraction exceeds 5 digits,the fraction part will be trimmed.
Requires If you want to use the FloatToStr for printing on LCD, ensure that your programclears/refreshes the display with each printing of a string. Otherwise, LCD will displaythe remnants (rightmost digits) of the previous string, if it was longer than the presentlydisplayed one.
Example // An example which prints value of a float variable on LCD:dim input as floatdim output as string[17]main:input = -3.1415FloatToStr(input, output)Lcd_Out_Cp(output) ' Print "-3.14150" on LCD
FloatToStr
mikroBasic provides a set of library functions for floating point math handling.
acosasinatanatan2ceilcoscoshexpfabsfloorfrexpldexploglog10modfpowpowersinsinhsqrttantanh
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 175page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Math Library
Library Routines
Prototype sub function acos(dim x as float) as float
Description Function returns the arc cosine of parameter x; that is, the value whose cosine is x.Input parameter x must be between -1 and 1 (inclusive). The return value is in radians,between 0 and pi (inclusive).
acos
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
176 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub function asin(dim x as float) as float
Description Function returns the arc sine of parameter x; that is, the value whose sine is x. Inputparameter x must be between -1 and 1 (inclusive). The return value is in radians,between -pi/2 and pi/2 (inclusive).
asin
Prototype sub function atan(dim x as float) as float
Description Function computes the arc tangent of parameter x; that is, the value whose tangent is x.The return value is in radians, between -pi/2 and pi/2 (inclusive).
atan
Prototype sub function atan2(dim x, y as float) as float
Description This is the two argument arc tangent function. It is similar to computing the arc tangentof y/x, except that the signs of both arguments are used to determine the quadrant ofthe result, and x is permitted to be zero. The return value is in radians, between -pi andpi (inclusive).
atan2
Prototype sub function ceil(dim num as float) as float
Description Function returns value of parameter num rounded up to the next whole number.
ceil
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 177page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub function cos(dim x as float) as float
Description Function returns the cosine of x in radians. The return value is from -1 to 1.
cos
Prototype sub function cosh(dim x as float) as float
Description Function returns the hyperbolic cosine of x, defined mathematically as (ex+e-x)/2. Ifthe value of x is too large (if overflow occurs), the function fails.
cosh
Prototype sub function exp(dim x as float) as float
Description Function returns the value of e — the base of natural logarithms — raised to the powerof x (i.e. ex).
exp
Prototype sub function fabs(dim num as float) as float
Description Function returns the absolute (i.e. positive) value of num.
fabs
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
178 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub function floor(dim num as float) as float
Description Function returns value of parameter num rounded down to the nearest integer.
floor
Prototype sub function frexp(dim num as float, dim byref n as integer) asfloat
Description Function splits a floating-point value num into a normalized fraction and an integralpower of 2. Return value is the normalized fraction, and the integer exponent is stored inthe parameter n.
frexp
Prototype sub function ldexp(dim num as float, dim n as integer) as float
Description Function returns the result of multiplying the floating-point number num by 2 raised tothe power n (i.e. returns x*2n).
ldexp
Prototype sub function log(dim x as float) as float
Description Function returns the natural logarithm of x (i.e. loge(x)).
log
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 179page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub function log10(dim x as float) as float
Description Function returns the base-10 logarithm of x (i.e. log10(x)).
log10
Prototype sub function modf(dim num as float, dim byref whole as float) asfloat
Description Function returns the signed fractional component of num, placing its whole numbercomponent into the variable pointed to by whole.
modf
Prototype sub function pow(dim x, y as float) as float
Description Function returns the value of x raised to the power of y (i.e. xy). If the x is negative,function will automatically cast the y into unsigned long.
pow
Prototype sub function sin(dim x as float) as float
Description Function returns the sine of x in radians. The return value is from -1 to 1.
sin
Prototype sub function power(dim x, y as longint) as longint
Description Function returns the value of an integer x raised to the power of y (i.e. xy).
power
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
180 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub function sinh(dim x as float) as float
Description Function returns the hyperbolic sine of x, defined mathematically as (ex-e-x)/2. If thevalue of x is too large (if overflow occurs), the function fails.
sinh
Prototype sub function sqrt(dim num as float) as float
Description Function returns the non negative square root of num.
sqrt
Prototype sub function tan(dim x as float) as float
Description Function returns the tangent of x in radians. The return value spans the allowed range offloating point in mikroBasic.
tan
Prototype sub function tanh(dim x as float) as float
Description Function returns the hyperbolic tangent of x, defined mathematically assinh(x)/cosh(x).
tanh
mikroBasic provides a basic utility routines for creating software delay. You cancreate more advanced and flexible versions based on this library.
Note: Routines do not provide an entirely accurate delay as it depends on theclock specified in the Project settings.
Delay_usDelay_msDelay_usExDelay_msExDelay_Cyc
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 181page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Delays Library
Prototype sub procedure Delay_us(const time_us as word)
Description Causes a software delay in duration of time_us microseconds (a constant). Range ofapplicable constants depends on the oscillator frequency.
Example Delay_us(10) ' Ten microseconds pause
Delay_us
Library Routines
Prototype sub procedure Delay_ms(const time_ms as word)
Description Causes a software delay in duration of time_ms milliseconds (a constant). Range ofapplicable constants depends on the oscillator frequency.
Example Delay_ms(1000) ' One second pause
Delay_ms
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
182 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure Delay_usEx(dim time_us as word)
Description Causes a blocking, interruptable delay in duration of time_us microseconds.
The delay is performed by counting cycles. The number of cycles is obtained by the fol-lowing formula:NoCyc = (Clock_Mhz * time_us) / 4
Also, the number of cycles is given by a multiple of 16384:NoCyc = w0 * 16384 + w1
Combining the two:w0 = NoCyc div 16384, w1 = NoCyc mod 16384
Short delay on slower clock causes larger error.
Maximum delay is obtained from the formula:MaxTime_us = 0x3FFFC / Clock_Mhz
and is given by the following table:
Clock[MHz] | Max_Time[us]-------------------------
4 | 655356 | 436908 | 32767
10 | 2621412 | 2184514 | 1872416 | 1638320 | 1310724 | 1092240 | 655364 | 409680 | 409696 | 2730
120 | 2184
Requires Allowed range for time_us is 20..65535; values out of the given range will generateunpredictable delays.
Example Delay_usEx(100)
Delay_usEx
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 183page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Delay_msEx(dim time_ms as word)
Description Causes a blocking, interruptable delay in duration of time_ms milliseconds.
The delay is performed by counting cycles. The number of cycles is obtained by the fol-lowing formula:NoCyc = (Clock_Khz * time_ms) / 4
Also, the number of cycles is given by a multiple of 16384:NoCyc = w0 * 16384 + w1
Combining the two:w0 = NoCyc div 16384, w1 = NoCyc mod 16384
Short delay on slower clock causes larger error.
Example Delay_ms(1000)
Delay_msEx
Prototype sub procedure Delay_Cyc(dim x, y as word)
Description Causes a blocking, interruptable delay of NoCyc cycles, whereNoCyc = x * 16384 + y.
Example Delay_Cyc(10, 5)
Delay_Cyc
mikroBasic includes a library which automatizes string related tasks.
MemchrMemcmpMemcpyMemmoveMemsetStrcatStrchrStrcmpStrcpyStrcspnStrlenStrncatStrncmpStrncpyStrpbrkStrrchrStrspnStrstr
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
184 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
String Library
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 185page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub function Memchr(dim p as word, dim ch as char, dim n as word)as word;
Description Function locates the first occurrence of byte ch in the initial n bytes of memory areastarting at the address p. Function returns the offset of this occurrence from the memoryaddress p or $FFFF if the character was not found.
For parameter p you can use either a numerical value (literal/variable/constant) indicat-ing memory address or a dereferenced value of an object, for example @mystring or@PORTB.
Memchr
Prototype sub function Memcmp(dim p1, p2, n as word) as integer;
Description Function returns a positive, negative, or zero value indicating the relationship of first nbytes of memory areas starting at addresses p1 and p2.
The Memcmp function compares two memory areas starting at addresses p1 and p2 for nbytes and returns a value indicating their relationship as follows:
Value Meaning< 0 p1 "less than" p2= 0 p1 "equal to" p2> 0 p1 "greater than" p2
The value returned by function is determined by the difference between the values of thefirst pair of bytes that differ in the strings being compared.
For parameters p1 and p2 you can use either a numerical value (literal/variable/con-stant) indicating memory address or a dereferenced value of an object, for example@mystring or @PORTB.
Memcmp
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
186 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure Memcpy(dim p1, p2, n as word);
Description Function copies n bytes from the memory area starting at the address p2 to the memoryarea starting at p1. If these memory buffers overlap, the memcpy function cannot guar-antee that bytes are copied before being overwritten. If these buffers do overlap, use theMemmove function.
For parameters p1 and p2 you can use either a numerical value (literal/variable/con-stant) indicating memory address or a dereferenced value of an object, for example@mystring or @PORTB.
Memcpy
Prototype sub procedure Memmove(dim p1, p2, n as word);
Description Function copies n bytes from the memory area starting at the address p2 to the memoryarea starting at p1. If these memory buffers overlap, the Memmove function ensures thatbytes in p2 are copied to p1 before being overwritten.
For parameters p1 and p2 you can use either a numerical value (literal/variable/con-stant) indicating memory address or a dereferenced value of an object, for example@mystring or @PORTB.
Memmove
Prototype sub procedure Memset(dim p as word, dim ch as char, dim n asword);
Description Function fills the first n bytes in the memory area starting at the address p with thevalue of byte ch.
For parameter p you can use either a numerical value (literal/variable/constant) indicat-ing memory address or a dereferenced value of an object, for example @mystring or@PORTB.
Memset
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 187page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Strcat(dim byref s1, s2 as string[100]);
Description Function appends the value of string s2 to string s1 and terminates s1 with a null char-acter.
Strcat
Prototype sub function Strchr(dim byref s as string[100], dim ch as char)as word;
Description Function searches the string s for the first occurrence of the character ch. The null char-acter terminating s is not included in the search.
Function returns the position (index) of the first character ch found in s; if no matchingcharacter was found, function returns $FFFF.
Strchr
Prototype sub function Strcmp(dim byref s1, s2 as string[100]) as word;
Description Function lexicographically compares the contents of strings s1 and s2 and returns avalue indicating their relationship:
Value Meaning< 0 s1 "less than" s2= 0 s1 "equal to" s2> 0 s1 "greater than" s2
The value returned by function is determined by the difference between the values of thefirst pair of bytes that differ in the strings being compared.
Strcmp
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
188 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure Strcpy(dim byref s1, s2 as string[100]);
Description Function copies the value of string s2 to the string s1 and appends a null character tothe end of s1.
Strcpy
Prototype sub function Strcspn(dim byref s1, s2 as string[100]) as word;
Description Function searches the string s1 for any of the characters in the string s2.
Function returns the index of the first character located in s1 that matches any characterin s2. If the first character in s1 matches a character in s2, a value of 0 is returned. Ifthere are no matching characters in s1, the length of the string is returned (not includingthe terminating null character).
Strcspn
Prototype sub function Strlen(dim byref s as string[100]) as word;
Description Function returns the length, in words, of the string s. The length does not include thenull terminating character.
Strlen
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 189page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Strncat(dim byref s1, s2 as string[100]; n asword);
Description Function appends at most n characters from the string s2 to the string s1 and terminatess1 with a null character. If s2 is shorter than n characters, s2 is copied up to andincluding the null terminating character.
Strncat
Prototype sub function Strncmp(dim byref s1, s2 as string[100], dim n asword) as integer;
Description Function lexicographically compares the first n bytes of the strings s1 and s2 andreturns a value indicating their relationship:
Value Meaning< 0 s1 "less than" s2= 0 s1 "equal to" s2> 0 s1 "greater than" s2
The value returned by function is determined by the difference between the values of thefirst pair of bytes that differ in the strings being compared (within first n bytes).
Strncmp
Prototype sub procedure Strncpy(dim byref s1, s2 as string[100], dim n asword);
Description Function copies at most n characters from the string s2 to the string s1. If s2 containsfewer characters than n, s1 is padded out with null characters up to the total length of ncharacters.
Strncpy
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
190 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure Strpbrk(dim byref s1, s2 as string[100]);
Description Function searches s1 for the first occurrence of any character from the string s2. Thenull terminator is not included in the search. Function returns an index of the matchingcharacter in s1. If s1 contains no characters from s2, function returns $FFFF.
Strpbrk
Prototype sub function Strrchr(dim byref s as string[100], dim ch as char)as word;
Description Function searches the string s for the last occurrence of character ch. The null characterterminating s is not included in the search. Function returns an index of the lastch found in s; if no matching character was found, function returns $FFFF.
Strrchr
Prototype sub function Strspn(dim byref s1, s2 as string[100]) as word;
Description Function searches the string s1 for characters not found in the s2 string.
Function returns the index of first character located in s1 that does not match a characterin s2. If the first character in s1 does not match a character in s2, a value of 0 isreturned. If all characters in s1 are found in s2, the length of s1 is returned (not includ-ing the terminating null character).
Strspn
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 191page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
DSP Library
Library Routines :
mikroBasic includes a libraries for DSP engine.
FIR_Radix IIR_RadixFFTIFFTBitReverseComplex Vector_Set VectorPower Vector_Subtract VectorScale Vector_Negate Vector_Multiply Vector_Min Vector_Max Vector_Dot Vector_Correlate Vector_Convolve Vector_Add Matrix_Transponse Matrix_Subtract Matrix_Scale Matrix_Multiply Matrix_Add
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
192 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub function FIR_Radix(dim FilterOrder as Word, dim ptrCoeffs asLongInt, dim BuffLength as Word, dim ptrInput as Word, dim Indexas Word)as Word;
Description This function applies FIR filter to ptrInput. Input samples must be in Y data space.FilterOrder is order of the filter + 1.ptrCoeffs is address of filter coeffitients in program memory.BuffLength represents number of samples ptrInput points to.ptrInput is address of input samples. Index index of current sample.
Returns sum(k=0..N-1)(coef[k]*input[N-k]) - Current sample of processedsignal(B[n]) N - buffer length k - Current index
FIR_Radix
Prototype sub function IIR_Radix(dim BScale as Integer, dim AScale asInteger, dim ptrB as LongInt, dim ptrA as LongInt, dimFilterOrder as Word, dim ptrInput as Word, dim Input_Len as Word,dim ptrOutput as Word, dim Index as Word)as Word;
Description This function applies IIR filter to ptrInput. Input and output samples must be in Y dataspace.AScale A Scale factorBScale B Scale factorptrB Address of B coefficients (In program memory)ptrA Address of A coefficients (In program memory)FilterOrder is order of the filter + 1.ptrInput is address of input samples. Input_Len represents number of samples ptrInputpoints to.ptrOutput is address of output samples. Output length is equal to Input length. Index index of current sample.
Returns y[n]=sum(k=0..N)(Acoef[k]*x[n-k]) - sum(k=1..M)(Bcoef[k]*y[n-k])
IIR_Radix
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 193page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure FFT(dim log2N as word, dim TwiddleFactorsAddress as LongInt, dimbyref Samples as array[1024] of word);
Description Function applies FFT transformation to input samples, input samples must be in Y dataspace.N - buffer length (must be the power of 2).TwiddleFactorsAddress is address of costant array which contains complex twiddle fac-tors.The array is expected to be in program memory.Samples - array of input samples.Upon completion complex array of FFT samples is placed in the Samples parameter.
Operation F(k) = 1/N*sum_n (f(n)*WN(kn)), WN(kn) = exp[-(j*2*pi*k*n)/N]Fn - array of complex input samplesn in {0, 1,... , N-1}, and k in {0, 1,... , N-1}, with N = 2^m, melement of Z.WN - TwiddleFactors
The amplitude of current FFT sample is calculated as:F[k]=sqrt(Re[k]^2+ Im[k]^2)
Note Complex array of FFT samples is placed in Samples parameter. Input Samples arearranged in manner Re,Im,Re,Im... (where Im is always zero). Output samples arearranged in the same manner but Im parts are different from zero. Output samples aresymmetrical (First half of output samples (index from 0 to N/2) is identical as secondhalf 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 ofeach of its elements is less than 0.5. If greater or equal to this value the results couldproduce saturation. Note that the output values are scaled by a factor of 1/N, with N thelength of the FFT. input is expected in natural ordering, while output is produced in bitreverse ordering.
FFT
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
194 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure IFFT(dim log2N as word, dim TwiddleFactorsAddress as LongInt,dim byref Samples as array[1024] of word);
Description Function applies IFFT transformation to input samples, input samples must be in Y dataspace.N - buffer length (must be the power of 2).TwiddleFactorsAddress is address of costant array which contains complex twiddle fac-tors.The array is expected to be in program memory.Samples array of input samples.Upon completion complex array of IFFT samples is placed in the Samples parameter.
Operation f(k) = 1/N*sum_n (F(n)*WN(kn)), WN(kn) = exp[(j*2*pi*k*n)/N]Fn - array of complex input samplesn in {0, 1,... , N-1}, and k in {0, 1,... , N-1}, with N = 2^m, m element of Z.WN - TwiddleFactors
Note Complex array of IFFT samples is placed in Samples parameter. Input Samples arearranged in manner Re,Im,Re,Im... (where Im is always zero).
Input data is a complex vector such that the magnitude of the real and imaginary parts ofeach of its elements is less than 0.5. If greater or equal to this value the results couldproduce saturation. Note that the output values are scaled by a factor of 1/N, with N thelength of the IFFT. Input is expected in bit reverse ordering, while output is produced innatural ordering.
IFFT
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 195page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure BitReverseComplex(dim log2N as word, dim byref ReIm asarray[1024] of word);
Description This function does Complex (in-place) Bit Reverse re-organization.N - buffer length (must be the power of 2).ReIm - Output Sample(from FFT).
Operation f(k) = 1/N*sum_n (F(n)*WN(kn)), WN(kn) = exp[(j*2*pi*k*n)/N]Fn - array of complex input samplesn in {0, 1,... , N-1}, and k in {0, 1,... , N-1}, with N = 2^m, m element of Z.WN - TwiddleFactors
Note Input samples must be in Y data space.
BitReverseComplex
Prototype sub procedure Vector_Set(dim byref input as array[1024] of word, dim size, value asword);
Description Sets size elements of input to value, starting from the first element.Size must be > 0. Length of input is limited by available ram.
Vector_Set
Prototype sub function VectorPower(dim N as word, dim byref Vector as array[1024] of word)as word;
Description Function returns result of power value (powVal) in radix point 1.15
Operation powVal = sum (srcV[n] * srcV[n]) with n in {0, 1,... , numElems-1}
Input Input samples must be in Y data space.
Note AccuA used, not restoredCORCON saved, used, restored
VectorPower
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
196 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure Vector_Subtract(dim byref dest, v1, v2 as array[1024] of word, dimnumElems as word);
Description This procedure does substraction of two vectors. numElems must be less or equal tominimum size of two vectors.v1 - First Vectorv2 - Second Vectordest - Result Vector
Operation dstV[n] = srcV1[n] - srcV2[n]with n in {0, 1,... , numElems-1}
Note AccuA used, not restored.CORCON saved, used, restored.
Vector_Subtract
Prototype sub procedure VectorScale(dim N as word, dim ScaleValue as integer, dim byrefSrcVector, DestVector as array[1024] of word);
Description This procedure does vector scaling with scale value.N - Buffer lengthSrcVector - original vectorDestVector - scaled vectorScaleValue - Scale Value
Operation dstV[n] = sclVal * srcV[n], with n in {0, 1,... , numElems-1}
Note AccuA used, not restored.CORCON saved, used, restored
VectorScale
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 197page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Vector_Negate(dim byref srcVector, DestVector as array[1024] ofword ,dim numElems as word);
Description This procedure does negation of vector.srcVector - Original vector destVector - Result vector numElems - Number of Elements
Operation dstV[n] = (-1)*srcV1[n] + 0, 0 <= n < numElems
Note Negate of 0x8000 is 0x7FFF.AccuA used, not restored.CORCON saved, used, restored.
Vector_Negate
Prototype sub procedure Vector_Multiply(dim byref v1, v2, dest as array[1024] of word, dimnumElems as word);
Description This procedure does multiplication of two vectors.numElems must be less or equal to minimum size of two vectors.v1 - First Vectorv2 - Second Vectordest - Result Vector
Operation dstV[n] = srcV1[n] * srcV2[n]with n in {0, 1,... , numElems-1}
Note AccuA used, not restored.CORCON saved, used, restored
Vector_Multiply
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
198 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub function Vector_Min(dim byref Vector as array[1024] of word, dim numElems asword, dim byref MinIndex as word) as word;
Description This function find min. value in vector.Vector - Original vector.numElems - Number of elementsMinIndex - Index of minimum value
Operation minVal = min {srcV[n], n in {0, 1,...numElems-1}if srcV[i] = srcV[j] = minVal, and i < j, then minIndex = j
Returns minimum value (minVal)
Vector_Min
Prototype sub function Vector_Max(dim byref Vector as array[1024] of word, dim numElemsas word, dim byref MaxIndex as word)as word;
Description This function find max. value in vector.Vector - Original vector.numElems - Number of elementsMaxIndex - Index of maximum value
Operation maxVal = max {srcV[n], n in {0, 1,...numElems-1} }if srcV[i] = srcV[j] = maxVal, and i < j, then maxIndex = j
Returns maximum value (maxVal)
Vector_Max
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 199page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub function Vector_Dot(dim byref v1, v2 as array[1024] of word, dim numElems asword) as word;
Description Procedure calculates vector dot product.v1 - First vector.v2 - Second vectornumElems - Number of elements
Operation dotVal = sum (srcV1[n] * srcV2[n]),with n in {0, 1,... , numElems-1}
Note AccuA used, not restored.CORCON saved, used, restored.
Vector_Dot
Prototype sub procedure Vector_Correlate(dim byref v1, v2, dest as array[1024] of word, dimnumElemsV1, numElemsV2 as word);
Description Procedure calculates Vector correlation (using convolution).v1 - First vector.v2 - Second vectornumElemsV1 - Number of first vector elementsnumElemsV2 - Number of second vector elementsdest - Result vector
Operation r[n] = sum_(k=0:N-1){x[k]*y[k+n]}, where:x[n] defined for 0 <= n < N,y[n] defined for 0 <= n < M, (M <= N),r[n] defined for 0 <= n < N+M-1.
Vector_Correlate
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
200 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Prototype sub procedure Vector_Convolve(dim byref v1, v2, dest as array[1024] of word, dimnumElemsV1, numElemsV2 as word);
Description Procedure calculates Vector using convolution.v1 - First vector.v2 - Second vectornumElemsV1 - Number of first vector elementsnumElemsV2 - Number of second vector elementsdest - Result vector
Operation y[n] = sum_(k=0:n){x[k]*h[n-k]}, 0 <= n < My[n] = sum_(k=n-M+1:n){x[k]*h[n-k]}, M <= n < Ny[n] = sum_(k=n-M+1:N-1){x[k]*h[n-k]}, N <= n < N+M-1
Note AccuA used, not restored.CORCON saved, used, restored.
Vector_Convolve
Prototype sub procedure Vector_Add(dim byref dest, v1, v2 as array[1024] of word, dimnumElems as word);
Description Procedure calculates vector addition.v1 - First vector.v2 - Second vectornumElemsV1 - Number of vector elementsdest - Result vector
Operation dstV[n] = srcV1[n] + srcV2[n],with n in {0, 1,... , numElems-1}
Note AccuA used, not restored.CORCON saved, used, restored.
Vector_Add
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 201page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Prototype sub procedure Matrix_Transponse(dim byref src, dest as array[1024]of word, dimnumRows, numCols as word);
Description Procedure does matrix transposition.src - Original matrix.dest - Result matrixnumRows - Number of matrix rowsnumCols - Number of matrix columns
Operation dstM[i][j] = srcM[j][i]
Matrix_Transponse
Matrix_Subtract
Prototype sub procedure Matrix_Subtract(dim byref src1, src2, dest as array[1024] of word,dim numRows, numCols as word);
Description Procedure does matrix substraction.src1 - First matrix.src2 - Second matrixdest - Result matrixnumRows - Number of matrix rowsnumCols - Number of matrix columns
Operation dstM[i][j] = srcM1[i][j] - srcM2[i][j]
Note AccuA used, not restored.AccuB used, not restored.CORCON saved, used, restored.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
202 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
Matrix_Scale
Prototype sub procedure Matrix_Scale(dim ScaleValue as word, dim byref src1, dest asarray[1024] of word, dim numRows, numCols as word);
Description Procedure does matrix scale.ScaleValue - Scale Valuesrc1 - Original matrixdest - Result matrixnumRows - Number of matrix rowsnumCols - Number of matrix columns
Operation dstM[i][j] = srcM[j][i]
Note AccuA used, not restored.CORCON saved, used, restored.
Matrix_Multiply
Prototype sub procedure Matrix_Multiply(dim byref src1, src2, dest as array[1024] of word,dim numRows1, numCols2, numCols1Rows2 as word);
Description Procedure does matrix multiply.src1 - First Matrixsrc2 - Second Matrixdest - Result MatrixnumRows1 - Number of first matrix rowsnumCols2 - Number of second matrix columnsnumCols1Rows2 - Number of first matrix columns and second matrix rows
Operation dstM[i][j] = sum_k(srcM1[i][k]*srcM2[k][j]),withi in {0, 1, ..., numRows1-1}j in {0, 1, ..., numCols2-1}k in {0, 1, ..., numCols1Rows2-1}
Note AccuA used, not restored.CORCON saved, used, restored.
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 203page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
Matrix_Add
Prototype procedure Matrix_Add(dim byref src1, src2, dest as array[1024] of word, dimnumRows, numCols as word);
Description Procedure does matrix addition.src1 - First Matrixsrc2 - Second Matrixdest - Result MatrixnumRows1 - Number of first matrix rowsnumCols2 - Number of second matrix columns
Operation dstM[i][j] = srcM1[i][j] + srcM2[i][j]
Note AccuA used, not restored.CORCON saved, used, restored.
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...
204 mikroElektronika: DDevelopment ttools - BBooks - CCompilers
page
If you are experiencing problems with any of our products or you just want addi-tional information, please let us know.
Technical Support for the compiler
If you are experiencing any trouble with mikroBasic, please do not hesitate tocontact us - it is in our mutual interest to solve these issues.
Discount for schools and universities
mikroElektronika offers a special discount for educational institutions. If youwould like to purchase mikroBasic for purely educational purposes, please con-tact us.
Problems with transport or delivery
If you want to report a delay in delivery or any other problem concerning distri-bution of our products, please use the link given below.
Would you like to become mikroElektronika's distributor?
We in mikroElektronika are looking forward to new partnerships. If you wouldlike to help us by becoming distributor of our products, please let us know.
Other
If you have any other question, comment or a business proposal, please contactus:
mikroElektronikaAdmirala Geprata 1B11000 BelgradeEUROPE
Phone: + 381 (11) 30 66 377, + 381 (11) 30 66 378Fax: + 381 (11) 30 66 379E-mail: [email protected]: www.mikroelektronika.co.yu
Contact us:
mikroElektronika: DDevelopment ttools - BBooks - CCompilers 205page
BASIC Compiler for Microchip dsPIC microcontrollers
mikroBASIC for dsPICmaking it simple...